【发布时间】:2012-07-10 10:45:17
【问题描述】:
我在使用 jackson 库将 Json API 回调转换为自定义对象时遇到了映射问题。
我有我的用户自定义类:
public class User {
protected String id;
protected GregorianCalendar registredAt;
protected String username;
protected Team team;
public User() {
}
public User(String id, GregorianCalendar registredAt, String username, Team team) {
this.id = id;
this.registredAt = registredAt;
this.username = username;
this.team = team;
}
public User(HashMap<String, Object> attributes) {
this.id = (String) attributes.get("id");
this.registredAt = (GregorianCalendar) attributes.get("registredAt");
this.username = (String) attributes.get("username");
this.team = (Team) attributes.get("team");
}
}
这是我的回调:
{
id: "4feab37c5600bbd56f000132",
registredAt: {
date: "2012-06-27 09:17:15",
timezone_type: 3,
timezone: "Europe/Paris"
},
username: "John Doe",
team: {
id: "4feab37c5600bbd56f000130",
indice: 1,
name: "John Doe's Team",
score: 200
}
}
然后,我尝试初始化一个用户对象:
// Code from a doInBackground() method of a custom AsyncTask.
URL completePath = new URL(apiBaseURL + "api/user/4feab37c5600bbd56f000132/show");
APIconnection = (HttpURLConnection) completePath.openConnection();
APIconnection.setDoInput(true);
APIconnection.connect();
callbackParser = jsonFactory.createJsonParser(APIconnection.getInputStream());
response = objectMapper.readValue(callbackParser, User.class);
// Catch a JsonMappingException :
Can not deserialize instance of java.util.Calendar out of START_OBJECT token at [Source: org.apache.harmony.luni.internal.net.www.protocol.http.FixedLengthInputStream@4082c7a0; line: 1, column: 33] (through reference chain: classes.models.User["registredAt"])
我认为问题在于回调 registredAt 对象是一个 json_encoded PHP \DateTime 实例... 我应该更改registredAt Java User 对象的类型吗? 还是我的构造函数中缺少某些东西?
【问题讨论】:
-
您的公历课程是否从日历扩展而来?它是否实现了 Serializable 接口?
-
这是扩展 java.util.Calendar 的 java.util.GregorianCalendar 类,它实现了 Serializable 接口 :) 当我用 Calendar 类(java.util 命名空间的)替换 GregorianCalendar 时,问题是一样的无法从 START_OBJECT 令牌中反序列化 java.util.Calendar 的实例。
-
Serializable 无关紧要——它不会被 JSON 序列化程序使用,因为它只意味着 JDK 可以生成二进制表示。
标签: php android json datetime jackson