映射键为null时找不到Key deserializer

时间:2014-05-22 20:06:37

标签: java serialization jackson

经过类似的问题后,我仍然无法解决这个问题。我正在使用Jackson序列化和反序列化没有匹配的getter / setters方法的类。

public class Products implements Serializable {
private static final long serialVersionUID = 1L;
@JsonProperty
private final Map<Product, String> prices;

public Products() {
    this.prices = new HashMap<>();
}

public void addPrice(final Product product, final String price) {
    prices.put(product, price);
}
}

产品类别:

public class Product implements Serializable {
private static final long serialVersionUID = 1L;
@JsonProperty
private final String name;
@JsonProperty
private final String type;

public Product(final String price, final String type) {
    this.name = price;
    this.type = type;
}
public String getName() {
    return name;
}

public String getType() {
    return type;
}


public static void main(String[] args) {
    Products products = new Products();
    products.addPrice(new Product("apple", "fruit"), "16");

    JsonDataConverter converter = new JsonDataConverter();
    String json = converter.toData(products);
    System.out.println(json);

    Products deserializedProducts = converter.fromData(json, Products.class);
}
}
我正在使用的{p> JsonDataConverter来自AWS Flow Frameworkhttp://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/simpleworkflow/flow/JsonDataConverter.html

我在反序列化步骤中遇到的异常是:Can not find a (Map) Key deserializer for type [simple type, class mypackage.Product] when mapping key "null"

我无法理解这一点,因为我的prices地图不包含任何空值。奇怪的是,如果Product只有一个成员(只有name)字段,那就可以了。

知道出了什么问题?

由于

1 个答案:

答案 0 :(得分:0)

您可以尝试修改产品和产品类的构造函数以使用JsonCreator注释并使用JsonProperty注释每个参数。

示例:

@JsonCreator
public Product(@JsonProperty("price") final String price, @JsonProperty("type") final String type) {
       this.name = price; this.type = type;
}