简体   繁体   中英

Jackson serialize and wrap attributes into a new Object

Serializing object of the following class yeilds string like

public class User implements Serializable{

    private Integer id;
    private String name;
    private Integer pinCode;
    private String city;

    // getters /setters
}

{"id":1,"name":"XYZ","pinCode":123456,"city":"ABC"}

But we want that attributes pinCode and city should be a part of new Json node say address node.

So my expectation of the result is:

{
  "id": 1,
  "name": "XYZ",
  "address": {
    "pinCode": 123456,
    "city": "ABC"
  }
}

Can this be accomplished without re-organizing the class structure and by using Json annotations

on the exact opposite lines of @JsonUnwrapped

you can use such workaround(but preferred to use JsonSerialize):

public class User implements Serializable{

    private Integer id;
    private String name;

    @JsonIgnore
    private Integer pinCode;

    @JsonIgnore
    private String city;

    @JsonProperty("address")
    public Map<String, Object> getAddress() {
        Map<String, Object> map = new HashMap<>();
        map.put("pinCode", pinCode);
        map.put("city", city);
        return map;
    }

    //Deserealization
    public void setAddress(Map<String, Object> map) { 
        if(map!=null) { 
            city = (String) map.get("city"); 
            pinCode = (Integer) map.get("pinCode"); 
        } 
    }

    // getters /setters
}

Thanks to @hemantvsn for deserialization example

Add another class called Address like below:

public class Address implements Serializable {

    private Integer pinCode;
    private String city;

    // getters /setters
}

Then use Address class inside User class like below:

public class User implements Serializable {

    private Integer id;
    private String name;
    private Address address;
    // getters /setters
}

Now Jackson give you json string like :

{
  "id": 1,
  "name": "XYZ",
  "address": {
    "pinCode": 123456,
    "city": "ABC"
  }
}

@JsonProperty("address.pinCode") used to set field name in json. Please see doc here for more detail JsonProperty

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