Flatten fields in request

Viewed 104

I have simple request:

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Request
{
    private Address address;
    private Name name;
}

where Address and Name:

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Address
{
    private String postalCode;
    private String city;
}

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Name
{
    private String firstName;
    private String lastName;
}

and easy controller:

@RestController
public class Controller
{
    @PostMapping(path = "data", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> post(@RequestBody Request request)
    {
        return ResponseEntity.ok("1234");
    }
}

To make a request I have to use postman with request body like:

{
    "address": {
        "postalCode":"aaaa",
        "city":"bbb"
    },
    "name": {
        "firstName": "tom",
        "lastName": "xyz"
    }
}

And my question: is there any way to "flatten" this request to simple attributes:

{
    "city":"bbb"
    "postalCode":"aaaa",
    "firstName": "tom",
    "lastName": "xyz"
}
1 Answers

Annotate with @JsonUnwrapped the fields address and name in your Request class:

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public static class Request
{
    @JsonUnwrapped
    private Address address;

    @JsonUnwrapped
    private Name name;
}

Here is a small sample of code:

At first serialize the Request to json string:

ObjectMapper mapper = new ObjectMapper(); 

Address address = new Address("123435", "Athens");
Name name = new Name("John", "Doe");
Request request = new Request(address, name);
String s = mapper.writeValueAsString(request);
System.out.println(s);

Console output:

{"postalCode":"123435","city":"Athens","firstName":"John","lastName":"Doe"}

And then deserialize the json string to Request object:

Request request1 = mapper.readValue("{\"postalCode\":\"12345\",\"city\":\"Athens\",\"firstName\":\"John\",\"lastName\":\"Doe\"}", Request.class);
System.out.println(request1.getAddress().getPostalCode());
System.out.println(request1.getAddress().getCity());
System.out.println(request1.getName().getFirstName());
System.out.println(request1.getName().getLastName());

and the console output:

12345
Athens
John
Doe
Related