简体   繁体   English

GSON-JSON反序列化类中的对象

[英]GSON-JSON Deserialize Object in Class

I've a little problem with GSON-JSON. 我对GSON-JSON有点问题。

Let see the following code: 让我们看下面的代码:

    public static class ProtoQuery {
    public String action;
    public String token;
    public Object params;

    public ProtoQuery(String action, String token, Object params) {
        this.action = action;
        this.token = token;
        this.params = params;
    }
}


// Authentication Phase
public static class ProtoAuth {
    public String username;
    public String password;

    public ProtoAuth(String username, String password) {
        this.username = username;
        this.password = password;
    }
}


    // Serialize Object
    Gson gson = new Gson();
    ProtoQuery tmp = new ProtoQuery("ProtoAuth", "", new JirckeProtocol.ProtoAuth("ABC", "myPASS"));
    String json = gson.toJson(tmp);

    // Deserialize Object
    ProtoQuery deserializedOBJ = gson.fromJson(json, ProtoQuery.class);

Here the problem: deserializedOBJ.object return a LinkedHashMap. 这里的问题是:deserializedOBJ.object返回一个LinkedHashMap。 I want to convert back into ProtoAuth object..How I can know that is a ProtoAuth? 我想转换回ProtoAuth对象。如何得知这是ProtoAuth? Using the "action" params in ProtoQuery. 在ProtoQuery中使用“操作”参数。

I need something like deserializedOBJ.params = gson.fromJSON(json.object, ProtoAuth.class) 我需要类似deserializedOBJ.params = gson.fromJSON(json.object,ProtoAuth.class)的东西

What's the best way to do this? 最好的方法是什么? There is an alternative to do this, without write my own serializer/deserialer? 还有另一种方法,而无需编写我自己的序列化器/解串器?

Actually I use that code: 实际上,我使用该代码:

deserializedOBJ.params = gson.fromJson(element, Class.forName("MyProtocol$ProtoAuth"));

I would type ProtoQuery as following: 我将输入ProtoQuery如下:

public static class ProtoQuery<T> {
    public String action;
    public String token;
    public T params;

    public ProtoQuery(String action, String token, T params) {
        this.action = action;
        this.token = token;
        this.params = params;
    }
}


// Authentication Phase
public static class ProtoAuth {
    public String username;
    public String password;

    public ProtoAuth(String username, String password) {
        this.username = username;
        this.password = password;
    }
}

and to deserialize with a param of type ProtoAuth, you can call as followed: 并使用ProtoAuth类型的参数反序列化,可以调用如下:

Type type = new TypeToken<ProtoQuery<ProtoAuth>>() {}.getType();
ProtoQuery<ProtoAuth> deserializedOBJ = gson.fromJson(json, type);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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