0

我有一个像

{"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
}

尝试@JsonSubTypesCar类上使用,但期望名称作为对象的type一部分。class{"color":"blue","ford_property":"A" }

谢谢

4

1 回答 1

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,但可以在反序列化器中对其进行优化。

于 2016-05-11T11:25:54.640 回答