sunny arya sunny arya - 3 months ago 24
Java Question

How to get array of objects from JSON response using GSON

I am writing a REST client using RestTemplate and GSON.
Below is sample of my JSON response

{
"value": [
{
"properties": {
"vmId": "f7f953fb-d853-4373-b564-",
"hardwareProfile": {
"vmSize": "Standard_D2"
},

},
"name": "A",
"Id": ""
},

{
"properties": {
"vmId": "f7f953fb-d853-4373-b564-",
"hardwareProfile": {
"vmSize": "Standard_D2"
},

},
"name": "B",
"Id": ""
},

{
"properties": {
"vmId": "f7f953fb-d853-4373-b564-",
"hardwareProfile": {
"vmSize": "Standard_D2"
},

},
"name": "C",
"Id": ""
}
]
}


What I want to is that I want to get only the values for the property --> "
name
"

So I created a simple POJO that has only
name
as the member field.

public class VMNames {
public String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}


and I am trying to use the GSON like this to get a array of this POJO. Here, the response is my JSON response object.

Gson gson = new Gson();
VMNames[] vmNamesArray = gson.fromJson(response.getBody(), VMNames[].class);
System.out.println(vmNamesArray.length);


But when I do this, I get an error i.e. as below:


java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $


Please note that I don't want to create a POJO that has exactly same structure as my JSON object because I want to get only one attribute out of my JSON object. I am hoping that I won't have to really create a POJO with the same structure as my JSON response because, in reality, it's a huge response and I don't control it, so it can also change tomorrow.

Answer

So I could get this done. Posting the answer to this so that someone can be benefited tomorrow :)

First thing, i stopped using GSON and started using JSON. And below is the code that helped.

RestTemplate restTemplate = new RestTemplate();

    response = (ResponseEntity<String>) restTemplate.exchange(url, HttpMethod.GET, entity, String.class);

    JSONObject jsonObj = new JSONObject(response.getBody().toString());

    JSONArray c = jsonObj.getJSONArray("value");

    for (int i = 0; i < c.length(); i++) {
        JSONObject obj = c.getJSONObject(i);
        String VMName = obj.getString("name");
        VMNames vmnames = new VMNames();
        vmnames.setName(VMName);
        vmNames.add(vmnames);
    }

return vmNames;

And i get a list of all the value against the attribute name in form of a json array.