gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:14:47 24 4
gpt4 key购买 nike

我对 GSON-JSON 有点问题。

让我们看下面的代码:

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

这里的问题:deserializedOBJ.object 返回一个 LinkedHashMap。我想转换回 ProtoAuth 对象。我怎么知道那是 ProtoAuth?在 ProtoQuery 中使用“action”参数。

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

执行此操作的最佳方法是什么?有一种替代方法可以做到这一点,而无需编写我自己的序列化程序/反序列化程序吗?

实际上我使用了那个代码:

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

最佳答案

我会按如下方式输入 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;
}
}

要使用 ProtoAuth 类型的参数进行反序列化,您可以按以下方式调用:

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

关于java - GSON-JSON反序列化类中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10567867/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com