如何为Jackson编写自定义JSON反序列化器?

问题描述 投票:0回答:2

我需要将一些JSON反序列化为Java类。我有以下JSON:

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

并且我有以下Java类:

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

public class Text extends BaseClass {
   ...
}

public class Image extends BaseClass {
}

并且我需要以这种方式进行反序列化,如果type等于image并且subType等于text,我需要反序列化为Text类,否则我需要反序列化为Image类。

我该怎么办?

java jackson
2个回答
0
投票

您可以像这样实现自己的解串器:

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...) */
        }
    }
}

0
投票

您不需要自定义解串器。用以下注释标记您的BaseClass,然后使用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定义为类型名称使用type字段的值。JsonSubTypes将类型名称与Java类关联

© www.soinside.com 2019 - 2024. All rights reserved.