Serializing and unpacking a Map to a POJO using the Jackson annotation

I have a POJO with paramMap property as a map type.

import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo.As;
import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;
import com.fasterxml.jackson.annotation.JsonUnwrapped;

@JsonTypeInfo(include=As.WRAPPER_OBJECT, use=Id.NAME)
public class Pojo {

    @JsonUnwrapped
    private Map<String, Object> paramMap = new HashMap<String, Object>();

    public Map<String, Object> getParamMap() {
        return paramMap;
    }

    public void setParamMap(Map<String, Object> paramMap) {
        this.paramMap = paramMap;
    }

      

consider that I have run some values ​​in the map, now I want to serialize this and expand the property name paramMap

.

Expected Result:

{
    "Pojo": {
        "name": "value1",
        "age": 12,
        "date": "12/02/2015"
    }
}

      

Actual output

{
    "Pojo": {
        "paramMap": {
            "name": "value1",
            "age": 12,
            "date": "12/02/2015"
        }
    }
}

      

+3


source to share


1 answer


The answer is here . Using the Jackson annotation @JsonAnyGetter

in the getter method getParamMap()

, we can get the expected result.

@JsonAnyGetter
public Map<String, Object> getParamMap() {
    return paramMap;
}

      



Note: This is still open in the Jackson project Issue # 171 Thanks to Tatu Saloranta post author

+4


source







All Articles