JAVA Gson的使用

/**

  • @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”:“女”}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值