jpganz18
jpganz18

Reputation: 5878

how to transform properly a json to object where the key is actually a changing value?

I am wondering how to do this transformation.

I normally transform from json to Java objects like this:

{
    "detail" : 
        {
            "student": {
                "name" : "John Doe",
                "age" : 31
            }
        }

}

So I can easily create a Java object called student and do something like this

public class Student {
String name;
int age;

public Student(@JsonProperty("name") String name, @JsonProperty("age") int age){
    this.name = name;
    this.age = age;
}

}

But now I am facing this issue...

I am getting a JSON like this:

{
       "detail" : 
        {
            "123456789": {
                "name" : "John Doe",
                "age" : 31
            }
        }

}

Where 123456789 is in this case, the "student" ...

Is there anyway I can design an object to parse from JSON to my java object? I have no idea how to do this trick...

Upvotes: 0

Views: 64

Answers (1)

Valery Yakovlev
Valery Yakovlev

Reputation: 31

May be this little example helps?

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.Map;

public class TestJson {

    public static void main(String[] args) throws IOException {
        String json = "    {\n" +
            "        \"123456789\": {\n" +
            "            \"name\" : \"John Doe\",\n" +
            "            \"age\" : 31\n" +
            "        }\n" +
            "    }";

        ObjectMapper objectMapper = new ObjectMapper();

        Map<Long, Student> map = objectMapper.readValue(json, new TypeReference<Map<Long, Student>>() {
        });
    }

    public static class Student {
        private String name;
        private int age;

        public String getName() {
            return name;
        }

        public int getAge() {
            return age;
        }
    }
}

Upvotes: 3

Related Questions