为了创建一个multipart/form-data请求,我需要转换一个嵌套的POJO或者嵌套JSONMap<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 ?
您可以将您的Person
对象转换为Map
,ObjectMapper#convertValue
将对象转换为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