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]