JSON介绍:

JSON:JavaScript对象表示法
JSON是存储和交换文本信息的语法。
特点:

  1. JSON是轻量级的文本数据交换格式
  2. JSON独立于语言和平台
  3. JSON具有自我描述性,更易理解
    JSON与XML比较:
    类似XML,比XML更小、更快、更易解析
  4. 没有结束标签
  5. 更短
  6. 读写速度更快
  7. 使用数组
  8. 不使用保留字

JSON语法:

  1. 数据在名称/值对中
  2. 数据有逗号分隔
  3. 花括号保存对象
  4. 方括号保存数组

    JSON值可以是:

  5. 数字(整数或浮点数)
  6. 字符串(在双引号中)
  7. 逻辑值(true或false)
  8. 数组(在方括号中)
  9. 对象(在花括号中)
  10. null

JSON对象在花括号中书写,对象可以包含多个键值对:
eg:

{"name":"zhang","sex":"男"}

JSON数组在方括号中书写,数组包含多个对象:
eg:

{"students":[{"name":"zhang","sex":"男"},{"name":"hong","sex":"女"},{"name":"fang","sex":"女"},]
}

JSON第三方解析库介绍

Gson的简介和特点:
Gson是Google提供的用来在Java对象和JSON数据之间进行映射的Java类库。可以将一个JSON字符串转成一个Java对象,或者反过来。
Gson的特点:

  1. 快速、高效
  2. 代码量小、简洁
  3. 面向对象(Gson处理和解析JSON是采用面向对象的方式)
  4. 数据传递和解析方便

Fast-json简介和特点:
Fastjson是一个性能很好的Java语言实现的JSON解析器和生成器,来自阿里巴巴的工程师开发。具有极快的性能,超越任何其他的Java json parser。

Fast-json特点:

  1. 快速FAST(比其他任何基于Java的解析器和生成器更快,包括jackson)
  2. 强大(支持普通JDK类包括任意Java Bean Class、Collection、Map、Date或enum)
  3. 零依赖(没有依赖其他任何类库,除了JDK)
  4. 支持注解、支持全类型序列化

解析JSON数据

1.使用Java自带的方法解析和生成json数据的方法:

要解析的文件内容:

{"languages": [{"id": 1,"ide": "Eclipse","name": "Java"},{"id": 2,"ide": "XCode","name": "Swift"},{"id": 3,"ide": "Visual Studio","name": "C#"}],"cat": "it"
}
package com.example.myjsontest;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);System.out.println("123456789");
//      //解析JSON数据
//      dealJSON();//生成JSON数据createJSON();}/*** 生成JSON数据*/private void createJSON() {JSONObject root = new JSONObject();try {root.put("cat", "it");//              {//                  "id": 1,
//                  "ide": "Eclipse",
//                  "name": "Java"
//              }JSONObject lan1 = new JSONObject();lan1.put("id", 1);lan1.put("ide", "Eclipse");lan1.put("name", "Java");//          {//            "id": 2,
//            "ide": "XCode",
//            "name": "Swift"
//          }JSONObject lan2 = new JSONObject();lan2.put("id", 2);lan2.put("ide", "XCode");lan2.put("name", "Swift");//          {//            "id": 3,
//            "ide": "Visual Studio",
//            "name": "C#"
//          }JSONObject lan3 = new JSONObject();lan3.put("id", 3);lan3.put("ide", "Visual Studio");lan3.put("name", "C#");JSONArray array = new JSONArray();array.put(lan1);array.put(lan2);array.put(lan3);root.put("languages", array);System.out.println(root.toString());} catch (JSONException e) {e.printStackTrace();}}/*** 解析JSON数据*/private void dealJSON() {System.out.println("---------");try {InputStreamReader inputStreamReader = new InputStreamReader(getAssets().open("test.json"), "UTF-8");BufferedReader bufferedReader = new BufferedReader(inputStreamReader);// 将文本中的所有数据都读取到一个StringBuiler中String line;StringBuilder builder = new StringBuilder();while ((line = bufferedReader.readLine()) != null) {builder.append(line);}bufferedReader.close();inputStreamReader.close();JSONObject root = new JSONObject(builder.toString());System.out.println("cat=" + root.getString("cat"));JSONArray jsonArray = root.getJSONArray("languages");for (int i = 0; i < jsonArray.length(); i++) {JSONObject jsonObject = jsonArray.getJSONObject(i);System.out.println("=============================");System.out.println("id=" + jsonObject.getInt("id"));System.out.println("ide=" + jsonObject.getString("ide"));System.out.println("name=" + jsonObject.getString("name"));}} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (JSONException e) {e.printStackTrace();}}
}

解析结果:

生成的json数据tostring()后的结果:

Gson基本用法:

  1. 定义实体类(注意:定义的实体类中属性名要与json返回的键名一致)
  2. 根据需要可以将JSON生成单个实体或列表实体集合

使用Gson解析JsonObject、JsonArray、将实体类转为JSON数据的例子:

GsonTest类:

package com.test.Gson;import java.util.HashMap;
import java.util.Map;import android.app.Activity;
import android.os.Bundle;
import android.util.Log;import com.android.volley.AuthFailureError;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.myjsontest.R;
import com.google.gson.Gson;public class GsonTest extends Activity{@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);RequestPost();}private void RequestPost() {String url = "http://apis.juhe.cn/ip/ip2addr?";final String key = "6f4328d5a40d23cf9974a64976717ede";final String ip = "www.baidu.com";StringRequest stringRequest = new StringRequest(Method.POST, url, new Response.Listener<String>() {@Overridepublic void onResponse(String arg0) {System.out.println(arg0);dealData(arg0);}}, new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError arg0) {System.out.println(arg0.toString());}}){@Overrideprotected Map<String, String> getParams() throws AuthFailureError {Map<String,String> map = new HashMap<String,String>();map.put("ip", ip);map.put("key", key);return map;}};Volley.newRequestQueue(getApplicationContext()).add(stringRequest);}//使用Gson解析JSON数据private void dealData(String result) {Gson gson = new Gson();//fromJson()方法中分别是:要解析的数据,要解析成的类型Info info = gson.fromJson(result, Info.class);Log.i("tag", "location:"+info.getResult().getLocation());}}

Info类:

package com.test.Gson;public class Info {private String resultcode;private String reason;private String error_code;private Tag result;public Tag getResult() {return result;}public void setResult(Tag result) {this.result = result;}public String getResultcode() {return resultcode;}public void setResultcode(String resultcode) {this.resultcode = resultcode;}public String getReason() {return reason;}public void setReason(String reason) {this.reason = reason;}public String getError_code() {return error_code;}public void setError_code(String error_code) {this.error_code = error_code;}}

Tag类:

package com.test.Gson;public class Tag {private String area;private String location;public String getArea() {return area;}public void setArea(String area) {this.area = area;}public String getLocation() {return location;}public void setLocation(String location) {this.location = location;}}

获取到的JSON数据:

{"resultcode": "200","reason": "Return Successd!","result": {"area": "北京市","location": "百度公司电信节点"},"error_code": 0
}

运行结果:

Fast-json的基本用法:

  1. 定义实体类(注意:实体类中的属性名称要与JSON数据中的键名一致)
  2. 根据需要可以将JSON生成单个实体或列表实体集合

    使用Fast-json解析JsonObject、JsonArray、将实体类转为JSON数据的例子:

FastJsonTest类:

package com.test.fastjson;import android.app.Activity;
import android.os.Bundle;
import android.util.Log;import com.alibaba.fastjson.JSON;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.myjsontest.R;public class FastJsonTest extends Activity{@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);RequestPost();}private void RequestPost() {String url = "https://api.douban.com/v2/book/1220562";StringRequest stringRequest = new StringRequest(Method.POST, url, new Response.Listener<String>() {@Overridepublic void onResponse(String arg0) {System.out.println(arg0);dealData(arg0);}}, new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError arg0) {System.out.println(arg0.toString());}});Volley.newRequestQueue(getApplicationContext()).add(stringRequest);}//使用Fast-json库解析JSON数据private void dealData(String result) {//parseObject()方法中参数说明:result 需要解析的JSON字符串、Book.class 要解析成的类型Book book = JSON.parseObject(result, Book.class);Log.i("tag", "书名:"+book.getTitle()+"内容摘要:"+book.getSummary()+"tags的size:"+book.getTags().size());}
}

Book类:

package com.test.fastjson;import java.util.ArrayList;public class Book {private String title;private String publisher;private String summary;private String price;private ArrayList<Tag> tags;public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public String getPublisher() {return publisher;}public void setPublisher(String publisher) {this.publisher = publisher;}public String getSummary() {return summary;}public void setSummary(String summary) {this.summary = summary;}public String getPrice() {return price;}public void setPrice(String price) {this.price = price;}public ArrayList<Tag> getTags() {return tags;}public void setTags(ArrayList<Tag> tags) {this.tags = tags;}}

Tag类:

package com.test.fastjson;public class Tag {private String title;private String name;private String count;public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getCount() {return count;}public void setCount(String count) {this.count = count;}}

获取到的JSON数据:

{"rating": {"max": 10,"numRaters": 343,"average": "7.0","min": 0},"subtitle": "","author": ["[日] 片山恭一"],"pubdate": "2005-1","tags": [{"count": 133,"name": "片山恭一","title": "片山恭一"},{"count": 62,"name": "日本","title": "日本"},{"count": 60,"name": "日本文学","title": "日本文学"},{"count": 38,"name": "小说","title": "小说"},{"count": 32,"name": "满月之夜白鲸现","title": "满月之夜白鲸现"},{"count": 15,"name": "爱情","title": "爱情"},{"count": 8,"name": "純愛","title": "純愛"},{"count": 8,"name": "外国文学","title": "外国文学"}],"origin_title": "","image": "http://img3.douban.com/mpic/s1747553.jpg","binding": "平装","translator": ["豫人"],"catalog": "\n      ","pages": "180","images": {"small": "http://img3.douban.com/spic/s1747553.jpg","large": "http://img3.douban.com/lpic/s1747553.jpg","medium": "http://img3.douban.com/mpic/s1747553.jpg"},"alt": "http://book.douban.com/subject/1220562/","id": "1220562","publisher": "青岛出版社","isbn10": "7543632608","isbn13": "9787543632608","title": "满月之夜白鲸现","url": "http://api.douban.com/v2/book/1220562","alt_title": "","author_intro": "","summary": "那一年,是听莫扎特、钓鲈鱼和家庭破裂的一年。说到家庭破裂,母亲怪自己当初没有找到好男人,父亲则认为当时是被狐狸精迷住了眼,失常的是母亲,但出问题的是父亲……。","price": "15.00元"
}

运行结果截图:

如果想要将Book实体类或者Book实体类集合转换成JSON数据:
只需要在dealData()方法中添加如下代码:

//使用Fast-json库解析JSON数据private void dealData(String result) {//parseObject()方法中参数说明:result 需要解析的JSON字符串、Book.class 要解析成的类型Book book = JSON.parseObject(result, Book.class);Book book1 = new Book();book1.setTitle("book1");//将实体类对象转换成JSON数据JSON.toJSON(book1);Book book2 = new Book();book2.setTitle("book2");Book book3 = new Book();book3.setTitle("book3");List<Book> list = new ArrayList<Book>();list.add(book1);list.add(book2);list.add(book3);//将实体类集合转换为JSON数据JSON.toJSON(list);Log.i("tag", "书名:"+book.getTitle()+"内容摘要:"+book.getSummary()+"tags的size:"+book.getTags().size());}

使用Gson或Fast-json库解析复杂的JSON数据:
FastAndGsonTest类:

package com.test.FastAndGson;import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;import org.json.JSONException;
import org.json.JSONObject;import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;import com.alibaba.fastjson.JSON;
import com.android.volley.AuthFailureError;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.myjsontest.R;public class FastAndGsonTest extends Activity {private ListView listView;private BookListAdapter adapter;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_second);initView();RequestPost();}private void initView() {listView = (ListView) findViewById(R.id.id_listView);}private void RequestPost() {String url = "http://japi.juhe.cn/book/recommend.from?";final String key = "bf5cae62e7854e8969e51660c0adc910";final String cat = "1";final String ranks = "1";StringRequest stringRequest = new StringRequest(Method.POST, url,new Response.Listener<String>() {@Overridepublic void onResponse(String arg0) {System.out.println(arg0);dealData(arg0);}}, new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError arg0) {System.out.println(arg0.toString());}}) {@Overrideprotected Map<String, String> getParams() throws AuthFailureError {Map<String, String> map = new HashMap<String, String>();map.put("key", key);map.put("cat", cat);map.put("ranks", ranks);return map;}};Volley.newRequestQueue(getApplicationContext()).add(stringRequest);}private void dealData(String arg0) {try {//使用Fast-json库解析JSON数据JSONObject resultObject = new JSONObject(arg0);JSONObject dataObject = new JSONObject(resultObject.getString("result"));ArrayList<Book> books = (ArrayList<Book>)JSON.parseArray(dataObject.getString("data"),Book.class);//使用Gson库解析JSON数据
//          Gson gson = new Gson();
//          JSONObject resultObject = new JSONObject(arg0);
//          JSONObject dataObject = new JSONObject(resultObject.getString("result"));
//          Type listType = new TypeToken<ArrayList<Book>>() {//          }.getType();
//          ArrayList<Book> books = gson.fromJson(dataObject.getString("data"),
//                  listType);adapter = new BookListAdapter(FastAndGsonTest.this, books);listView.setAdapter(adapter);} catch (JSONException e) {e.printStackTrace();}}}

BookListAdapter类:

package com.test.FastAndGson;import java.util.ArrayList;import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;import com.example.myjsontest.R;public class BookListAdapter extends BaseAdapter{private Context context;private ArrayList<Book> list;public BookListAdapter(Context context,ArrayList<Book> books){this.context = context;this.list = books;}@Overridepublic int getCount() {return list.size();}@Overridepublic Object getItem(int position) {return list.get(position);}@Overridepublic long getItemId(int position) {return position;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {ViewHolder holder = null;if(holder==null){convertView = View.inflate(context, R.layout.item_list, null);holder = new ViewHolder();holder.textView = (TextView) convertView.findViewById(R.id.id_textView);convertView.setTag(holder);}else{holder = (ViewHolder) convertView.getTag();}Book book = list.get(position);holder.textView.setText(book.getTitle()+"\n"+book.getCode());return convertView;}class ViewHolder{TextView textView;}}

Book类:

package com.test.FastAndGson;public class Book {private String title;private String code;public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public String getCode() {return code;}public void setCode(String code) {this.code = code;}}

获取的JSON数据:

{"error_code": 0,"reason": "Success","result": {"data": [{"title": "美国70年:大而不倒的阴谋政治","code": 39705},{"title": "关情","code": 39706},{"title": "维基大战前传1:阿桑奇和他的黑客战友","code": 39707},{"title": "大逆转:大败局之后的复活密码","code": 39708},{"title": "我是夜场女企划(全本)","code": 39709},{"title": "杜月笙传(上、中、下)","code": 39710},{"title": "你走以后","code": 39711},{"title": "创造贝因美——服务经济时代的公司革命","code": 39712},{"title": "9999滴眼泪","code": 39716},{"title": "新闻人","code": 39717},{"title": "草莽生长:十大首富的创富之道","code": 39718},{"title": "1块变10块的投资分配法","code": 39719},{"title": "阿嬷,我回来了","code": 39720},{"title": "换个方式好好爱","code": 39721},{"title": "权力野兽朱元璋3(大结局)","code": 39722},{"title": "流动中国","code": 39723},{"title": "问你爸去","code": 39724},{"title": "667公里的吻","code": 39725},{"title": "给你一个公司,看你怎么管","code": 39726},{"title": "职场中50个第一次","code": 39727},{"title": "从零开始学K线","code": 39728},{"title": "非常印度","code": 39729},{"title": "远征流在缅北的血","code": 39731},{"title": "这样喝咖啡最健康","code": 39732},{"title": "扑克脸:Lady Gaga传","code": 39733},{"title": "换个姿势爱","code": 39734},{"title": "30年后,你拿什么养活自己2","code": 39735},{"title": "暗权力——黑道启示录","code": 39736},{"title": "重金求子","code": 39738},{"title": "成为作家","code": 39739},{"title": "寻路中国:从乡村到工厂的自驾之旅","code": 39740},{"title": "一个人的旅行","code": 39741},{"title": "女人29岁","code": 39742},{"title": "有爱无爱一身轻","code": 39743},{"title": "嫁人的资本","code": 39744},{"title": "小女人隐私报告2","code": 39745},{"title": "小女人隐私报告1","code": 39746},{"title": "冷血感情信箱","code": 39747},{"title": "为什么男人爱说谎女人爱哭","code": 39748},{"title": "像女人一样行动,像男人一样思考","code": 39749},{"title": "男人来自火星·白金升级版","code": 39750},{"title": "放下","code": 39751},{"title": "爱的锁钥","code": 39752},{"title": "爱情纪","code": 39753},{"title": "婚恋中女人不能犯的100个错误","code": 39754},{"title": "婚恋中男人不能犯的100个错误","code": 39755},{"title": "再婚书","code": 39756},{"title": "幸福太太完全自助宝典","code": 39757},{"title": "婚恋急诊室","code": 39758},{"title": "男人是野生动物 女人是筑巢动物","code": 39759}]}
}

运行结果截图:

Andorid中使用Gson和Fast-json解析库解析JSON数据---第三方库学习笔记(二)相关推荐

  1. Dom4j 解析Xml文档及 XPath查询 学习笔记

    2019独角兽企业重金招聘Python工程师标准>>> 本文查阅方法:     1.查阅目录 -- 查阅本文目录,确定想要查阅的目录标题     2.快捷"查找" ...

  2. css中怎么加入立体模型,CSS学习笔记二:css 画立体图形

    继上一次学了如何去运用css画平面图形,这一次学如何去画正方体,从2D向着3D学习,虽然有点满,但总是一个过程,一点一点积累,然后记录起来. Transfrom3D 在这一次中运用到了一下几种属性: ...

  3. JavaScript高级程序设计学习笔记二(在HTML中使用JavaScript)

    在 HTML 中使用 JavaScript 在html中使用JavaScript脚本有两种方式一种是嵌入在HTML中的脚本,另一种是引入外部的脚本.两种方式都离不开<script>元素. ...

  4. Swift: 在Swift中桥接OC文件(自己创建的类文件、第三方库文件)

    一.介绍 随着Swift的逐渐成熟,使用swift开发或者混合开发已经成为了一个趋势,本身苹果公司也十分推荐使用Swift这门新语言.目前Swift已经更新到了3.0,估计没有多久4.0就要出来了.那 ...

  5. 【theano-windows】学习笔记二——theano中的函数和共享参数

    前言 上一篇博客中学到了theano中的变量类型,也就是dscalar.dvector之类的, 然后还有一个theano.function和eval函数, 将我们所定义的操作转换成theano可执行的 ...

  6. python第三方库文件传输_Python第三方库在Excel文件读写中的应用

    Python第三方库在Excel文件读写中的应用 文/刘卫华1 史婷婷2 许学添1 [摘 要]摘 要 [期刊名称]<电子技术与软件工程> [年(卷),期]2019(000)016 [总页数 ...

  7. python中pyinstaller库的使用(第三方库) 实例8:科赫雪花小包裹

    模块一:turtle库 模块二:time库 模块三:random库 模块四:pyinstaller库(第三方库) 我们希望用可执行文件的方式来执行一段代码 而不是直接用源代码 将.py源代码转换成无需 ...

  8. python 解析html xml_Python中可以用来解析HTML和XML的第三方库是(_____)。

    [判断题]量杯不是衡器. [单选题]86. 目前钻石油井主要是采用( )钻井方法. [单选题]Excel工作表中,把一个含有单元格坐标引用的公式复制到另一个单元格中时,其中所引用的单元格坐标保持不变. ...

  9. python解析雷达数据_【学习笔记】使用python带时间戳提取rosbag中的图像和雷达数据...

    使用sick的TIM561雷达采集数据,topic nam是/scan,摄像头录制图像,topic name是/usb_cam/image_raw.脚本以下:python # coding:utf-8 ...

最新文章

  1. 2018.3.6 11周1次课
  2. ios 百度地图指定区域_iOS开发(第三方使用)——百度地图的简单使用(定位与当前位置的显示)...
  3. C#异步编程(一):异步基础
  4. python静态方法可以被继承吗_python 类的继承 实例方法.静态方法.类方法的代码解析...
  5. 前端埋点的缺点_【埋点学习埋点质量】埋点的框架设计及其准确性
  6. spring核心:bean工厂的装配 2
  7. python aiml_Python AIML搭建聊天机器人实例
  8. linux日志级别的正确使用(printk)
  9. Java图书管理系统(控制台程序)
  10. 如何强制升级索尼sony tablet s android 4.0,【S丶Tablet】教你root Tablet S 4.0.3 R5
  11. Mac上Java环境变量配置_飘云羽逸_新浪博客
  12. mysql实战45讲--- 22 mysql有那些”饮鸩止渴”提高性能的方法?
  13. 8、16、32-BIT系列单片机区别与特点
  14. 控制面板中点击管理工具提示administrative tools 位置不可用的解决办法
  15. linux电子相册,基于Linux电子相册的.doc
  16. 免费edu邮箱申请注冊地址
  17. [TCP灵魂之问]介绍一下 TCP 报文头部的字段
  18. Consul 注册中心介绍
  19. php GD库的使用
  20. 29_多易教育之《yiee数据运营系统》附录:扩展知识点汇总系列二

热门文章

  1. SaaS服务模式下的电商ERP遇到企业仓库分布于多组织下的管理
  2. 【话题】如何看待AI人工智能
  3. JavaScript:利用JavaScript实现的功能、算法和奇淫技巧(持续更新)
  4. 双路由器设置经验:无线路由器接房东的网线,房东给予IP和DNS
  5. 20、JAVA进阶——集合(1)
  6. 希捷ST9500325AS本盘0容量数据恢复
  7. 如何用java打印1-100_在java中使用10个线程打印1到100
  8. lightgbm 特征重要性选择 / 看所有特征哪个重要
  9. 为什么计算机不显示桌面工具栏,快速解决电脑任务栏显示桌面图标不见了几个实用方法...
  10. 架构师的 36 项修炼第02讲:架构核心技术之分布式缓存(上)