2

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 
2
  • It's not that complicated. I tried gson but I only got empty objects. Post the code that you tried. You are likely doing something easily resolvable. Commented Mar 20, 2020 at 14:59
  • Updated my post Commented Mar 20, 2020 at 16:18

1 Answer 1

1

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"}
Sign up to request clarification or add additional context in comments.

1 Comment

I don't need it as a JsonObject[], an JsonArray is fine as well. Your code above works, don't know why I couldn't find it out myself, propably becauseI was working for too long. Thx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.