[英]How to deserialize with jackson objectmapper
I want to convert a json (shown below) into a java object. 我想将json(如下所示)转换为java对象。 I have created java classes for the json objects without using any jackson annotations for now.
我已经为json对象创建了Java类,目前还没有使用任何jackson注释。
import com.fasterxml.jackson.databind.ObjectMapper;
public class TestJunkie {
private static final ObjectMapper objectMapper = new ObjectMapper();
public static void main(String[] args) throws Exception {
String json = "{\r\n" +
" \"Info\":{\r\n" +
" \"prop1\": \"value1\",\r\n" +
" \"prop2\": \"value2\",\r\n" +
" \"prop3\": \"value3\"\r\n" +
" },\r\n" +
" \"Data\":{\r\n" +
" \"prop1\": \"value1\",\r\n" +
" \"prop2\": \"value2\"\r\n" +
" }\r\n" +
"}";
Pack pack = objectMapper.readValue(json, Pack.class);
System.out.println(pack);
}
}
I converted the above Json object into a Java class called "Pack" below: 我将上面的Json对象转换为下面的Java类,称为“ Pack”:
import org.apache.commons.lang3.builder.ToStringBuilder;
public class Pack {
private Info info;
private Data data;
public Info getInfo() {
return info;
}
public void setInfo(Info info) {
this.info = info;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
@Override
public String toString() {
return new ToStringBuilder(this).append("info", info).append("data", data).toString();
}
}
I have deliberately omitted the classes for Info and Data. 我故意省略了信息和数据类。 Their variables, getters, setters match the json.
它们的变量,getter,setter与json匹配。 I can include them if you want.
如果需要,我可以包括它们。
I get the following exception. 我得到以下异常。 Why does this exception occur & how do I fix it ?
为什么会发生此异常以及如何解决?
Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "Info" (class com.tester.Jacksons.Pack), not marked as ignorable (2 known properties: "data", "info"])
at [Source: (String)"{
"Info":{
"prop1": "value1",
"prop2": "value2",
"prop3": "value3"
},
"Data":{
"prop1": "value1",
"prop2": "value2"
}
}"; line: 2, column: 10] (through reference chain: com.tester.Jacksons.Pack["Info"])
at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:60)
at com.fasterxml.jackson.databind.DeserializationContext.handleUnknownProperty(DeserializationContext.java:822)
at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:1152)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1582)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownVanilla(BeanDeserializerBase.java:1560)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:294)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4001)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2992)
at com.tester.Jacksons.TestJunkie.main(TestJunkie.java:22)
Your object's keys are lower case and in the json they are upper-camel-case. 对象的键是小写字母,而在json中,它们是大写字母。 If this naming scheme is consistent you can just set the naming stategy on the object mapper.
如果此命名方案是一致的,则可以在对象映射器上设置命名策略。
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.UpperCamelCaseStrategy);
Your properties inside Pack are not matching the names because in json it's starting with capital case letter. Pack中的属性与名称不匹配,因为在json中,它以大写字母开头。 Hence, update
Pack
as follows: 因此,更新
Pack
如下:
import org.apache.commons.lang3.builder.ToStringBuilder; 导入org.apache.commons.lang3.builder.ToStringBuilder;
public class Pack {
@JsonProperty("Info")
private Info info;
@JsonProperty("Data")
private Data data;
public Info getInfo() {
return info;
}
public void setInfo(Info info) {
this.info = info;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
@Override
public String toString() {
return new ToStringBuilder(this).append("info", info).append("data", data).toString();
}
}
Also, in case there are properties which are not specified in Info or Data class. 另外,如果某些属性未在Info或Data类中指定。 Use
@JsonIgnoreProperties(ignoreUnknown = true)
annotation on class to Ignore unknown properties. 在类上使用
@JsonIgnoreProperties(ignoreUnknown = true)
注释可忽略未知属性。
Updates 更新
Using annotations could not be very handy if you have to use same Classes say as Hibernate Entities or in other places. 如果您必须使用与Hibernate Entities相同的类或在其他地方使用注释,那么使用注释可能不会很方便。 Hence, My recommendation is that you perform
serialization and deserialization using Dtos
and then later put values from these Dtos to your other objects wherever you need to. 因此,我的建议是您
serialization and deserialization using Dtos
执行serialization and deserialization using Dtos
然后再将这些Dtos中的值放到您需要的其他对象中。 You could use good apis like mapstruct
to do such creation of objects. 您可以使用诸如
mapstruct
类的mapstruct
来创建此类对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.