I’ve a little problem with 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.
I want to convert back into ProtoAuth object..How I can know that is a ProtoAuth? Using the “action” params in ProtoQuery.
I need something like
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:
and to deserialize with a param of type ProtoAuth, you can call as followed: