2016-07-28 125 views
3

我的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

不能從初始化字符串的地圖,即取代'「值」 :「」'它必須是'「Values」:{}'。 – Thomas

+0

我從第三方API獲取json,因此我無法更改json格式。 –

回答

1

當您的值爲空字符串時,您似乎試圖將String與Map映射。

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

傑克遜將使用setter方法來映射值。該設置器將被Jackson檢測到,並將在從JSON中讀取屬性時使用。所以在你的setter中,你可以檢查你的字段是map還是空字符串。 爲此,您可以接受對象。然後檢查它..如波紋管......

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

希望......這將有助於...

+0

Ohoo謝謝!!它的工作.... –