Kalpen Patel Kalpen Patel - 4 months ago 20
JSON Question

how to map empty string with Map using jackson mapper

My Json String is


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


}

I am facing problem while map values filed. in my json string, values filed is either empty string or map. I am mapping values field in below mentioned variable.

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


So my problem is mapping empty string with map.it gives exception,
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"])


I have already used @JsonInclude(Include.NON_NULL). but its not working.

Answer

It seems that you are trying to map String with Map when your value is empty string.

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

Jackson will use setter method to map values. This setter will be detected by Jackson and will be used when the property is read from the JSON. So within your setter, you can check if your field is either map or empty string. For that you can accept Object. And then check for it.. as bellow...

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

Hope ... It will help...