gpt4 book ai didi

json - com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException : UnrecognizedPropertyException and Unrecognized field

转载 作者:行者123 更新时间:2023-12-04 23:45:25 24 4
gpt4 key购买 nike

我是 JSON 的新手,我正在尝试应用最简单的 JSON 概念: https://github.com/FasterXML/jackson-databind

它简单明了,很容易理解。解释是有道理的。POJO很干净,东西不多。映射器应该完成这项工作,但事实并非如此。

所以我有以下代码:

public static void main(String[] args) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
MyValue value = objectMapper.readValue("{\"name\":\"Bob\", \"age\":13}", MyValue.class);
System.out.println("- value.getName = ["+value.getName()+"] ");
System.out.println("- value.getAge = ["+value.getAge()+"] ");
} // main()


public class MyValue {
private String name;
private int age;

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}

// Constructor
public MyValue() {
}

} // MyValue Class

当我运行它时,它会生成以下异常:

Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class com.csc.cloud.cp.service.solarwinds.orion.impl.SolarWindsOrionServiceImpl$MyValue]: can not instantiate from JSON object (need to add/enable type information?)
at [Source: {"name":"Bob", "age":13}; line: 1, column: 2]

即使我在那里有默认的 MyValue() 构造函数。

所以当我将以下注释添加到 MyValue 类时:

// Constructor
@JsonCreator
public MyValue() {
}

我得到以下异常

Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "name" (class com.csc.cloud.cp.service.solarwinds.orion.impl.SolarWindsOrionServiceImpl), not marked as ignorable (0 known properties: ])
at [Source: {"name":"Bob", "age":13}; line: 1, column: 10] (through reference chain: com.csc.cloud.cp.service.solarwinds.orion.impl.SolarWindsOrionServiceImpl["name"])
at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:51)

我在拉头发。请帮助!!!

谢谢

最佳答案

有两种可能的解决方案:

方案一

您只需将注释 @JsonIgnoreProperties(ignoreUnknown = true) 添加到您的 MyValue 类。

方案二

添加到配置 objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); 以便 objectMapper 不会因未知属性而失败。

关于json - com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException : UnrecognizedPropertyException and Unrecognized field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25091737/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com