/**
-
@Author : JCccc
-
@CreateTime : 2018-11-27
-
@Description :
-
@Point: Keep a good mood
**/
public class testMain {
public static void main(String[] args) {
//手动创的一个实体类, 里面字段全是String类型
User userTest=new User();
userTest.setName(“joke”);
userTest.setAge(“16岁”);
userTest.setHeight(“60Kg”);
userTest.setSex(“男”);
Gson gson=new Gson();
String jsonStr=gson.toJson(userTest,User.class);
System.out.println(“对象转JSON—”+jsonStr);
User userTestNew=gson.fromJson(jsonStr,User.class);
System.out.println(“JSON转对象—”+userTestNew.toString());
Map map=new LinkedHashMap();
map.put(“name”,“merry”);
map.put(“age”,“17岁”);
map.put(“height”,“62Kg”);
map.put(“sex”,“女”);
String mapJsonStr=gson.toJson(map);
System.out.println(“map转JSON—”+mapJsonStr);
List userList = new ArrayList<>();
userList.add(userTest);
// System.out.println(userList.toString());
String listJsonStr=gson.toJson(userList);
System.out.println(“list转JSON—”+listJsonStr);
List retList = gson.fromJson(listJsonStr,new TypeToken<List>(){}.getType());
System.out.println(“listJSON转list—”+retList);
//报错
// List retList1 = gson.fromJson(mapJsonStr,new TypeToken<List>(){}.getType());
// System.out.println(“mapJSON转list—”+retList1);
//报错
/*List retList2 = gson.fromJson(jsonStr,new TypeToken<List>(){}.getType());
System.out.println(“对象JSON转list—”+retList2);*/
}
}
运行结果:
对象转JSON—{“name”:“joke”,“age”:“16岁”,“height”:“60Kg”,“sex”:“男”}
map转JSON—{“name”:“merry”,“age”:“17岁”,“height”:“62Kg”,“sex”:“女”}