简体   繁体   中英

Map json field from child object

Here is the description of issue to convert Json string to json.

Address{
    private long id;
    private String city;
}

Employee{
    private long id;
    private String name;
    private Address address;
}

Client will send a request with JSON of employee

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

Now i want to convert the input json into below format where addressId = id field of Address class.

Output{
    private long id;
    private String name;
    private long addressId; 
}

is there any way to achieve this. I have tried Jackson and Gson also.

With Jackson, you can add a class AddressId to wrap the address with just the id field and an annotated constructor that takes an AddressId as argument. Add getters and other constructors as needed. This doesn't require defining Employee and Address classes only Output .

class Output {
    private long id;
    private String name;
    private long addressId;

    @JsonCreator
    public Output(
            @JsonProperty("id") long id,
            @JsonProperty("name") String name,
            @JsonProperty("address") AddressId address) {
        this.id = id;
        this.name = name;
        this.addressId = address.getId();
    }
}

class AddressId {
    private long id;
}

In this case, you would also need to configure your ObjectMapper to quietly ignore unknown JSON fields:

mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

Another alternative, that doesn't require class AddressId , would be to create a custom setter for the addressId field based on the Map<String, Object> that Jackson uses internally when deserializing. This is how Output would look like in this case (add other setters/getters you may need):

class Output {
    private long id;
    private String name;

    @JsonProperty("address")
    public void setAddressId(final Map<String, Object> address) {
        addressId = (Integer) address.get("id");
    }

    private long addressId;
}

You can use Gson api to convert object from json.

Similar to the below code. Not sure whether it has no syntax error. But, this is possible.

Gson gson = new Gson();
Employee emp = gson.fromJson("{"id": 1, "name": "ABC", "address": {"id": 1, "city": "XYZ"}}", 
    Employee.class);

If the above code doesn't work out, try using dozer

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