Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transform a flat JSON to hierarchical java Class?

I need to deserialize a flat JSON object to a Java object with some properties set to child object.

{
 "name": "abcd",
 "addressLine1": "123",
 "addressLine2": "1111"
}

Class Student {
  String name;
  Address address;
}

Class Address {
 String line1;
 String line2;
}

How do I deserialize my JSON using Jackson into a Student object? I am not able to map addressLine1 to Student.Address.line1 and addressLine2 to Student.Address.line2

like image 296
Prashant Singh Rathore Avatar asked Jun 22 '26 16:06

Prashant Singh Rathore


1 Answers

You can define your data classes this way:

  public static class Student {
    String name;

    @JsonUnwrapped
    Address address;
  }

  public static class Address {
    @JsonProperty("addressLine1")
    String line1;
    @JsonProperty("addressLine2")
    String line2;
  }

Then you can use the Objectmapper in the usual way - without any additional magic or workaround :

Student student = mapper.readValue(json, Student.class);

If your incoming json string is indeed in the format you provided (without quotes) then also add:

mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
like image 192
Selindek Avatar answered Jun 24 '26 06:06

Selindek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!