Android中的Json解析,Gson和FastJson

JSON数据

String url = “http://api.m.mtime.cn/PageSubArea/TrailerList.api”;
GitHub测试Url: https://api.github.com/users/basil2style
这里面有很多json数据:https://gank.io/api

在线解析:https://www.json.cn/

JSONObject.toJSONString(list),

这个可以生产json字符串

GsonFormat

主要用于使用Gson库将JSONObject格式的String 解析成实体,该插件可以加快开发进度,使用非常方便,效率高。

插件地址:
https://plugins.jetbrains.com/plugin/7654-gsonformat
介绍
https://www.cnblogs.com/1024zy/p/6370305.html

Gson的简单使用

https://github.com/google/gson

//Gson
implementation 'com.google.code.gson:gson:2.8.5'
// 使用new方法
Gson gson = new Gson();

// toJson 将bean对象转换为json字符串
String jsonStr = gson.toJson(user, User.class);

// fromJson 将json字符串转为bean对象
Student user= gson.fromJson(jsonStr, User.class);

// **序列化List**
String jsonStr2 = gson.toJson(list);

// **反序列化成List时需要使用到TypeToken getType()**
List<User> retList = gson.fromJson(jsonStr2,new TypeToken<List<User>>(){}.getType());

FastJson的简单使用

https://github.com/alibaba/fastjson

//fastjson
implementation 'com.alibaba:fastjson:1.2.44'
[
        {
            "coverImg": "http://img5.mtime.cn/mg/2018/07/22/100134.53759038_120X90X4.jpg",
            "hightUrl": "http://vfx.mtime.cn/Video/2018/07/22/mp4/180722100205713536.mp4",
            "id": 71318,
            "movieId": 213190,
            "movieName": "《哥斯拉:怪兽之王》中字预告",
            "rating": -1,
            "summary": "大怪兽集结!小11成焦点人物",
            "type": [
                "动作",
                "冒险",
                "科幻"
            ],
            "url": "http://vfx.mtime.cn/Video/2018/07/22/mp4/180722100205713536.mp4",
            "videoLength": 146,
            "videoTitle": "哥斯拉:怪兽之王 中字预告1"
        },
        {
            "coverImg": "http://img5.mtime.cn/mg/2018/07/22/041641.10540075_120X90X4.jpg",
            "hightUrl": "http://vfx.mtime.cn/Video/2018/07/22/mp4/180722041607197988.mp4",
            "id": 71311,
            "movieId": 87876,
            "movieName": "《雷霆沙赞》SDCC预告片",
            "rating": -1,
            "summary": "沙雕英雄身体里住了个孩子",
            "type": [
                "动作",
                "奇幻",
                "科幻"
            ],
            "url": "http://vfx.mtime.cn/Video/2018/07/22/mp4/180722041607197988.mp4",
            "videoLength": 173,
            "videoTitle": "雷霆沙赞 SDCC预告片"
        }]

1.Movie.java 对上面JSON数组中的一项进行GsonFormat
2.Json数组使用List movies = JSON.parseArray(json, Movie.class);
3. List list = JSON.parseArray(jsonString);//如果是一个普通的List,里面没有Bean对象,则也可以这样解析。
4.json对象的话,DataInfo dataInfo = JSON.parseObject(json, DataInfo.class);

猜你喜欢

转载自blog.csdn.net/yu540135101/article/details/84405302