java - How to get array of objects from JSON response using GSON -


i writing rest client using resttemplate , gson. below sample of 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 want want values property --> "name"

so created simple pojo has name member field.

public class vmnames {     public string name;      public string getname() {         return name;     }      public void setname(string name) {         this.name = name;     }  } 

and trying use gson array of pojo. here, response json response object.

gson gson = new gson(); vmnames[] vmnamesarray = gson.fromjson(response.getbody(), vmnames[].class); system.out.println(vmnamesarray.length); 

but when this, error i.e. below:

java.lang.illegalstateexception: expected begin_array begin_object @ line 1 column 2 path $

please note don't want create pojo has same structure json object because want 1 attribute out of json object. hoping won't have create pojo same structure json response because, in reality, it's huge response , don't control it, can change tomorrow.

can try this:

public class vmnames {     @serializedname("name")     public string name;      public string getname() {         return name;     }      public void setname(string name) {         this.name = name;     } }  type collectiontype = new typetoken<collection<vmnames>>(){}.gettype(); collection<vmnames> vmnamesarray = gson.fromjson(response.getbody(), collectiontype); system.out.println(vmnamesarray.length); 

or try:

vmnames[] vmnamesarray = gson.fromjson(response.getbody(), vmnames[].class); 

Comments