john
john

Reputation: 11669

How to serialize JSON array to a Java Object using GSON?

I have a below JSON document which I need to parse. I am showing only two objects in files array. In general I will have more than 500 objects.

{  
   "files":[  
      {  
         "name":"/testing01/partition_395.shard",
         "max_chain_entries":20,
         "partition":"297, 298",
         "new_users":"123, 345, 12356"
      },
      {  
         "name":"/testing02/partition_791.shard",
         "max_chain_entries":20,
         "partition":"693, 694, 695",
         "new_users":"3345, 6678, 34568"
      }
   ]
}

And here is my DataModel class for above object -

public class JsonResponseTest {
    private String name;
    private String max_chain_entries;
    private String partition;
    private String new_users;

    // getters here
}

I need to extract all the new_users if name tag has /testing01 and populate it in HashSet in Java. I am using GSON for JSON Serialization.

private static RestTemplate restTemplate = new RestTemplate();
private static final Gson gson = new Gson();

public static void main(String[] args) {

    String jsonResponse = restTemplate.getForObject(
            "some_url", String.class);

    Type collectionType = new TypeToken<List<JsonResponseTest>>() {}.getType();
    List<JsonResponseTest> navigation = gson.fromJson(jsonResponse, collectionType);

    System.out.println(navigation);
}

But the above code is giving me error message as -

Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

Anything wrong I am doing here?

Upvotes: 1

Views: 7332

Answers (1)

arsenal
arsenal

Reputation: 24144

Issue is you have a JSON Object first and then JSON Array but you are de-serializing thinking that it is JSON Array. Try below code -

String jsonResponse = restTemplate.getForObject("some_url", String.class);

Type collectionType = new TypeToken<List<JsonResponseTest>>() {}.getType();

JsonObject json = new JsonParser().parse(jsonResponse).getAsJsonObject();
JsonArray jarr = json.getAsJsonObject().getAsJsonArray("files");

List<JsonResponseTest> navigation = gson.fromJson(jarr, collectionType);
System.out.println(navigation);

Upvotes: 2

Related Questions