The problem is that the data type contained in the array is unknown before execution. I created a test case to illustrate my problem. Everything works fine until it comes to arrays.
User user1 = new User(1, "one");
User user2 = new User(2, "two");
User [] users = {user1, user2};
Gson gson = new Gson();
String toJson = gson.toJson(users, User[].class);
User [] newUsers = gson.fromJson(toJson, User[].class);
for(User user : newUsers) {
System.out.println(user.toString());
}
final Class<?> userType = Class.forName("com.abc.ws.GsonTest$User");
User user3 = new User(3, "three");
toJson = gson.toJson(user3, userType);
Object newUser = gson.fromJson(toJson, userType);
System.out.println(newUser.toString());
toJson = gson.toJson(users, WHAT_TO_PASS_HERE?);
Object newerUsers = gson.fromJson(toJson, WHAT_TO_PASS_HERE?);
for(User user : newerUsers) {
System.out.println(user.toString());
}
btw: Below is the full code.
package com.abc;
import com.google.gson.Gson;
public class GsonTest {
public static void main(String[] args) throws Exception {
GsonTest.go();
}
public static void go() throws Exception {
User user1 = new User(1, "one");
User user2 = new User(2, "two");
User [] users = {user1, user2};
Gson gson = new Gson();
String toJson = gson.toJson(users, User[].class);
User [] newUsers = gson.fromJson(toJson, User[].class);
for(User user : newUsers) {
System.out.println(user.toString());
}
final Class<?> userType = Class.forName("com.abc.GsonTest$User");
User user3 = new User(3, "three");
toJson = gson.toJson(user3, userType);
Object newUser = gson.fromJson(toJson, userType);
System.out.println(newUser.toString());
toJson = gson.toJson(users, WHAT_TO_PASS_HERE?);
Object newerUsers = gson.fromJson(toJson, WHAT_TO_PASS_HERE?);
for(User user : newerUsers) {
System.out.println(user.toString());
}
}
public static class User {
private int id;
private String name;
public User() { }
public User(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return "id: " + this.id + ", name: " + this.name;
}
}
}
source
share