我有一个需要映射到单个平面POJO对象的json。我正在使用jackson-databind,它似乎不支持这些类型的操作。有什么建议吗?
{
"id": 1,
"name": "Alex",
"emailId": "alex@gmail.com",
"address": {
"address": "21ST & FAIRVIEW AVE",
"district": "district",
"city": "EATON",
"region": "PA",
"postalCode": "18044",
"country": "US"
}}
public class singlePojo{
String id;
String name;
String emailId;
String address;
String district;
String city;
String region;
String postalCode;
}发布于 2019-03-09 02:50:12
使用@JsonAnyGetter映射address
@JsonAnyGetter注释允许灵活地将映射字段用作标准属性。
public class singlePojo{
String id;
String name;
String emailId;
Map<String,Object> address;
@JsonAnyGetter
public Map<String, Object> getAddress() {
return address;
}
}如果序列化这个类,输出将是
{
"id": 1,
"name": "Alex",
"emailId": "alex@gmail.com",
"address": "21ST & FAIRVIEW AVE",
"district": "district",
"city": "EATON",
"region": "PA",
"postalCode": "18044",
"country": "US"
}发布于 2019-03-09 03:04:46
您可以使用@JsonProperty在POJO中创建自定义设置器,将映射展平为各个字段:
@SuppressWarnings("unchecked")
@JsonProperty("address")
public void setDistrict(Map<String,String> map) {
Map<String,String> address = map.get("address");
this.district = address.get("district");
}您必须对来自map的POJO中的每个字段执行此操作,因此它可能是冗长和重复的。
您还可以使用一个自定义的反序列化程序,它可以一次完成所有字段:
public class SimplePojoDeserializer extends StdDeserializer<SimplePojo> {
@Override
public SimplePojo deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
JsonNode node = jp.getCodec().readTree(jp);
SimplePojo pojo = new SimplePojo();
product.setAddress(node.get("address").get("address").textValue());
product.setDistrict(node.get("address").get("district").textValue());
// ...
return pojo;
}
}在这种情况下,您必须处理POJO中的所有字段,而不仅仅是地址字段。
更多细节here。
https://stackoverflow.com/questions/55068964
复制相似问题