使用gson-2.2.4.jar来处理json数据

来源:互联网 发布:php 判断是微信浏览器 编辑:程序博客网 时间:2024/05/17 01:01
public class TestGSON {    @Test    public void testObjectToJSON() {        List<Student> list = new ArrayList<Student>();        Student s = new Student();        Student s3 = new Student();        s.setName("张三");        s.setSex("男");        s3.setName("李四");        s3.setSex("男");        list.add(s);        list.add(s3);        Gson g = new Gson();        String str = g.toJson(s);        System.out.println("bean对象转化成json字符串为");        System.out.println(str);        Student s1 = g.fromJson(str, Student.class);        System.out.println("json字符串转化为bean对象");        System.out.println(s1.getName()+" "+s1.getSex());        Map<String, String> m1 = g.fromJson(str, new TypeToken<Map<String,String>>(){}.getType());        System.out.println("json字符串转化为map");        System.out.println(m1.get("name")+" "+m1.get("sex"));        String liststr = g.toJson(list);        System.out.println("List<Object>转化为json字符串");        System.out.println(liststr);        List<HashMap<String, String>> listh = g.fromJson(liststr, new TypeToken<List<HashMap<String, String>>>(){}.getType());        System.out.println("json字符串转化为list<map>");        System.out.println(listh.get(0).get("name")+" "+listh.get(1).get("name"));    }}
0 0
原创粉丝点击