How to parse Json in Java?


Hello! There is such a response from the server:

 {
    "p_result": "ok",
    "p_item": [
        {
            "p_id": 132,
            "p_name": "Николай"
        }, 
        {
            "p_id": 133,
            "p_name": "Светлана"
        }
    ]
 }

If I understand correctly, this is an array. You need to write a method that will use the parameter to find the desired element something like:

_http.getArrayParamValue("p_name");

I can't figure it out.

P. s. I think some indication would be more useful for me than a link to the ocherenduyu library. Thanks!

Decision. I also understood the error. @Josfey Thank you so much. You've been very helpful!

String str = null; 
String input = "данные полученные от сервера"; 

JsonParser parser = new JsonParser(); 
JsonObject mainObject = parser.parse(input).getAsJsonObject();
JsonArray pItem = mainObject.getAsJsonArray("p_item"); 

for (JsonElement user : pItem) {

    JsonObject userObject = user.getAsJsonObject(); 
    userObject.get("p_id"); 
    str = userObject.get("p_id").toString(); 
}
Author: maxteneff, 2014-04-14

3 answers

I didn't quite understand what exactly you want to extract from the given json structure, but here, for example, is how to extract the username c id = 132 from it using GSON.

String input = "тут ваша json-структура";
JsonParser parser = new JsonParser();
JsonObject mainObject = parser.parse().getAsJsonObject();
JsonArray pItem = mainObject.getAsJsonArray("p_item");
for (JsonElement user : pItem) {
    JsonObject userObject = user.getAsJsonObject();
    if (userObject.get("p_id").getAsInt() == 132) {
        System.out.println(userObject.get("p_name"));
        return;
    }
}
 6
Author: Jofsey, 2017-11-18 22:39:49

In my opinion, the best library for working with JSON at the moment is Jackson from fasterxml.

I measured the speed of serialization/deserialization using JMH, and this library showed the best results on a fairly complex data structure. In addition, it has a fairly rich set of settings: interning keys, responding to syntax errors, etc.

If you want to not just serialize/deserialize JSON documents, but want to change the structure JSON document on the fly, then I recommend GSON.

 7
Author: a_gura, 2014-04-14 12:52:00

I recommend paying attention to json-simple Here is here is an example of using

 2
Author: anykey, 2014-04-15 14:51:13