java - 为具有不同对象的嵌套 json 改造 gson 转换器

标签 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"
        }
    }
}

以上格式很常见。只有 data 键可以保存不同类型的信息,如 userproductinvoice 等。

我想在每个休息响应中保持 statusmessagedata 键相同。 data 将根据 status 进行处理,message 将显示给用户。

所以基本上,所有 api 都需要上述格式。 只有data键里面的信息每次都会不同。

我已经设置了以下类并将其设置为 gson 转换器 - 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;
    }
}

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

    }
}

并使用如下 -

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

restBuilder.setConverter(new GsonConverter(gsonBuilder.create()));

服务接口(interface)如下 -

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


@POST("/other")
public void test2(Callback<MyResponse<Product>> apiResponseCallback);

问题

我可以从回调内部访问 statusmessage 字段。但是 data 键中的信息没有被解析,像 MeUserProduct 这样的模型总是返回为空。

如果我将 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"
        }
    }

如何在 data 对象中指定单独的键并成功解析它?

最佳答案

如果我可以建议更改 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"
    }
}

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
}

DataType 是一个定义数据类型的枚举。您必须在构造函数中将 Data.class 作为参数传递。对于所有数据类型,您必须创建新类。 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;
    }
}

Json 的解串器应该如下所示:

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;

    }
}

当你创建 RestAdapter 时,在你注册 Deserializator 的那一行,你应该使用这个:

 .registerTypeAdapter(MyResponse.class, new DeserializerJson())

您定义的其他类(数据类型)如 Gson 的标准 POJO 在单独的类中。

关于java - 为具有不同对象的嵌套 json 改造 gson 转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29026596/

相关文章:

java - JVM 如何收集 ThreadDump 底层

java - 覆盖字段初始化

android - 如何使光标停留在edittext的中心

javascript - 将 JSON 对象列表从 javascript 发送到 MVC 操作

java - 如何使用 Fiddler 避免 JAVA 证书警告

java.security.cert.CertificateException : No subject alternative DNS name matching

jQuery Mobile taphold 事件触发浏览器对话框

android - 如何为 Android 平板电脑布局实现固定左 Pane ?

javascript - DotNetBrowser : passing a json string from .Net 到接受 json 对象的 JavaScript 函数

javascript - 解析 JSON 响应