简体   繁体   中英

How to write custom JSON Deserializer for Jackson?

I need to deserialize some JSON to Java class. I have the following JSON:

{
  "list": [[{
        "type": "text",
        "subType": "ss"
     },
     {
        "type": "image",
        "subType": "text"
     }
]]
}

and I have the following Java classes:

public abstract class BaseClass {
    public String type;
    public String subType;
}

public class Text extends BaseClass {
   ...
}

public class Image extends BaseClass {
}

and I need deserialize in this way, if type equals image and subType equals text I need to deserialize into Text class otherwise I need deserialize to Image class.

How can I do it?

You don't need a custom deserializer. Mark your BaseClass with the following annotations, and deserialize with an ObjectMapper:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", visible = true)
@JsonSubTypes({@JsonSubTypes.Type(value = Text.class, name = "text"), @JsonSubTypes.Type(value = Image.class, name = "image")
})
public abstract class BaseClass {
    public String type;
    public String subType;
}

JsonTypeInfo defines to use value of type field for type name. JsonSubTypes associates type names with java classes

You can implement your own deserializer like so:

public class BaseClassDeserializer extends StdDeserializer<BaseClass> { 

    public BaseClassDeserializer(Class<?> vc) { 
        super(vc); 
    }

    @Override
    public BaseClass deserialize(JsonParser jp, DeserializationContext ctxt) 
      throws IOException, JsonProcessingException {
        JsonNode node = jp.getCodec().readTree(jp);
        String type = node.get("type").asText();
        String subType = node.get("subType").asText();

        if("image".equals(type) && "text".equals(subType)){
            /* create Text class
            return new Text */
        } else {
            /* create Image class
            return new Image(args...) */
        }
    }
}

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