我正在尝试解析一些 JSON(可以在这个 Gist中看到 JSON 的完整示例)。我在下面展示了 JSON 的一般结构:
[
{
"title": "Principles of Compiler Design",
"authors": [
"Aho",
"Ullman"
],
"publisher": "Addison Wesley",
"year": 1977
},
{
"title": "Compilers: Principles Techniques and Tools",
"authors": [
"Aho",
"Sethi",
"Ullman"
],
"publisher": "Addison Wesley",
"year": 1985
}
]
我正在尝试使用 Jackson 库解析 JSON,但在测试时出现以下错误:
Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_ARRAY token
at [Source: library.json; line: 2, column: 49] (through reference chain: com.acme.datatypes.User["authors"])
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:163)
at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:588)
at com.fasterxml.jackson.databind.deser.std.JdkDeserializers$StringDeserializer.deserialize(JdkDeserializers.java:90)
at com.fasterxml.jackson.databind.deser.std.JdkDeserializers$StringDeserializer.deserialize(JdkDeserializers.java:59)
at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:336)
at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:89)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:290)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:112)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2563)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:1759)
at com.acme.datatypes.UserTest.main(UserTest.java:20)
这是我的代码:
用户测试类:
public class UserTest {
public static void main(String[] args) throws JsonParseException,
JsonMappingException, IOException {
File jsonFile = new File("library.json");
User user = null;
ObjectMapper mapper = new ObjectMapper();
user = mapper.readValue(jsonFile, User.class);
System.out.println(user.getTitle());
user = mapper.readValue(jsonFile, User.class);
System.out.println(user.getAuthors());
user = mapper.readValue(jsonFile, User.class);
System.out.println(user.getPublisher());
user = mapper.readValue(jsonFile, User.class);
System.out.println(user.getYear());
}
}
用户等级:
public class User {
private String authors;
private String publisher;
private String title;
private Number year;
public String getAuthors() {
return this.authors;
}
public void setAuthors(String authors) {
this.authors = authors;
}
public String getPublisher() {
return this.publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public Number getYear() {
return this.year;
}
public void setYear(Number year) {
this.year = year;
}
}
有谁知道问题可能是什么?谢谢。