0

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...

jpganz18
  • 5,508
  • 17
  • 66
  • 115
  • Maybe first transform it into a `Map` and then do your own mapping, or a complete other way: *Where are you getting that data from*? Can you influence what is done to the JSON before it is sent to you? – Lino Jan 25 '19 at 12:17
  • `name` and `age` are still the properties you look for. `@JsonProperty` is not a class-level annotation, so how do you go about transforming this normally? It should just be the same. – bkis Jan 25 '19 at 12:18
  • thanks @Lino, any concrete example ? – jpganz18 Jan 25 '19 at 12:18
  • thanks @mumpitz, but I actually want to get that ID as well – jpganz18 Jan 25 '19 at 12:19
  • Maybe [this](https://stackoverflow.com/questions/37010891/how-to-map-a-nested-value-to-a-property-using-jackson-annotations) helps? – bkis Jan 25 '19 at 12:23
  • I added more details if that helps... – jpganz18 Jan 25 '19 at 12:39
  • I assumed that you have a `Detail` class which has `Student` field? – Kamil W Jan 25 '19 at 12:51
  • yes, I named it "Student" but when using the constructor with @JsonProperty it doesnt not work – jpganz18 Jan 25 '19 at 12:59

1 Answers1

3

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;
        }
    }
}