简体   繁体   中英

Using @JsonAnyGetter /@JsonAnySetter to Serialize JSON and change property name (Jackson)

I have a JSON that looks like:

{"pfm1":{"status":true,"candid":true},
"pfm2":{"status":false,"candid":true},
"pfm3":{"status":false,"candid":true}}

I want to map it and change the property naming for pfm1,pfm2,pfm3 with a variable string name. Could you please indicate how it can be done in the class below. The output shall be:

{"Idname01":{"status":true,"candid":true}, 
"Idname02":{"status":false,"candid":true}, 
"Idname03":{"status":false,"candid":true}}
Msg jsonobject=mapper.readValue(input, Msg.class);

Class

static class Msg {
    @JsonIgnore
    private Object pfm1;
    @JsonIgnore
    private Object pfm2;
    @JsonIgnore
    private Object pfm3;
    private Map<String, Object> pfm = new HashMap<String, Object>();
    public Object getPfm1() {return pfm1;}
    public void setMpfm1(Object pfm1) {this.pfm1 = pfm1;}
    public Object getPfm2() {return mpfm2;}
    public void setPfm2(Object pfm2) {this.pfm2 = pfm2;}
    public Object getPfm3() {return mpfm3;}
    public void setPfm3(Object pfm3) {this.pfm3 = pfm3;}
    @JsonAnySetter
    public void set(String name, Object value) {
        mpfm.put(name, value);
    }
    public Msg(){
    }
}

Found solution for that without using getters, setters and @jsonanygetter. Just by using Object node. it is possible to manipulate your json structure including changing name property. it's much simpler and straightforward.

newNode.set("newname",node);
///convert constructed newNode to json
String jsonout = newNode.toString(); 

"newname" can be set as a stored variable. node is Object node extracted from top structure.

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