我使用Jackson Json Mapper来解析我的服务器上的查询。Jackson Json Mapper:无字段或空字段?
例如,我在等待查询其适合My_class
类:
class My_class {
String a;
String b;
}
我反序列化查询,这种方式:
public <T> T Deserialize(String json, Class<T> type) throws DeserializationException {
if (json == null || type == null) {
throw new IllegalArgumentException();
}
try {
return objectMapper.readValue(json, type);
} catch (JsonParseException e) {
throw new DeserializationException(e);
} catch (org.codehaus.jackson.map.JsonMappingException e) {
throw new DeserializationException(e);
} catch (IOException e) {
throw new DeserializationException(e);
}
}
这里有两个例子查询:
{"a":"test"}
{"a":"test", "b":null}
问题是我想知道用户只给我一个查询字段a
,当他发送一个查询字段b
设置为null
。在两种情况下,映射器将字段b
标记为null
。
什么是更好的方法来做到这一点(并避免编写我自己的解串器)?
这两种情况有什么区别? – 2013-09-16 12:45:41
在这两种情况下,你会期望杰克逊如何映射'b'的值?在Java中,My_class有一个名为'b'的字段,它只能有一个字符串值或为空。因此,当B不存在于JSON有效载荷中时,您希望My_class'b'字段具有什么值?如果JSON有效载荷中的“b”为空,该怎么办? – Kyle