I have a JSON:
{
"firstField": "Something One",
"secondField": "Something Two",
"thirdField": [
{
"thirdField_one": "Something Four",
"thirdField_two": "Something Five"
},
{
"thirdField_one": "Something Six",
"thirdField_two": "Something Seven"
}
],
"fifthField": [
{
"fifthField_one": "Something… ",
"fifthField_two": "Something...",
"fifthField_three": 12345
},
{
"fifthField_one": "Something",
"fifthField_two": "Something",
"fifthField_three": 12345
}
]
}
I have my classes:
public static class MyClass {
@JsonProperty
private String firstField, secondField;
@JsonProperty
private ThirdField thirdField;
@JsonProperty
private FifthField fifthField;
public static class ThirdField {
private List<ThirdFieldItem> thirdField;
}
public static class ThirdFieldItem {
private String thirdField_one, thirdField_two;
}
public static class FifthField {
private List<FifthFieldItem> fifthField;
}
public static class FifthFieldItem {
private String fifthField_one, fifthField_two;
private int fifthField_three;
}
}
I’m deserializing them with Jackson library:
public void testJackson() throws IOException {
JsonFactory factory = new JsonFactory();
ObjectMapper mapper = new ObjectMapper(factory);
File from = new File("text.txt"); // JSON I mentioned above
mapper.readValue(from, MyClass.class);
}
but I’m getting the Exception:
org.codehaus.jackson.map.JsonMappingException: Can not deserialize
instance of Main$MyClass$ThirdField out of START_ARRAY token
You defined your
thirdFieldandfifthFieldproperties as arrays in your JSON. They need to be arrays or collections on your Java bean as well:As you are going through and converting an existing JSON object into beans, keep in mind that JSON data is very much like a map. If you envision how you would map the data from a map into your object it really helps. Your
ThirdFieldandFifthFieldobjects need to map the definitions in your JSON. This is what your JSON says aThirdFieldis:Literally converting that to a Java bean gives you:
You can add in your annotations etc, etc to get a full fledged bean. Do the same thing for your
FifthFieldobject.