mjht
mjht

Reputation: 19

How to use Jackson to deserialize an array of objects when we have written custom deserializer

i have written one custom deserializer , which will take the string and deserialize it public static class MyDeserializer extends JsonDeserializer {

  @Override
  public MyClass deserialize(JsonParser parser,
                                DeserializationContext deserializer) throws IOException {
            Myclass obj = new Myclass();
            while(!parser.isClosed()) {

            JsonToken jsonToken = parser.nextToken();

            if (JsonToken.FIELD_NAME.equals(jsonToken)) {

                String fieldName = parser.getCurrentName();
                System.out.println(fieldName);
                jsonToken = parser.nextToken();

                switch(fieldName) { 
                -----set the fields of obj
                }
               }
            return obj
          }

This can serialize one object at a time , i want to create a list of objects

tried this

    JavaType mapType = MAPPER.getTypeFactory().constructCollectionType(List.class, Myclass.class);
    List <MyClass> mylist = (List<MyClass>)MAPPER.readValue(jsonString,mapType);

This is not working and no error is thrown , just stuck while deserializing it Do we need to split json array and call deserializer for every object or modify the custom deserializer to create list of objects

Upvotes: 1

Views: 485

Answers (1)

mle
mle

Reputation: 2542

Hm, I do not get why there is a need for a custom deserializer at all.

IMHO you could just do:

List <MyClass> mylist = MAPPER.readValue(jsonString, new TypeReference<List<MyClass>>() {});

Upvotes: 0

Related Questions