我从httpresponse
获得以下json{
"result": "success",
"team_registration": {
"current_status": "executed",
"expiration_time": "2012-07-18T21:29:43Z",
"id": 609,
"team_id": 50,
}
}
如何将“结果”作为字符串进行检索,将“team_registration”作为POJO(在Android中)与杰克逊进行检索?
目前我有这个:
HttpResponse response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
String json = EntityUtils.toString(entity);
Map<String, Object> map = mapper.readValue(json, new TypeReference<Map<String, Object>>() {
});
result = (String) map.get("result");
resultRegistration = (Registration) map.get("team_registration");
注册课程:
package be.radarwerk.app.model;
import java.io.Serializable;
import java.util.Date;
import org.codehaus.jackson.annotate.JsonIgnore;
public class Registration implements Serializable { // Todo implements parceable?
private static final long serialVersionUID = 1L;
private int id;
private String currentStatus;
private Date expirationTime;
@JsonIgnore
private Volunteer volunteer;
@JsonIgnore
private Team team;
public Registration() {
}
public Registration(int id, String currentStatus, Volunteer volunteer,
Team team) {
super();
this.id = id;
this.currentStatus = currentStatus;
this.volunteer = volunteer;
this.team = team;
}
public int getId() {
return id;
}
public String getCurrentStatus() {
return currentStatus;
}
public Volunteer getVolunteer() {
return volunteer;
}
public Team getTeam() {
return team;
}
public Date getExpirationTime() {
return expirationTime;
}
}
“result”因为String工作正常但是对于“registration_moment”我得到了这个异常: java.lang.ClassCastException:java.util.LinkedHashMap无法强制转换为注册
我也尝试以与“result”相同的方式将其转换为String,并对该字符串执行mapper.readValue。 没有成功。
任何提示?
答案 0 :(得分:1)
如果您按照此类修改(注意!Jackson 2.1+必需),您的课程应自动反序列化:
@JsonIgnoreProperties("team_id")
@JsonNamingStrategy(PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy)
public class Registration implements Serializable
{
private static final long serialVersionUID = 1L;
private int id;
private String currentStatus;
private Date expirationTime;
@JsonIgnore
private Volunteer volunteer;
@JsonIgnore
private Team team;
public Registration() {
}
// other code
}
然后,在您的代码中反序列化:
Registration registration;
final JsonNode node = mapper.readTree(json);
if (node.get("result").textValue().equals("success"))
registration = mapper.readObject(node.get("team_registration").traverse(),
Registration.class);
答案 1 :(得分:1)
你的方法对我来说似乎有些奇怪。你应该真的使用Android JSONObject类,这就是它的用途。一旦有了JSONObject(或JSONArray),如果要将元素移动到不同的数据结构中,则需要对其进行迭代,但这很可能是不必要的。
无论如何,这里有一些代码(使用android-query)来获取JSONObject:
String url = "whatever you want";
aq.ajax(url, JSONArray.class, new AjaxCallback<JSONArray>() {
@Override
public void callback(String url, JSONArray json, AjaxStatus status) {
if (json == null) {
Toast.makeText(context, "Failed to retrieve JSON", Toast.LENGTH_SHORT);
}
else {
try {
JSONObject general = json.getJSONObject(0);
...
}
}
}
});