如何使用jackson mapper

时间:2016-07-28 07:32:21

标签: java json jackson

我的Json字符串是

{  
   "FieldInfo":{  
      "Field1":{  
         "FieldName":"test1",
         "Values":""
      },
      "Field2":{  
         "FieldName":"test2",
         "Values":{  
            "test":"5",
            "test1":"2"
         }
      }
   }
}

我在提交地图值时遇到问题。在我的json字符串中,值字段是空字符串或映射。我在下面提到的变量中映射值字段。

@JsonProperty("Values")
private Map<String, String> values;

所以我的问题是用map.it映射空字符串给出异常,

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)了。但它不起作用。

1 个答案:

答案 0 :(得分:1)

当您的值为空字符串时,您似乎正在尝试将String映射到Map。

@JsonProperty("Values")
private Map<String, String> values;

杰克逊将使用setter方法来映射值。 Jackson将检测此setter,并在从JSON读取属性时使用。因此,在您的setter中,您可以检查您的字段是map还是空字符串。 为此你可以接受对象。然后检查它......如下... ...

 public void setValues(Object values) {  
  if(values instanceof String){
   this.values = null;
  }else{
   this.values = (Map<String, String>) values;
  }
 }

希望......这会有所帮助......