【发布时间】:2017-12-02 13:46:36
【问题描述】:
我有这样一个程序,它使用 API REST 获取数据并将其显示在 JTextArea 中。一切都很好,但我需要通过反序列化来修改这个程序。我需要将从 API 获得的数据反序列化到 Country 类,然后才显示它。我试过但得到了错误:
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of model.Country[] out of START_OBJECT token
at [Source: {"nativeName":"latitude","longitude"}; line: 1, column: 1]
这是我的主要课程(我的反序列化尝试已被评论):
public void actionPerformed(ActionEvent evt) {
/*ObjectMapper mapper = new ObjectMapper();
String userDataJSON = "{\"nativeName\":\"latitude\",\"longitude\"}";
mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
try {
Country[] userFromJSON = mapper.readValue(userDataJSON, Country[].class);
System.out.println(userFromJSON);
} catch (IOException e1) {
System.out.println(e1);
}*/
...
textField.selectAll();
textArea.setCaretPosition(textArea.getDocument().getLength());
}
} catch (Exception e) {
}
}
}
还有我的班级国家:
public class Country {
@JsonProperty
private String name;
@JsonProperty
public String nativeName;
@JsonProperty
private String latitude;
@JsonProperty
private String longitude;
@JsonProperty
private String currencyCode;
public Country(String name, String nativeName, String latitude, String longitude, String currencyCode) {
super();
this.name = name;
this.nativeName = nativeName;
this.latitude = latitude;
this.longitude = longitude;
this.currencyCode = currencyCode;
// getters & setters
}
【问题讨论】:
-
您正在尝试将 one 国家对象反序列化为 JSON 到国家的 array 对象。
-
那我该怎么办?
-
你想要一个国家,所以你应该告诉杰克逊你想要那个作为反序列化的结果:
Country country = mapper.readValue(userDataJSON, Country.class);
标签: java json deserialization