Jackson: Split a json and populate known and unknown properties

Jordi :

I'm coding an Spring-boot service and I'm using jackson ObjectMapper in order to handle with my jsons.

I need to split a json like this:

{
  "copy": {
    "mode": "mode",
    "version": "version"
  },
  "known": "string value",
  "unknown": {
   "field1": "sdf",
   "field2": "sdfdf"
  },
  "unknown2": "sdfdf"
}

I mean, my bean is like this:

public class MyBean {

    private CopyMetadata copy;
    private String known;
    private Object others;

}

I'd like to populate known fields to MyBean properties, and move the other unknown properties inside MyBean.others property.

Known properties are which are placed as a field inside MyBean.

Any ideas?

Vaibhav Gupta :

A possible solution to this problem is to use the jackson annotations @JsonAnyGetter and @JsonAnySetter

Your Model Mybean.class should look something like this and it should work

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

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

public class MyBean {

    private CopyMetadata copy;
    private String known;
    private Map<String, Object> others = new HashMap<>();

    public CopyMetadata getCopy() {
        return copy;
    }

    public void setCopy(CopyMetadata copy) {
        this.copy = copy;
    }

    public String getKnown() {
        return known;
    }

    public void setKnown(String known) {
        this.known = known;
    }

    public Map<String, Object> getOthers() {
        return others;
    }

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

    @JsonAnyGetter
    public Map<String, Object> getUnknownFields() {
        return others;
    }

    @JsonAnySetter
    public void setUnknownFields(String name, Object value) {
        others.put(name, value);
    }

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=99557&siteId=1