Java 将哈希映射反序列化为POJO并将空字段设置为null?
我有一个JSON响应,其中我解析如下:Java 将哈希映射反序列化为POJO并将空字段设置为null?,java,json,serialization,deserialization,objectmapper,Java,Json,Serialization,Deserialization,Objectmapper,我有一个JSON响应,其中我解析如下: List<LinkedHashMap> jsonResponse = objectMapper.readValue(jsonResponse, List.class); 但是,这个自定义POJO有额外的可选字段,这些字段可能包含在JSON响应中,也可能不包含在JSON响应中。最终,JSON响应中排除的整数/双精度字段分别自动设置为0或0.0。我希望它们是空的 编辑: 仍在接收空字段的0 我试过的代码: Type
List<LinkedHashMap> jsonResponse = objectMapper.readValue(jsonResponse, List.class);
但是,这个自定义POJO有额外的可选字段,这些字段可能包含在JSON响应中,也可能不包含在JSON响应中。最终,JSON响应中排除的整数/双精度字段分别自动设置为0或0.0。我希望它们是空的
编辑:
仍在接收空字段的0
我试过的代码:
TypeReference<List<ProductsByInstitution>> typeRef
= new TypeReference<List<ProductsByInstitution>>() {};
objectMapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
List<ProductsByInstitution> objs = objectMapper.readValue(lambdaResponse, typeRef);
因此JSON响应可能如下所示:
id: 0
name: "Place"
status: "Good"
buy: 50
min: 20
然后,当发生反序列化时,figure、max和offer被设置为0/0.0基元类型
int
或double
不能表示null
。使用可以表示空值的包装类Integer
或Double
public class ProductsByInstitiution {
private Integer id;
private Integer max;
private Double figure;
...
}
基元类型
int
或double
不能表示null
。使用可以表示空值的包装类Integer
或Double
public class ProductsByInstitiution {
private Integer id;
private Integer max;
private Double figure;
...
}
Objectmapper在反序列化List.class时使用链接的hashmap。要使其成为特定类型的列表,您需要一个TypeReference作为示例,请参见:但如果是List,只需使用:TypeReference(并用实际类型替换字符串)检查OPObjectmapper中更新的对立POJO代码在反序列化List.class时使用链接的hashmap。要使其成为特定类型的列表,您需要一个TypeReference作为示例,请参见:但如果是列表,请使用:TypeReference(并用实际类型替换字符串)检查OP中更新的对立POJO代码
public class ProductsByInstitiution {
private Integer id;
private Integer max;
private Double figure;
...
}