0

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.

Robin Green
  • 32,079
  • 16
  • 104
  • 187

2 Answers2

0

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).

Community
  • 1
  • 1
triplem
  • 1,324
  • 13
  • 26
  • If I remove the get method I won't be able to get the unknown parameters that have been stored into map, I want my output like this - `{ "context_id": "14", "properties" : { "io": "odp" } }` not this - `{ "context_id": "14", "properties" : { "io": "odp" }, "io": "odp" }` – Aniket Nandan Jan 22 '17 at 13:54
  • Sure. Have you tried it using the above mentioned answer? – triplem Jan 22 '17 at 14:00
  • yup. for that i got my json as `{"context_id":"12","yio":"odjp"}` not as expected. – Aniket Nandan Jan 22 '17 at 14:02
0

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; }