0

I have a JSON structured like:

{
  "id" : "123",
  "name" : [ {
    "id" : "234",
    "stuff" : [ {
      "id" : "345",
      "name" : "Bob"
    }, {
      "id" : "456",
      "name" : "Sally"
    } ]
  } ]
}

I want to map to the following data structure:

Class01

@Getter
public class Class01{
    private String id;
    @JsonDeserialize(using = Class01HashMapDeserialize.class)
    private ArrayList<Class02> name;
}

Class02

@Getter
public class Class02{
    private String id;
    private ArrayList<Class03> stuff;
}

Class03

@Getter
public class Class03{
    private String id;
    private String name;
}

In my main Method im using an ObjectMapper with objectMapper.readValue(jsonString,new TypeReference<ArrayList<Class02>>(){}) to map this JSON to my Class01. This Class successfully deserealizes the Class02-array into the name array.

When it comes to the second array I don't know how to further deserialize as I am not able to access the json text from the class02 stuff entry.

@Override
public ArrayList<Class02> deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException {
    ArrayList<Class02> ret = new ArrayList<Class02>();

    ObjectCodec codec = parser.getCodec();
    TreeNode classes02 = codec.readTree(parser);

    if (classes02.isArray()) {
        for (JsonNode class02 : (ArrayNode) classes02) {
            if(classe02.get("stuff").isArray()){
                 ObjectMapper objectMapper = new ObjectMapper();
                 ArrayList<Class03> classes03 = objectMapper.readValue(class02.get("stuff").asText(), new TypeReference<ArrayList<Class03>>(){});
            }
            ret.add(new Class02(class02.get("id").asText(), classes03));
        }
    }
    return ret;
}

1 Answer 1

1

Why did you put a @JsonDeserialize annotation ? Jackson shall be able to deserialize it just fine without any custom mapping:

@Getter
public class Class01{
    private String id;
    private ArrayList<Class02> name;
}

Also in a first pass, I would generate the getters/setters/constructor manually for the 3 classes. There may be issues with Lombok & Jackson that you may want to solve later once you made the first version of the code works (Can't make Jackson and Lombok work together)

And your reader shall be more like:

ObjectMapper objectMapper = new ObjectMapper();
String text = ... //Your JSon
Class01 class01 = objectMapper.readValue(text, Class01.class)
Sign up to request clarification or add additional context in comments.

1 Comment

I adjusted the structure of of the program and now jackson is able to automatically deserialize. Thanks for your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.