类MyObject<T>,有个属性List<T> list, 不能用Gson将一个MyObject<User>类型的对象obj转成json的原因是?
代码如下:publicclassMyObject<T>{privateList<T>list;publicList<T>getList(){returnlist;}pub...
代码如下:
public class MyObject<T>{
private List<T> list;
public List<T> getList(){ return list;}
public void setList(List<T> list) {this.list=list;}
}
public class User{
private String id;
private String name;
//.......getters/setters and constructors
}
public class Test{
public static void main(String[] args){
User user1 = new User("1","zhangsan1");
User user2 = new User("1","zhangsan2");
User user3 = new User("1","zhangsan2");
List<User> list = new ArrayList<>();
list.add(user1);
list.add(user2);
list.add(user3);
MyObject<User> obj = new MyObject<>();
obj.setList(list);
Gson gson = new Gson();
String json = gson.toJson(obj);//json 中list不包含任何信息????为什么??
System.out.println(json);//如果将MyObject的泛型去除,则list包含User的信息????为什么??
}
}
我自己解决了,方法如下:
最后几行代码改为
Gson gson = new Gson();
Type type = new TypeToken<MyObject<User>>(){}.getType();
String json = gson.toJson(obj,type);
System.out.println(json); 展开
public class MyObject<T>{
private List<T> list;
public List<T> getList(){ return list;}
public void setList(List<T> list) {this.list=list;}
}
public class User{
private String id;
private String name;
//.......getters/setters and constructors
}
public class Test{
public static void main(String[] args){
User user1 = new User("1","zhangsan1");
User user2 = new User("1","zhangsan2");
User user3 = new User("1","zhangsan2");
List<User> list = new ArrayList<>();
list.add(user1);
list.add(user2);
list.add(user3);
MyObject<User> obj = new MyObject<>();
obj.setList(list);
Gson gson = new Gson();
String json = gson.toJson(obj);//json 中list不包含任何信息????为什么??
System.out.println(json);//如果将MyObject的泛型去除,则list包含User的信息????为什么??
}
}
我自己解决了,方法如下:
最后几行代码改为
Gson gson = new Gson();
Type type = new TypeToken<MyObject<User>>(){}.getType();
String json = gson.toJson(obj,type);
System.out.println(json); 展开
2015-12-07
展开全部
public static void SetPositionX(this Transform tran, float x)
{
tran.position = new Vector3(x, tran.position.y, tran.position.z);
}
{
tran.position = new Vector3(x, tran.position.y, tran.position.z);
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询