JSON解析学习笔记(json、gson、fastjson)

JSON解析学习笔记

JSON(JavaScript Object Notation Javascript):表示对象的一种方式,是基于JavaScript语言的轻量级数据交换格式(即:用来传输数据的一种格式)。
首先,我们先来比较下JSON和XML的区别:
JSON数据量小,可读性差,功能单一,只能用于保存数据。
XML数据量大,可读性好,可以用于软件配置和布局绘图、保存数据等。
可以通过使用bejson - 在线JSON校验格式化工具(Be JSON)快速将XML转为JSON格式。

JSON的表示结构:
JSON就是一串字符串 只不过元素会使用特定的符号标注。
{} 双括号表示对象
[] 中括号表示数组
“” 双引号或’’单引号内是属性或值
: 冒号表示后者是前者的值(这个值可以是字符串、数字、也可以是另一个数组或对象)
所以 {“name”: “zhangsan”} 可以理解为是一个包含name为zhangsan的对象,而[{“name”: “zhangsan”},{“name”: “lisi”}]就表示包含两个对象的数组 。

下面是一些示例:
1、表示对象:{brand:’宝马’,color:’red’,price:150}
2、表示数组:[{brand:’宝马’,color:’red’,price:150},{brand:’宝马’,color:’red’,price:150}, {brand:’宝马’,color:’red’,price:150},{brand:’宝马’,color:’red’,price:150}]
3、表示复杂的对象:{brand:’宝马’,color:’red’,price:150,engine:{company:’无名’,horsePower:‘400’}}
4、表示含有数组或者集合的对象:{address:’**’,time’2016-1-1’,cars:[{brand:’宝马’,color:’red’,price:150},{brand:’宝马’,color:’red’,price:150}, {brand:’宝马’,color:’red’,price:150},{brand:’宝马’,color:’red’,price:150}]}

JSON解析(Android自带的解析方式)
1.当JSON字符串以“{”开始,用JSONObject解析
JSONObject部分方法
getString(String key)根据键找到对应该的值
getInt(String key) 得到int类型的值
getJSONObject(String key)得到JSONObject
put(String key,String/Boolean/Object^^)
构造方法
new JSONObject(String source) 把对应的String类型的JSON数据转成JSON的对象
new JSONObject(Object bean) 将bean对象转成Json对象,用于转成json字符串
2.当JSON字符串以“[”开始,用JSONArray解析
JSONArray部分方法
getJSONObject(int index);
length()
构造方法
new JSONArray(Collection list)
new JSONArray(String jStr)
注意:
解析时用含参构造创建对象。
组装时用无参构造创建对象。
{}—-遇到{}用JSONObject
[]—-遇到[]用JSONArray

JSON解析的三种方式(都需要自己将jia包导入到相应项目):
1.json原生解析(最灵活,步骤复杂)
步骤:
* 导入jar包
* 看见{},创建JSONObject对象
* 看见[],创建JsonArray对象

private static void testObject() throws JSONException {
        String jsonStr = "{brand:'宝马',price:150,clr:'red'}";

        //1.解析简单对象:参数是要解析的字符串
        JSONObject jObject = new JSONObject(jsonStr);

        //2.解析
        Car car = new Car();
        String brand = jObject.getString("brand");
        car.setBrand(brand);
        car.setColor(jObject.getString("clr"));
        car.setPrice(jObject.getInt("price"));

        System.out.println(car);
    }
//解析含有数组的字符串
    private static void testArray() throws JSONException {
        String jsonString = "[{brand:'宝马',color:'red',price:150},{brand:'路虎',color:'black',price:180},{brand:'法拉利',color:'yellow',price:200}]";

        JSONArray jArray = new JSONArray(jsonString);
//      System.out.println(jArray.length());
        List<Car> carList = new ArrayList<>();
        for (int i = 0; i < jArray.length(); i++) {
            JSONObject jObject = jArray.getJSONObject(i);
            Car car = new Car();
            car.setBrand(jObject.getString("brand"));
            car.setColor(jObject.getString("color"));
            car.setPrice(jObject.getInt("price"));

            carList.add(car);
        }
        System.out.println(carList);

    }

既含有对象也含有数组


public class HWJSON {

    public static void main(String[] args) throws IOException, JSONException {
        String url = "http://api.1-blog.com/biz/bizserver/xiaohua/list.do";
        String str = new HttpDownload().HttpDownLoad(url);//通过Http请求获得要解析的JSON字符串
//      System.out.println(str);
        List<DetailInfo> list = new ArrayList<>();//创建用于存放DetailInfo信息的集合
        Info info = new Info();
        JSONMethod(str, list, info);//JSON数据解析
        info.setDetail(list);
        System.out.println(info);//输出解析后的结果
    }

    public static void JSONMethod(String str, List<DetailInfo> list, Info info)
            throws JSONException {
        JSONObject jo = new JSONObject(str);//将要解析的字符串转为JSON对象
        info.setStatus(jo.getString("status"));
        info.setDesc(jo.getString("desc"));
        JSONArray jsonObject = jo.getJSONArray("detail");
                for (int i = 0; i < jsonObject.length(); i++) {
            JSONObject jsono = jsonObject.getJSONObject(i);

            DetailInfo detailInfo = new DetailInfo();
            detailInfo.setId(jsono.getInt("id"));
            detailInfo.setXhid(jsono.getInt("xhid"));
            detailInfo.setAuthor(jsono.getString("author"));
            detailInfo.setContent(jsono.getString("content"));
            detailInfo.setPicUrl(jsono.getString("picUrl"));
            detailInfo.setStatus(jsono.getInt("status"));
            list.add(detailInfo);

        }
    }

}

注:DetailInfo.class 、Info.class、HttpDownload.class三个类由于下面还会调用到,因此放在了文章末尾。
2.gson
Gson 是 Google 提供的用来在 Java 对象和 JSON 数据之间进行映射的 Java 类库。可以将一个 JSON 字符串转成一个 Java 对象,或者反过来。需要jar包:
用法:
Gson gson=new Gson()
1) fromJson(String json,Class.class)把JSON转成对应的对象【注意】:类和属性和json的键要对应
2) fromJson(String json,new TypeToken

String url = "http://api.1-blog.com/biz/bizserver/xiaohua/list.do";
        String str = new HttpDownload().HttpDownLoad(url);//获得要解析的JSON字符串
        Gson gson = new Gson();
        Info info = gson.fromJson(str, Info.class);
        System.out.println(info);

3.fastjson
部分方法:
JSON.parseObject(json, Person.class) 把JSON数据转成对象
JSON.parserArray(json,Person.class)把JSON数据转成集合
JSON.toJSONString(Object obj)把对象转成json

String url = "http://api.1-blog.com/biz/bizserver/xiaohua/list.do";
        String str = new HttpDownload().HttpDownLoad(url);//获得要解析的JSON字符串

        Info info = JSON.parseObject(str,Info.class);

        System.out.println(info);

Info.class


public class Info {
    private String status;
    private String desc;
    List<DetailInfo> detail;
    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
    public String getDesc() {
        return desc;
    }
    public void setDesc(String desc) {
        this.desc = desc;
    }

    public List<DetailInfo> getDetail() {
        return detail;
    }
    public void setDetail(List<DetailInfo> detail) {
        this.detail = detail;
    }
    public Info() {
        super();
        // TODO Auto-generated constructor stub
    }
    public Info(String status, String desc, List<DetailInfo> detail) {
        super();
        this.status = status;
        this.desc = desc;
        this.detail = detail;
    }
    @Override
    public String toString() {
        return "Info [status=" + status + ", desc=" + desc + ", detail="
                + detail + "]\n";
    }


}

DetailInfo.class

public class DetailInfo {

    private int id;
    private int xhid;
    private String author;
    private String content;
    private String picUrl;
    private int status;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public int getXhid() {
        return xhid;
    }
    public void setXhid(int xhid) {
        this.xhid = xhid;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public String getPicUrl() {
        return picUrl;
    }
    public void setPicUrl(String picUrl) {
        this.picUrl = picUrl;
    }
    public int getStatus() {
        return status;
    }
    public void setStatus(int status) {
        this.status = status;
    }
    public DetailInfo() {
        super();
        // TODO Auto-generated constructor stub
    }
    public DetailInfo(int id, int xhid, String author, String content,
            String picUrl, int status) {
        super();
        this.id = id;
        this.xhid = xhid;
        this.author = author;
        this.content = content;
        this.picUrl = picUrl;
        this.status = status;
    }
    @Override
    public String toString() {
        return "detail [id=" + id + ", xhid=" + xhid + ", author=" + author
                + ", content=" + content + ", picUrl=" + picUrl + ", status="
                + status + "]\n";
    }

}

HttpDownload.class


public class HttpDownload {

    public String HttpDownLoad(String urlStr) throws IOException {//返回字符串
        String jsonStr = null;
//      URL url = new URL(urlStr);
//      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        HttpURLConnection connection = (HttpURLConnection) new URL(urlStr).openConnection();
        int responseCode = connection.getResponseCode();
        if (responseCode == 200) {
            InputStream input = connection.getInputStream();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte buff[] = new byte[1024];
            int ret;
            while ((ret = input.read(buff, 0, buff.length)) != -1) {
                bos.write(buff, 0, ret);
                bos.flush();
            }

            jsonStr = new String(bos.toByteArray(), "UTF-8");
        }
        return jsonStr;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值