com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException:UnrecognizedPropertyException和Unrecognized field

时间:2014-08-02 04:43:27

标签: json data-binding

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

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

谢谢

1 个答案:

答案 0 :(得分:0)

有两种可能的解决方案:

解决方案一

您只需向@JsonIgnoreProperties(ignoreUnknown = true)课程添加注释MyValue即可。

解决方案二

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