简体   繁体   中英

Difficulty in mapping java object to JSON

I am trying to map JSON to java object and vice-versa. In doing so, my unknown parameters for the class are mapped into java.util.Map by @JsonAnySetter method. But at the time of getting back the json from java object I am getting wrong output. I am using fasterxml library.

Here is my java object:

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

import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonInclude;

@JsonInclude(JsonInclude.Include.NON_NULL)
public class TestClass {
    private String context_id;
    private Map<String, String> properties = new HashMap<>();

    public String getContext_id() {
        return context_id;
    }
    public void setContext_id(String context_id) {
        this.context_id = context_id;
    }
    @JsonAnySetter
    public void set(String fieldName, String value){
        this.properties.put(fieldName, value);
    }
    @JsonAnyGetter
    public Map<String, String> any() {
        return this.properties;
    }
    public String get(String fieldName){
        return this.properties.get(fieldName);
    }
}

and the JSON I am providing to map into java object by com.fasterxml.jackson.databind.ObjectMapper is:

{
    "context_id": "14",
    "io": "odp"
}

and when I try to get the JSON back from java object I am getting like this:

{
            "context_id": "14",
            "properties" : {
                   "io": "odp"
             },
            "io": "odp"
}

But I should get it back like:

{
        "context_id": "14",
        "properties" : {
               "io": "odp"
         }
}

which I am not getting.

Remove the get-method and all should be fine. As an alternative you could set @JsonIgnore on the getter (see Only using @JsonIgnore during serialization, but not deserialization ).

Thanks all for your help. I have solved the problem. 1. I have removed this portion

@JsonAnyGetter
public Map<String, String> any() {
    return properties;
}
  1. Add a normal getter for the properties map like -

    public Map getProperties() { return properties; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM