将Json字段包装到pojo的实例变量中 [英] Wrapping Json fields into instance variable of a pojo
问题描述
我正在尝试将某些json字段映射到类实例变量.
i am trying to map certain json fields to a class instance variable.
我的示例人类如下:
public class Person {
private String name;
private Address address;
//many more fields
//getters and setters
}
示例 Address 类是:
public class Address {
private String street;
private String city;
//many more fields
// getters and setters
}
要反序列化到我的Person类的json对象不包含地址"字段.看起来像:
The json object to be deserialized to my Person class doesn't contain "address" field. It looks like:
{
"name":"Alexander",
"street":"abc 12",
"city":"London"
}
是否可以将json反序列化为Person pojo,其中Address字段也已正确映射?
Is there a way to deserialize the json to the Person pojo where the Address fields are also mapped properly?
我使用了自定义地址反序列化器,如此处许多文章所述.但是,由于Json对象不包含地址"字段,因此没有被调用.
I have used a custom Address deserializer as mentioned in so many posts here. However, it's not being called as the Json object doesn't contain "address" field.
我已经通过使用JsonNode手动映射每个字段解决了这个问题,但是在我的真实项目中,这不是一个很好的解决方案.
I had resolved this problem by mapping each field manually using JsonNode, however in my real project, it's not a nice solution.
使用杰克逊可解决此问题吗? 另外,如果在此之前有人问过这个问题,那么我就此深表歉意,因为我一直在寻找解决方案,但可能还没有看到.
Is there any work around for such problem using jackson? Plus if this question has been asked before then apologies on my behalf as as i have intensively searched for the solution and might have not seen it yet. .
推荐答案
@JsonUnwrapped
批注.型号:
class Person {
private String name;
@JsonUnwrapped
private Address address;
// getters, setters, toString
}
class Address {
private String street;
private String city;
// getters, setters, toString
}
用法:
ObjectMapper mapper = new ObjectMapper();
String json = "{\"name\":\"Alexander\",\"street\":\"abc 12\",\"city\":\"London\"}";
System.out.println(mapper.readValue(json, Person.class));
打印:
Person{name='Alexander', address=Address{street='abc 12', city='London'}}
有关更多信息,请阅读:
For more info read:
- Jackson Annotation Examples
- Annotation Type JsonUnwrapped
- Jackson JSON - Using @JsonUnwrapped to serialize/deserialize properties as flattening data structure
这篇关于将Json字段包装到pojo的实例变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!