Android-Gson+GsonFormat的导入
Android-json解析(一):Gson的使用
Android-json解析(二):Jackson的使用
Android-json解析(三):原生JSONObject+JSONArray的使用
Android-json解析(四):fastjson的使用
Android -序列化 : Serializable / Parcelable
一、JSONObject和JSONArray的数据表示形式
JSONObject的数据是用 { } 来表示的,
例如:
{
"id":"1",
"courseID":"化学",
"title":"滴定实验",
"content":"下周二实验楼201必须完成"
}
而JSONArray,顾名思义是由JSONObject构成的数组,用 [ { } , { } , … , { } ] 来表示
例如:
[
{
"id":"1",
"courseID":"数学",
"title":"一加一等于几"
},
{
"id":"2",
"courseID":"语文",
"title":"请背诵全文"
}
]
表示了包含2个JSONObject的JSONArray。
可以看到一个很明显的区别,一个最外面用的是 { } ,一个最外面用的是 [ ] ;
二、如何从字符串jsonString获得JSONObject对象和JSONArray对象
/*json字符串最外层是大括号时:*/
JSONObject jsonObject = new JSONObject(jsonStr);
/*json字符串最外层是方括号时:*/
JSONArray jsonArray = new JSONArray(jsonStr);
三、如何从JSONArray中获得JSONObject对象
遇到方括号时,就要先获取JSONArray,然后再循环遍历出JSONObject
大家可以把JSONArray当成一般的数组来对待,只是获取的数据内数据的方法不一样。
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
}
注意:
/*JSONObject 获取jsonArray :需要数组的字段名*/
JSONArray jsonArray = jsonObject.getJSONArray("children");
/*jsonArray获取JSONObject : 需要遍历数组*/
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
}
四、通过JsonObject获取JSON内的具体数据:
int mid= jsonObject.getInt("id");
String mcourse=jsonObject.getString("courseID");
示例一:
{
"msg": "",
"code": "succeed",
"login_status": 0,
"mall_uid": "epet_0",
"mall_user": "",
"sys_time": 1494388655,
"push_alias": "",
"push_tags": "version3",
"categorys": [
{
"cateid": 53,
"name": "狗狗玩具",
"children": [
{
"type": "cateid",
"id": "210",
"name": "棉制玩具",
"photo": "http://i.epetbar.com/nowater/cates/2014-03/24/fcab37ead00d77bcdddf7dabe6c817d7.jpg"
},
{
"type": "cateid",
"id": "211",
"name": "橡胶玩具",
"photo": "http://i.epetbar.com/nowater/2016-07/21/14/874299e54a8cf1488d6b1bead8f8e9bb.jpg"
},
{
"type": "cateid",
"id": "212",
"name": "塑料玩具",
"photo": "http://i.epetbar.com/nowater/cates/2014-03/24/df1ed7120376370a4b5badaae61a0a7e.jpg"
},
{
"type": "cateid",
"id": "213",
"name": "手工玩具",
"photo": "http://i.epetbar.com/nowater/cates/2014-03/24/6709410560b999ab37ffb9747bb2ee71.jpg"
},
{
"type": "cateid",
"id": "3088",
"name": "食用玩具",
"photo": "http://i.epetbar.com/nowater/cates/2014-03/24/a5c7619872749790f6d6fd1ff3eccedc.jpg"
},
{
"type": "cateid",
"id": "4157",
"name": "木质玩具",
"photo": "http://i.epetbar.com/nowater/cates/2014-03/24/e9145de044fd5cec4c9b8ed47360d98f.jpg"
},
{
"type": "cateid",
"id": "4188",
"name": "梵米派",
"photo": "http://i.epetbar.com/nowater/cates/2015-07/28/45c339f6acb56364132b92f04b090c5c.jpg"
}
]
}
],
"topadv": {
"advid": "20605",
"src": "https://img2.epetbar.com/nowater/2017-04/05/14/19427a29344bcc0f385ca4718adca02f.jpg",
"title": "红脚丫",
"param": {
"mode": "web",
"param": "http://sale.epet.com/m/mould/activity/ztMTAzOA%3D%3D.html?tid=1038"
}
},
"owner": 53
}
解析如下:
注意:MyData类可以借助GsonFormat类生成实体类。
private List<MyData.CategorysBean.ChildrenBean> parseJSONOrgin(String string) {
List<MyData.CategorysBean.ChildrenBean> childrenBeanList = new ArrayList<MyData.CategorysBean.ChildrenBean>();
try {
JSONObject jsonObject = new JSONObject(string);
JSONArray jsonArray = jsonObject.getJSONArray("categorys");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
JSONArray children = jsonObject1.getJSONArray("children");
for (int j = 0; j < children.length(); j++) {
JSONObject jsonObject2 = children.getJSONObject(j);
MyData.CategorysBean.ChildrenBean childrenBean = new MyData.CategorysBean.ChildrenBean();
childrenBean.setName(jsonObject2.getString("name"));
childrenBean.setId(jsonObject2.getString("id"));
childrenBean.setPhoto(jsonObject2.getString("photo"));
childrenBean.setType(jsonObject2.getString("type"));
childrenBeanList.add(childrenBean);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return childrenBeanList;
}
示例二:
[
{
"id": 582490,
"name": "单车自驾:魔幻张家界",
"photos_count": 128,
"start_date": "2016-04-05",
"end_date": "2016-04-08",
"days": 4,
"level": 4,
"views_count": 55199,
"comments_count": 34,
"likes_count": 441,
"source": "web",
"front_cover_photo_url": "http://p.chanyouji.cn/582490/1468260328216p1andi510ihgkc2f5hk6rf198.jpg",
"featured": false,
"user": {
"id": 313643,
"name": "huchichi",
"image": "http://tva2.sinaimg.cn/crop.0.12.282.282.50/5c5ee839gw1ec7kq4pasrj207v08d3zv.jpg"
}
},
{
"id": 666746,
"name": "【斯里兰卡10天】跨过山和大海",
"photos_count": 122,
"start_date": "2016-12-24",
"end_date": "2017-01-02",
"days": 10,
"level": 3,
"views_count": 33023,
"comments_count": 32,
"likes_count": 471,
"source": "app",
"front_cover_photo_url": "http://p.chanyouji.cn/666746/1485787660939p1b7ntf07u16kdssn1tfl1ck1q1qd.jpg",
"featured": false,
"user": {
"id": 469471,
"name": "宇_RainyK",
"image": "http://a.chanyouji.cn/469471/1460020629.jpg"
}
},
{
"id": 665223,
"name": "上帝自留地探访 : 新西兰——快乐咔嚓声",
"photos_count": 250,
"start_date": "2016-11-30",
"end_date": "2016-12-04",
"days": 5,
"level": 3,
"views_count": 23981,
"comments_count": 30,
"likes_count": 533,
"source": "app",
"front_cover_photo_url": "http://p.chanyouji.cn/1483013211/40p8jhlx7t4e8hntyhp4z31c0.jpg",
"serial_id": 664971,
"serial_position": 1,
"featured": false,
"user": {
"id": 131541,
"name": "片儿川",
"image": "http://a.chanyouji.cn/131541/1483887153821.jpg"
}
},
{
"id": 591454,
"name": "土耳其...我喜欢你,像风走了八千里",
"photos_count": 195,
"start_date": "2016-08-08",
"end_date": "2016-08-22",
"days": 15,
"level": 3,
"views_count": 18822,
"comments_count": 42,
"likes_count": 854,
"source": "web",
"front_cover_photo_url": "http://p.chanyouji.cn/1472368913/9896F012-522E-46C4-9F29-5F6D86C790DB.jpg",
"featured": false,
"user": {
"id": 208609,
"name": "晶晶姑姑娘娘",
"image": "http://a.chanyouji.cn/208609/1493099858.jpg"
}
},
{
"id": 589708,
"name": "浪迹非洲最南——“慢得啦”国闲游之一",
"photos_count": 128,
"start_date": "2016-07-23",
"end_date": "2016-07-24",
"days": 2,
"level": 3,
"views_count": 5858,
"comments_count": 4,
"likes_count": 65,
"source": "web",
"front_cover_photo_url": "http://p.chanyouji.cn/589708/1471963416200p1aqrtl1pq8js1ek0sn913uq1kdmh.jpg",
"serial_id": 589708,
"serial_position": 0,
"featured": false,
"user": {
"id": 103122,
"name": "牵着蜗牛散步的JOY",
"image": "http://tva1.sinaimg.cn/crop.0.17.640.640.50/794bd26ajw8e7tg9nfqb5j20hs0iqmxg.jpg"
}
},
{
"id": 598966,
"name": "霓虹国/留学生 梦游记录",
"photos_count": 88,
"start_date": "2016-08-28",
"end_date": "2017-05-07",
"days": 253,
"level": 3,
"views_count": 16648,
"comments_count": 10,
"likes_count": 72,
"source": "app",
"front_cover_photo_url": "http://p.chanyouji.cn/1476365877/C9B59738-58E8-47C9-BCD1-5F2AC5CC9526.jpg",
"featured": false,
"user": {
"id": 694154,
"name": "Y-dec",
"image": "http://q.qlogo.cn/qqapp/100277927/5475C47B95A36891E2698462184F8785/100"
}
},
{
"id": 544528,
"name": "【我的年假】7 重庆—吃一顿地道火锅",
"photos_count": 385,
"start_date": "2016-08-31",
"end_date": "2016-09-03",
"days": 4,
"level": 3,
"views_count": 37214,
"comments_count": 55,
"likes_count": 530,
"source": "app",
"front_cover_photo_url": "http://p.chanyouji.cn/544528/1474011393910p1asoupfpujrj1rnd5o813qo1jvi5.jpg",
"serial_id": 544528,
"serial_position": 0,
"featured": false,
"user": {
"id": 17010,
"name": "马兰头头2010",
"image": "http://a.chanyouji.cn/17010/1426768814.jpg"
}
},
{
"id": 665311,
"name": "就该这么玩【北海道】",
"photos_count": 118,
"start_date": "2016-12-05",
"end_date": "2016-12-12",
"days": 8,
"level": 3,
"views_count": 24644,
"comments_count": 6,
"likes_count": 108,
"source": "app",
"front_cover_photo_url": "http://p.chanyouji.cn/1484295471/E2B2C32A-C910-490F-9F13-BC9D3B118C1B.jpg",
"featured": false,
"user": {
"id": 544219,
"name": "炘仔~",
"image": "http://a.chanyouji.cn/544219/1489641072.jpg"
}
},
{
"id": 668998,
"name": "漫步成都一一我的寻(熊)猫之旅",
"photos_count": 108,
"start_date": "2017-02-06",
"end_date": "2017-02-12",
"days": 7,
"level": 3,
"views_count": 15222,
"comments_count": 30,
"likes_count": 146,
"source": "app",
"front_cover_photo_url": "http://p.chanyouji.cn/1487129075/720F81CB-EE64-4681-8564-A9A6864AAD33.jpg",
"featured": false,
"user": {
"id": 261578,
"name": "小柠12345",
"image": "http://tva1.sinaimg.cn/crop.27.0.238.238.50/bb9ff9e8gw1eggbljiopfj208w06oaam.jpg"
}
},
{
"id": 297060,
"name": "「吃遍日本」大阪·神户·名古屋",
"photos_count": 125,
"start_date": "2015-04-25",
"end_date": "2015-05-02",
"days": 8,
"level": 4,
"views_count": 56384,
"comments_count": 121,
"likes_count": 948,
"source": "web",
"front_cover_photo_url": "http://p.chanyouji.cn/297060/1440912374444p19tuh3ukup7t1l5c1j0u8r6kfs2.jpg",
"featured": false,
"user": {
"id": 312316,
"name": "CaitlinGao",
"image": "http://tva3.sinaimg.cn/crop.0.0.640.640.50/96246e0bjw8ensjycmsdmj20hs0hsjs7.jpg"
}
}
]
解析如下:
注意:最外层是个方括号。
private List<News> parseJSONOrgin(String json) {
List<News> list = new ArrayList<News>();
try {
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
News news = new News();
news.setSource(jsonObject.getString("source"));
news.setFront_cover_photo_url(jsonObject.getString("front_cover_photo_url"));
news.setName(jsonObject.getString("name"));
news.setStart_date(jsonObject.getString("start_date"));
list.add(news);
}
} catch (JSONException e) {
e.printStackTrace();
}
return list;
}
JSONObject获取Float Double类型数据的准确性:
示例:
{
"status":0,
"result":[
{
"x":114.2307489832,
"y":29.579081808346
}
]
}
解析如下:
String jsonStr = "{\"status\":0,\"result\":[{\"x\":114.2307489832,\"y\":29.579081808346}]}";
try {
JSONObject jsonObject = new JSONObject(jsonStr);
if (jsonObject.has("result")) {
JSONArray jsonArray = jsonObject.getJSONArray("result");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjectResult = jsonArray.getJSONObject(i);
if (jsonObjectResult.has("x")) {
//方法一:
String x = jsonObjectResult.getString("x");
System.out.println("x============" + x);//114.2307489832
Double aDouble = Double.valueOf(x);
System.out.println("aDouble=======" + aDouble);//114.2307489832
//方法二:
String x1 = jsonObjectResult.get("x").toString();
System.out.println("x1============" + x1);//114.2307489832
Double aDouble1 = Double.valueOf(x1);
System.out.println("aDouble1=======" + aDouble1);//114.2307489832
//方法三
double x2 = jsonObjectResult.getDouble("x");
System.out.println("x2============" + x2);//114.2307489832
//获取失败
long x3 = jsonObjectResult.getLong("x");
System.out.println("x3============" + x3);//114
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
判断字符串是JSONObject还是JSONArray
使用 JSONTokener。JSONTokener.nextValue() 会给出一个对象,然后可以动态的转换为适当的类型。
示例一:
有时候这样:
{
"id":"1",
"courseID":"化学",
"title":"滴定实验",
"content":"下周二实验楼201必须完成"
}
有时候又这样:
[
{
"id":"1",
"courseID":"数学",
"title":"一加一等于几"
},
{
"id":"2",
"courseID":"语文",
"title":"请背诵全文"
}
]
解析如下:
//String jsonStr = "{\"id\":\"1\",\"courseID\":\"化学\",\"title\":\"滴定实验\",\"content\":\"下周二实验楼201必须完成\"}";
String jsonStr = "[{\"id\":\"1\",\"courseID\":\"数学\",\"title\":\"一加一等于几\"},{\"id\":\"2\",\"courseID\":\"语文\",\"title\":\"请背诵全文\"}]";
try {
Object object = new JSONTokener(jsonStr).nextValue();
if (object instanceof JSONObject) {
System.out.println("==我是JSONObject==");
JSONObject jsonObject = (JSONObject) object;
if (jsonObject.has("title")) {
String title = jsonObject.getString("title");
if (!TextUtils.isEmpty(title)) {
System.out.println("title==" + title);
}
}
} else if (object instanceof JSONArray) {
System.out.println("==我是JSONArray==");
JSONArray jsonArray = (JSONArray) object;
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
if (jsonObject.has("title")) {
String title = jsonObject.getString("title");
if (!TextUtils.isEmpty(title)) {
System.out.println("title==" + title);
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
示例二:
有时候这样:
{
"cource":{
"id":"1",
"courseID":"数学",
"title":"一加一等于几"
}
}
有时候又这样:
{
"cource":[
{
"id":"1",
"courseID":"数学",
"title":"一加一等于几"
},
{
"id":"2",
"courseID":"语文",
"title":"请背诵全文"
}
]
}
解析如下:
String jsonStr="{\"cource\":[{\"id\":\"1\",\"courseID\":\"数学\",\"title\":\"一加一等于几\"},{\"id\":\"2\",\"courseID\":\"语文\",\"title\":\"请背诵全文\"}]}";
//String jsonStr = "{\"cource\":{\"id\":\"1\",\"courseID\":\"数学\",\"title\":\"一加一等于几\"}}";
try {
JSONObject jsonObject = new JSONObject(jsonStr);
if (jsonObject.has("cource")) {
String cource = jsonObject.getString("cource");
Object object = new JSONTokener(cource).nextValue();
if (object instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) object;
for (int k = 0; k < jsonArray.length(); k++) {
JSONObject parameterObject = jsonArray.getJSONObject(k);
System.out.println("==我是JSONArray==" + parameterObject);
}
} else if (object instanceof JSONObject) {
JSONObject jsonObject1 = (JSONObject) object;
System.out.println("==我是JSONObject==" + jsonObject1);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
opt与get的区别:
get()取值不正确会抛出异常,必须用try catch或者throw包起
而opt()取值不正确则会试图进行转化或者输出友好值,不会抛出异常
json中的opt和get方法
get()和opt()
getBoolean()和optBoolean();
getDouble()和optDouble();
getInt()和optInt();
getLong()和optLong();
getString()和optString();
getJSONObject和optJSONobject();
getJSONArray和optJSONArray();
getJSONArray和optJSONArray()源码对比:
/** * Returns the value mapped by {@code name} if it exists and is a {@code * JSONArray}, or throws otherwise. * * @throws JSONException if the mapping doesn't exist or is not a {@code * JSONArray}. 不存在或不是jsonArray抛出异常 */
public JSONArray getJSONArray(String name) throws JSONException {
Object object = get(name);
if (object instanceof JSONArray) {
return (JSONArray) object;
} else {
throw JSON.typeMismatch(name, object, "JSONArray");
}
}
/** * Returns the value mapped by {@code name} if it exists and is a {@code * JSONArray}, or null otherwise. 不存在或不是jsonArray返回null */
public JSONArray optJSONArray(String name) {
Object object = opt(name);
return object instanceof JSONArray ? (JSONArray) object : null;
}
getString 可以看出 返回的任何数据类型都会被转换为String
public String getString(String name) throws JSONException {
Object object = get(name);
String result = JSON.toString(object);
if (result == null) {
throw JSON.typeMismatch(name, object, "String");
}
return result;
}
json的创建:
通过put方法来设置json的创建。
try {
createJson();
} catch (JSONException e) {
e.printStackTrace();
}
private String createJson() throws JSONException {
JSONObject jsonObject = new JSONObject();
jsonObject.put("intKey", 123);
jsonObject.put("doubleKey", 10.1);
jsonObject.put("longKey", 666666666);
jsonObject.put("stringKey", "lalala");
jsonObject.put("booleanKey", true);
JSONArray jsonArray = new JSONArray();
jsonArray.put(0, 111);
jsonArray.put("second");
jsonObject.put("arrayKey", jsonArray);
JSONObject innerJsonObject = new JSONObject();
innerJsonObject.put("innerStr", "inner");
jsonObject.put("innerObjectKey", innerJsonObject);
System.out.println("创建的json=======" + jsonObject.toString());
return jsonObject.toString();
}
打印结果:
{
"intKey":123,
"doubleKey":10.1,
"longKey":666666666,
"stringKey":"lalala",
"booleanKey":true,
"arrayKey":[
111,
"second"
],
"innerObjectKey":{
"innerStr":"inner"
}
}
遍历key和value:
示例一:jsonobject
{
"id":"1",
"courseID":"化学",
"title":"滴定实验",
"content":"下周二实验楼201必须完成"
}
String jsonStr = "{\"id\":\"1\",\"courseID\":\"化学\",\"title\":\"滴定实验\",\"content\":\"下周二实验楼201必须完成\"}";
try {
JSONObject jsonObject = new JSONObject(jsonStr);
Iterator iterator = jsonObject.keys();
while (iterator.hasNext()) {
String key = (String) iterator.next();
String value = jsonObject.getString(key);
System.out.println(key + "===" + value);
}
} catch (JSONException e) {
e.printStackTrace();
}
示例二:jsonarray
[
{
"id":"1",
"courseID":"数学",
"title":"一加一等于几"
},
{
"id":"2",
"courseID":"语文",
"title":"请背诵全文"
}
]
String jsonStr = "[{\"id\":\"1\",\"courseID\":\"数学\",\"title\":\"一加一等于几\"},{\"id\":\"2\",\"courseID\":\"语文\",\"title\":\"请背诵全文\"}]";
try {
JSONArray jsonArray = new JSONArray(jsonStr);
if (jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Iterator iterator = jsonObject.keys();
while (iterator.hasNext()) {
String key = (String) iterator.next();
String value = jsonObject.getString(key);
System.out.println(key + "===" + value);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
今天的文章Android-json解析(三):原生JSONObject+JSONArray的解析、遍历及生成等分享到此就结束了,感谢您的阅读。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/5254.html