[英]Convert nested POJO or JSON to Map<String, String>
为了创建multipart/form-data请求,我需要将嵌套 POJO或由 Jackson 序列化产生的嵌套 JSON转换为具有以下格式的Map<String, String> 。
Map<String, String> map = new HashMap<>();
map.put("transaction_id", request.getTransactionId());
map.put("person[dob]", request.getPerson().getDob());
map.put("person[first_name]", request.getPerson().getFirstName());
map.put("person[last_name]", request.getPerson().getLastName());
以下是相关类的定义。
@Getter
public class Request {
@JsonProperty("transaction_id")
private String transactionId;
private Person person;
}
@Getter
public class Person {
@JsonProperty("dob")
private String dob;
@JsonProperty(value = "first_name")
private String firstName;
@JsonProperty(value = "last_name")
private String lastName;
}
有没有办法从给定的Request
POJO 或序列化的 JSON 中自动进行地图填充,例如使用我已经用于 JSON 序列化的 Jackson?
您可以使用ObjectMapper#convertValue
将您的Person
对象转换为Map
,该对象将对象转换为字段名称为键且值为字段值的map
,然后将transaction_id
键及其值添加到获取的映射中:
//map will contain keys = {dob, first_name, last_name}
//up to you modify the keys' names as you like
Map<String, String> map = mapper.convertValue(request.getPerson(),
new TypeReference<Map<String, String>>(){});
map.put("transaction_id", request.getTransactionId());
没有办法像你想要的那样做:
Map<String, String> map = new HashMap<>();
map.put("transaction_id", request.getTransactionId());
map.put("person[dob]", request.getPerson().getDob());
map.put("person[first_name]", request.getPerson().getFirstName());
map.put("person[last_name]", request.getPerson().getLastName());
您可以使用convertValue
方法
Map<String, Object> map = mapper.convertValue(request,
new TypeReference<Map<String, Object>>(){});
但生成的地图将是这样的:
Map<String, Object> map = new HashMap<>();
map.put("transactionId", request.getTransactionId());
map.put("person", new HashMap<String, Object>());
阅读该地图:
String transactionId = map.get("transactionId").toString();
String firstName = ((Map)map.get("person")).get("firstName").toString();
//The same for the rest of the properties
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.