【问题标题】:com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: UnrecognizedPropertyException and Unrecognized fieldcom.fasterxml.jackson.databind.exc.UnrecognizedPropertyException:UnrecognizedPropertyException 和 Unrecognized 字段
【发布时间】:2014-08-02 04:43:26
【问题描述】:

我是 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)

我正在拉我的头发。请帮忙!!!

谢谢

【问题讨论】:

  • 你能告诉我你在哪里写了main方法吗?同时显示您的导入语句。

标签: json data-binding


【解决方案1】:

有两种可能的解决方案:

解决方案一

您可以将注释 @JsonIgnoreProperties(ignoreUnknown = true) 添加到您的 MyValue 类中。

解决方案二

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

【讨论】:

  • 如果您能进一步解释您提供的两种解决方案之间的差异,那就太好了。
猜你喜欢
  • 2015-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多