我的 Json 字符串是
{
"FieldInfo":{
"Field1":{
"FieldName":"test1",
"Values":""
},
"Field2":{
"FieldName":"test2",
"Values":{
"test":"5",
"test1":"2"
}
}
}
}
我在提交 map 值时遇到问题。在我的 json 字符串中,提交的值是空字符串或映射。我正在映射下面提到的变量中的值字段。
@JsonProperty("Values")
private Map<String, String> values;
所以我的问题是用 map 映射空字符串。它给出异常,
com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate
value of type [map type; class java.util.LinkedHashMap, [simple type, class
java.lang.String] -> [simple type, class java.lang.String]] from String
value; no single-String constructor/factory method (through reference
chain: com.test.model.ExtraInformation["FieldInfo"]->com.test.model.FieldInfo["Values"])
我已经使用了@JsonInclude(Include.NON_NULL)
。但它不起作用。
最佳答案
当您的值为空字符串时,您似乎正在尝试将 String 与 Map 进行映射。
@JsonProperty("Values")
private Map<String, String> values;
Jackson 将使用 setter 方法来映射值。这个 setter 将被 Jackson 检测到,并在从 JSON 中读取属性时使用。因此,在您的 setter 中,您可以检查您的字段是映射还是空字符串。 为此,您可以接受 Object.然后检查它……如下所示……
public void setValues(Object values) {
if(values instanceof String){
this.values = null;
}else{
this.values = (Map<String, String>) values;
}
}
希望...它会帮助...
关于java - 如何使用 jackson mapper 将空字符串映射到 Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38629825/