[英]json parsing with jackson
I am using the Jackson library for conversion of a JSON string to Java objects 我正在使用Jackson库将JSON字符串转换为Java对象
My json is: 我的json是:
{
"human":{
"fname":"anjali",
"lname":"malhotra"
}
}
I want this to be converted into a Java class with following structure: 我希望将其转换为具有以下结构的Java类:
public class Human
{
String fname;
String lname;
}
I can successfully convert it into 我可以成功地将其转换为
public class HumanWrapper
{
Human human;
}
But, I wanted to know if there is a way I can directly convert it into the Human format. 但是,我想知道是否可以直接将其转换为Human格式。 I read about custom deserialization but was reluctant for that approach.
我读过有关自定义反序列化的信息,但不愿采用这种方法。
You could achieve this by configuring ObjectMapper to use DeserializationFeature.UNWRAP_ROOT_VALUE
: 您可以通过将ObjectMapper配置为使用
DeserializationFeature.UNWRAP_ROOT_VALUE
来实现:
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
and annotatating your Human
class with @JsonRootName
annotation : 并使用
@JsonRootName
注释对Human
类进行注释:
@JsonRootName("human")
public class Human {
....
}
You need to have a HumanWrapper
class as your human object is defined inside you json object 您需要有一个
HumanWrapper
类,因为您的人类对象是在json对象内部定义的
{
"human": {
}
}
If you able to change you API to send just a human
object like this 如果您能够更改您的API以仅发送这样的
human
对象
{
"fname":"anjali",
"lname":"malhotra"
}
Then you woudn't be bothering to have a HumanWrapper
那你就不用
HumanWrapper
一个HumanWrapper
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.