如何使用改造和parceler库解析Json

时间:2015-08-10 12:54:04

标签: android retrofit parceler

我已经读过,根据这篇博文http://blog.robinchutaux.com/blog/a-smart-way-to-use-retrofit/

,更好的方法是使用parcelable而不是serialisable进行解析

但是如何使用Parceler库(https://github.com/johncarl81/parceler)自定义解析?

在GSON库中我们可以这样做:

public class GuestEntityDeserializer implements JsonDeserializer<GuestEntity> {

    private static final String ID = "id";
    private static final String FIRST_NAME = "firstname";
    // other fields...

    @Override
    public GuestEntity deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
            throws JsonParseException {
        final GuestEntity guestEntity = new GuestEntity();
        final JsonObject jsonObject = json.getAsJsonObject();

        guestEntity.setId(jsonObject.get(ID).getAsString());
        guestEntity.setFirstName(jsonObject.get(FIRST_NAME).getAsString());
        guestEntity.setLastName(jsonObject.get(LAST_NAME).getAsString());
        // and so on...

        return guestEntity;
    }

像这样配置GsonBuilder:

        final Gson gson = new GsonBuilder()
                .registerTypeAdapter(GuestEntity.class, new GuestEntityDeserializer())
                .create();

所以,问题是:如何使用Retrofit和Parceler库解析json字符串?例如,我需要两个具有以下模型的对象。

@Parcel
public class MatchModel {

    @SerializedName("id")
    private String mId;
    @SerializedName("first")
    private String mFirst;
    @SerializedName("last")
    private String mLast;
    @SerializedName("ilike")
    private String mIlike;
    @SerializedName("created_at")
    private String mCreatedAt;
    @SerializedName("liketo")
    private String mLiketo;
    @SerializedName("firstname")
    private String mFirstName;
    @SerializedName("lastname")
    private String mLastName;
    @SerializedName("birthday")
    private String mBirthday;

    //  getters and setters
}

我需要解析一下:

{
  "1277": {
    "id": "322",
    "first": "1294",
    "last": "1277",
    "ilike": "1",
    "created_at": "2015-07-31 18:51:47",
    "liketo": "1277",
    "firstname": "Alex",
    "lastname": "Alexov",
    "birthday": null
  },
  "1312": {
    "id": "951",
    "first": "1294",
    "last": "1312",
    "ilike": "1",
    "created_at": "2015-08-06 15:12:29",
    "liketo": "1312",
    "firstname": "Roman",
    "lastname": "Romanov",
    "birthday": "1990-06-23"
  }
}

1 个答案:

答案 0 :(得分:3)

使用改造解析

RestAdapter restAdapter = new RestAdapter.Builder()
   .setEndpoint("url")
   .setClient(new OkClient(new OkHttpClient()))
   .build();

getMatchModel mMatchModel= restAdapter.create(getMatchModel.class);
Map<String, MatchModel > mMatchModelMaps = mMatchModel.MatchModel(params..);


public interface getMatchModel {
   @GET("/{params}")
   Map<String, MatchModel > MatchModel(@Path("params") String params);
}