Json desirialization使用杰克逊与摘要类杰克逊列表

时间:2016-05-11 10:14:26

标签: java json jackson objectmapper

我有像

这样的json结构
{"myobj": { "ford" : [ {"color":"blue","ford_property":"A" } ], "audi": [ {"color":"red", "audi_property":"B"}, {"color":"black", "audi_property":"C"} ] } }

类结构是

abstract class Car implements Serializable { 
    private String color;
    // getter setter here
}
class Ford extends Car { 
    private String fordProperty;
    // getter setter here
}
class Audi extends Car {
    private String audiProperty;
    // getter setter here
}

我的回复课

class Response implements Serializable {
     private Map<String, List<Car>> myObj;
     // getter setters
}

@JsonSubTypes课程中使用Car进行了尝试,但希望type的{​​{1}}名称作为对象class的一部分。

由于

1 个答案:

答案 0 :(得分:0)

选项1

您可以通过更改Response代码并启用SerializationFeature.WRAP_ROOT_VALUE + DeserializationFeature.UNWRAP_ROOT_VALUE设置来实现此目的

以下是演示:

public static void main(String[] args) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
    mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
    Response resp = mapper.readValue(json, Response.class);
}

public abstract static class Car implements Serializable {
    public String color;
}

public static class Ford extends Car {
    @JsonProperty("ford_property")
    public String fordProperty;
}

public static class Audi extends Car {
    @JsonProperty("audi_property")
    public String audiProperty;
}

@JsonRootName("myobj")
public static class Response implements Serializable {
    public List<Audi> audi;
    public List<Ford> ford;
}

选项2

不要更改结构中的任何内容,不需要WRAP_ROOT_VALUE,但这会将对象反序列化2次

public static class Response implements Serializable {
    private Map<String, List<Car>> myObj;

    @JsonAnySetter
    private void setter(String key, JsonNode value) {
        try {
            if (key.equals("ford")) {

                myObj.put(key, mapper.readValue(value.toString(), 
                                     new TypeReference<List<Ford>>() {}));
            } else if (key.equals("audi")){
                myObj.put(key,  mapper.readValue(value.toString(), 
                                   new TypeReference<List<Audi>>() {}));
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

选项3

Response的自定义反序列化器与上面的@JsonAnySetter代码几乎相同,但可以在反序列化器中对其进行优化。