简体   繁体   中英

Deserialize json with different object types

I get the following json from a httpresponse

{
"result": "success",
"team_registration": {
    "current_status": "executed",
    "expiration_time": "2012-07-18T21:29:43Z",
    "id": 609,
    "team_id": 50,
    }
}

How do I retreive the "result" as a string and the "team_registration" as a POJO (in Android) with Jackson?

Currently I have this:

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");

Registration class:

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" as String works fine but for the "registration_moment" I get this exception: java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to Registration

I also tried casting it to a String in the same way as "result" and doing mapper.readValue on that string. No success.

Any tips?

Your class should be deserialized automatically if you modify it like this ( Note! Jackson 2.1+ required ):

@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
}

Then, to deserialize in your 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);

Your approach seems a bit odd to me. You should really be using the Android JSONObject class, that's what it's there for. Once you have a JSONObject (or JSONArray), you will need to iterate over it if you want to move elements into a different data structure, but that's very likely unnecessary.

In any event, here's some code (using android-query ) to get you to a 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);
                ...
            }
        }
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM