【发布时间】: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