平坦请求中的字段



我有一个简单的请求:

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

其中AddressName:

@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;
}

和简易控制器:

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

要发出请求,我必须使用带有请求体的postman:

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

我的问题是:有没有办法让"平坦化"?这是对简单属性的请求:

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

Request类中用@JsonUnwrapped注释addressname字段:

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public static class Request
{
@JsonUnwrapped
private Address address;
@JsonUnwrapped
private Name name;
}
下面是一小段代码示例:

首先将请求序列化为json字符串:

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);

控制台输出:

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

然后将json字符串反序列化为请求对象:

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());

和控制台输出:

12345
Athens
John
Doe

相关内容

  • 没有找到相关文章

最新更新