首页 > Web开发 > 详细

JSON

时间:2021-02-26 14:24:11      阅读:16      评论:0      收藏:0      [点我收藏+]

转:

JSON

Gson

public class Demo_Gson {
    public static void main(String[] args) {
        //1、创建Gson对象
        Gson g = new Gson();
        //2、将对象转换为JSON字符串 String json = new Gson().toJSON(要转换的对象);
        Book b = new Book("1002","金苹果","种苹果");
        String json = g.toJson(b);
        System.out.println(json);
        //3、将JSON字符串转换为对象 对象 = new Gson().fromJson(JSON字符串,对象类型.class);
        //Book b1 = g.fromJson(json,Book.class);
        //转换为Book对象
        Book b1 = g.fromJson("{"id":"1002","name":"金苹果","info":"种苹果"}",Book.class);
        System.out.println(b1.getId());
        //转换为Hashmap对象
        HashMap data = g.fromJson("{"id":"1002","name":"金苹果","info":"种苹果"}",HashMap.class);
        System.out.println(data.get("id"));
    }
}

技术分享图片
若JSON文件中有数组格式,转换为对象时,数组类型会变成ArrayList

public class Demo1 {
    public static void main(String[] args) {
        //1.    创建Gson对象
        Gson g = new Gson();
        //2.    将JSON字符串转换为对象   :  {"id":"100","name":"金苹果","info":"种植苹果真辛苦","page":["锄禾日当午","汗滴禾下土","嘿嘿嘿嘿嘿"]}
        HashMap data = g.fromJson("{"id":"100","name":"金苹果","info":"种植苹果真辛苦","page":["锄禾日当午","汗滴禾下土","嘿嘿嘿嘿嘿"]}", HashMap.class);
        List page = (List) data.get("page");
        System.out.println(data.get("page").getClass());
        System.out.println(page.get(1));
    }
}

技术分享图片
FastJson

public class Demo_FastJson {
    public static void main(String[] args) {
        Book b = new Book("1002","金苹果","种苹果");
        //将对象转换为JSON字符串 String json=JSON.toJSONString(要转换的对象);
        String json = JSON.toJSONString(b);
        System.out.println(json);
        //将JSON字符串转换为对象
        //类型 对象名=JSON.parseObject(JSON字符串, 类型.class)
        Book b1 = JSON.parseObject("{"id":"1002","name":"金苹果","info":"种苹果"}",Book.class);
        System.out.println(b1.getId());
        //或List<类型> list=JSON.parseArray(JSON字符串,类型.class)
        List<String> list = JSON.parseArray("["锄禾日当午","汗滴禾下土","嘿嘿嘿嘿嘿"]",String.class);
        System.out.println(list.get(1));
    }
}

技术分享图片

转:

JSON

JSON

原文:https://www.cnblogs.com/wangtcc/p/14451587.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!