2

I want to deserialize JSON using Java:

{  
   "Smith":{  
      "id":1,
      "age": 20
   },
   "Carter":{  
      "id":2,
      "age": 21
   }
}

to a list of objects of this class:

class Person {
    private Long id;
    private Integer age;
    private String name; //here I want to have eg. Smith

    //getters and setters
}

How to do this?

Luciano van der Veekens
  • 6,307
  • 4
  • 26
  • 30
Greg Zuber
  • 1,229
  • 1
  • 12
  • 22
  • 2
    You should create a iterator to iterate over all the keys in your json. Then move the "Smith" to a new key inside called name. I have done something similar once. See https://stackoverflow.com/questions/40535188/custom-deserializer-for-realmobject. It might help you – Juxture Oct 03 '17 at 11:43
  • Are you able to change the structure of the JSON? Cause that would be the easiest option – Matt Oct 03 '17 at 12:24
  • 2
    Have a look at this answer with custom Desirializer https://stackoverflow.com/a/42766712/369946 – Matt Oct 03 '17 at 12:28
  • Thank you @Matt this is exactly what I was looking for. After some adjustments it works. – Greg Zuber Oct 03 '17 at 13:06

4 Answers4

0
ObjectMapper map = new ObjectMapper();
String json ="your json here " 
Person person = map.readValue(json, Person.class);

This is the standard method, in your case your json seems bit different , so you have to create a pojo class which is matching to your JSON

0

This would be through mapping, (in this specific case) for instance:

Person myPerson = new ObjectMapper().readValue(YOURJSONHERE, Person.class);

The mapper will map the properties specified in your Person model, to the corresponding fields in the JSON. If you have any problems try looking here

However, the way your JSON is structured suggests it would map to a class 'Smith' or 'Carter', the correct format for using the mapper would therefore be:

{
 "Person":{
     "name":"Smith",
     "id": 1,
     "age": 20
  }
}
Paaz
  • 133
  • 7
  • This doesn't work. The problem is with the name field. Some more custom mapping is required. – Greg Zuber Oct 03 '17 at 11:30
  • That is correct, I overlooked it, check the edit. Your JSON and the class dont match, so that would indeed require custom mapping. – Paaz Oct 03 '17 at 11:38
  • But this is the JSON I'm getting. It's not up to me how it looks like. – Greg Zuber Oct 03 '17 at 11:40
  • In that case, try looking here [link](https://stackoverflow.com/questions/41958263/jackson-mapping-some-fields-of-json-to-inner-fields-of-class) – Paaz Oct 03 '17 at 11:47
0

Using gson is quite simple:

Type type = new TypeToken<List<Person>>() {}.getType();
Gson gson = new GsonBuilder().create();
List<Person> person = gson.fromJson(yourJson, type);
Aldeguer
  • 821
  • 9
  • 32
0

This is a rough working example not following best practices but if you use Jackson elsewhere you should be able to figure it out. You can also register a custom module that can use this same logic for you if its serialized this way in other places as well.

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Test {

    static class Person {
        private Long id;
        private Integer age;
        private String name; //here I want to have eg. Smith

        public Person() {

        }

        public Long getId() {
            return id;
        }
        public void setId(Long id) {
            this.id = id;
        }
        public Integer getAge() {
            return age;
        }
        public void setAge(Integer age) {
            this.age = age;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        @Override
        public String toString() {
            return "Person [id=" + id + ", age=" + age + ", name=" + name + "]";
        }
    }

    public static void main(String[] args) throws JsonProcessingException, IOException {
        String json = "{  \n" +
                "   \"Smith\":{  \n" +
                "      \"id\":1,\n" +
                "      \"age\": 20\n" +
                "   },\n" +
                "   \"Carter\":{  \n" +
                "      \"id\":2,\n" +
                "      \"age\": 21\n" +
                "   }\n" +
                "}";

        ObjectMapper mapper = new ObjectMapper();
        JsonNode nodes = mapper.readTree(json);

        List<Person> people = new ArrayList<>();
        nodes.fields().forEachRemaining(entry -> {
            String name = entry.getKey();
            Person person = mapper.convertValue(entry.getValue(), Person.class);
            person.setName(name);
            people.add(person);
        });

        for (Person person : people) {
            System.out.println(person);
        }
    }
}

Output

Person [id=1, age=20, name=Smith]
Person [id=2, age=21, name=Carter]
Bill O'Neil
  • 556
  • 3
  • 13