简体   繁体   中英

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

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>>() {});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM