Good day!

I'm trying to parse a json string using the gson library. I have this class:

class Foo { int Id; String Name; } 

and, for example, this line:

 {response: [123, { id: 1, name: 'qwerty'}, { id: 2, name: 'asdfgh'}, ]} 

I'm trying to deserialize it like this:

 Gson gson = new Gson(); Foo[] res = gson.fromJson(jsonStr, Foo[].class); 

But when I try to run it, I get an error. The problem here is that the string does not contain an array of json objects, but an object with a response field, which is an array, but I would like to deserialize only the array itself. The second problem is that in the array, besides elements that can be deserialized as objects of the Foo class, there is also a prime number 123, which cannot be deserialized as Foo.

My question is: can I somehow "tell" the deserializer that I want to deserialize only the contents of the response object and that I want to skip the value 123 in the array and not deserialize it? Or do I need to parse a string and somehow select the necessary data in it? I would not like to do it manually.

    1 answer 1

    Try it like this.

    In the parser, pay attention to the use of types when getting a json element and further deserializing it.

    Json example:

     var myJson = { "one": { name: 'Peter', phone: '+375294356674', address: 'Komsomolskaya st.' }, "two": { name: 'Luci', phone: '+79032227898', address: 'Sovetskaya st.' }, "three": { name: 'Jonathan', phone: '+44227895463', address: 'Golubeva st.' }, }; 

    Entity:

     public class TestEntity { private String name; private String phone; private String address; public TestEntity() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } } 

    Parser:

     public class JsonToEntity { public List<TestEntity> getListEntities(String json){ Gson gson = new Gson(); TestEntity entity; List<TestEntity> list = new ArrayList<>(); JsonElement element = new JsonParser().parse(json); Map<String, Object> map = gson.fromJson(json, Map.class); for (String key : map.keySet()) { entity = gson.fromJson(((JsonObject) element).get(key), TestEntity.class); list.add(entity); System.out.println("Information about " + entity.getName() + ":\nPhone: " + entity.getPhone() + "\nAddress: " + entity.getAddress()); } return list; } } 
    • Please try to write more detailed answers. I am sure the author of the question would be grateful for your expert commentary on the code above. - Nicolas Chabanovsky