java json string into json array

Mointy :

I have a JsonArray as a string with multiple JsonObjects in it. Since I am not a java developer I am a little bit confused, since it is so complicated to convert JsonObjects into strings and strings into JsonObjects.

I have this JsonArray as a string.

[{
    "id":"XXXX-XXXX-XXXX-XXXX-XXXX",
    "name":"Name"
},{
    "id":"XXXX-XXXX-XXXX-XXXX-XXXX",
    "name":"Name"
}]

It changes and I don't know what data it includes.

Goal: I need to convert the json string into JsonArray so I can work with. I tried gson but I only got empty objects.

What I tried:

Gson g = new Gson();
JSONObject jsons[] = g.fromJson(JsonString, JSONObject[].class);

Output:

Log.e ( "JSON", Integer.toString(jsons.length)); ---> 2 (Right!)
Log.e ( "JSON", jsons[0].toString()); ---> { } empty Object 
Demetrio :

You have to use JsonArray instead of JsonObject[]. Sample code:

String json = "[{ " + 
              "    \"id\":\"XXXX-XXXX-XXXX-XXXX-XXXX\", " + 
              "    \"name\":\"Name\" " + 
              "},{ " + 
              "    \"id\":\"XXXX-XXXX-XXXX-XXXX-XXXX\", " + 
              "    \"name\":\"Name\" " + 
              "}]";
Gson gson = new Gson();
JsonArray array = gson.fromJson(json,JsonArray.class);
System.out.println(array);

Output:

[{"id":"XXXX-XXXX-XXXX-XXXX-XXXX","name":"Name"},{"id":"XXXX-XXXX-XXXX-XXXX-XXXX","name":"Name"}]

If you want to work with a JsonObject[] you could do something like this:

JsonArray array = gson.fromJson(json,JsonArray.class);
JsonObject[] objects = new JsonObject[array.size()];
for(int i=0;i<array.size();i++)
    objects[i] = array.get(i).getAsJsonObject();
for(JsonObject x : objects)
    System.out.println(x);

Output:

{"id":"XXXX-XXXX-XXXX-XXXX-XXXX","name":"Name"}
{"id":"XXXX-XXXX-XXXX-XXXX-XXXX","name":"Name"}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=336058&siteId=1