改造用于嵌套json的gson转换器与不同的对象

Gim*_*ali 16 java android json gson retrofit

我的JSON结构如下 -

{
    "status": true,
    "message": "Registration Complete.",
    "data": {
        "user": {
            "username": "user88",
            "email": "user@domain.com",
            "created_on": "1426171225",
            "last_login": null,
            "active": "1",
            "first_name": "User",
            "last_name": "",
            "company": null,
            "phone": null,
            "sign_up_mode": "GOOGLE_PLUS"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

以上格式很常见.只有data钥匙可以容纳不同类型的信息,如user,product,invoice等.

我想保留status,messagedata在每个休息响应中键入相同的键.data将根据待治疗statusmessage将被显示给用户.

所以基本上,所有api都需要以上格式.每次只有data密钥内的信息会有所不同.

我已经设置了以下类并将其设置为gson converter - MyResponse.java

public class MyResponse<T> implements Serializable{
    private boolean status ;
    private String message ;
    private T data;

    public boolean isStatus() {
        return status;
    }

    public void setStatus(boolean status) {
        this.status = status;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}
Run Code Online (Sandbox Code Playgroud)

Deserializer.java

class Deserializer<T> implements JsonDeserializer<T>{
    @Override
    public T deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException{
        JsonElement content = je.getAsJsonObject();

        // Deserialize it. You use a new instance of Gson to avoid infinite recursion to this deserializer
        return new Gson().fromJson(content, type);

    }
}
Run Code Online (Sandbox Code Playgroud)

并使用如下 -

GsonBuilder  gsonBuilder = new GsonBuilder();
gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); 
gsonBuilder.registerTypeAdapter(MyResponse.class, new Deserializer<MyResponse>());
...... ..... ....

restBuilder.setConverter(new GsonConverter(gsonBuilder.create()));
Run Code Online (Sandbox Code Playgroud)

服务界面如下 -

@POST("/register")
public void test1(@Body MeUser meUser, Callback<MyResponse<MeUser>> apiResponseCallback);


@POST("/other")
public void test2(Callback<MyResponse<Product>> apiResponseCallback);
Run Code Online (Sandbox Code Playgroud)

问题

我可以从回调内部访问statusmessage字段.但是datakey中的信息没有被解析,模型就像MeUser并且Product总是返回为空.

如果我将json结构更改为以下代码完美无缺 -

{
        "status": true,
        "message": "Registration Complete.",
        "data": {                
                "username": "user88",
                "email": "user@domain.com",
                "created_on": "1426171225",
                "last_login": null,
                "active": "1",
                "first_name": "User",
                "last_name": "",
                "company": null,
                "phone": null,
                "sign_up_mode": "GOOGLE_PLUS"
        }
    }
Run Code Online (Sandbox Code Playgroud)

如何使用指定单独的键内部data对象并成功解析它?

Kon*_*iak 24

如果我可以建议在json中更改某些内容,则必须在一个定义数据类型的新字段中添加,因此json应如下所示:

{
   "status": true,
   "message": "Registration Complete.",
   "dataType" : "user",
   "data": {                
            "username": "user88",
            "email": "user@domain.com",
            "created_on": "1426171225",
            "last_login": null,
            "active": "1",
            "first_name": "User",
            "last_name": "",
            "company": null,
            "phone": null,
            "sign_up_mode": "GOOGLE_PLUS"
    }
}
Run Code Online (Sandbox Code Playgroud)

MyResponse班必须有新的申请DataType,因此应如下:

public class MyResponse<T> implements Serializable{
    private boolean status ;
    private String message ;
    private DataType dataType ;
    private T data;


    public DataType getDataType() {
        return dataType;
    }

    //... other getters and setters
}
Run Code Online (Sandbox Code Playgroud)

DataType是一个定义数据类型的枚举.您必须在构造函数中将Data.class作为param传递.对于所有数据类型,您必须创建新类.DataType枚举应如下所示:

public enum DataType {

    @SerializedName("user")
    USER(MeUser.class),
    @SerializedName("product")
    Product(Product.class),
    //other types in the same way, the important think is that 
    //the SerializedName value should be the same as dataType value from json 
    ;


    Type type;

    DataType(Type type) {
        this.type = type;
    }

    public Type getType(){
        return type;
    }
}
Run Code Online (Sandbox Code Playgroud)

Json的desarializator应如下所示:

public class DeserializerJson implements JsonDeserializer<MyResponse> {

    @Override
    public MyResponse deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
            throws JsonParseException {
        JsonObject content = je.getAsJsonObject();
        MyResponse message = new Gson().fromJson(je, type);
        JsonElement data = content.get("data");
        message.setData(new Gson().fromJson(data, message.getDataType().getType()));
        return message;

    }
}
Run Code Online (Sandbox Code Playgroud)

当您RestAdapter在注册Deserializator的行中创建时,您应该使用:

 .registerTypeAdapter(MyResponse.class, new DeserializerJson())
Run Code Online (Sandbox Code Playgroud)

您定义的其他类(数据类型),如分离类中的Gson标准POJO.