佛山+网站建设推一手新闻发稿平台
详解:https://www.jianshu.com/p/b87fee2f7a23
--------Android Studio自带org.json解析
解析原理:基于文档驱动
解析流程:把全部文件读入到内存中 ->> 遍历所有数据 ->> 根据需要检索想要的数据
具体使用:
// 创建需解析的JSON数据:student.json
// 将该文件放入到本地assets文件夹里 {"student":[{"id":1,"name":"小明","sex":"男","age":18,"height":175},{"id":2,"name":"小红","sex":"女","age":19,"height":165},{"id":3,"name":"小强","sex":"男","age":20,"height":185}],"cat":"it" }//从assets获取json文件 InputStreamReader isr = new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("assets/" + "student.json"));//字节流转字符流 BufferedReader bfr = new BufferedReader(isr);String line ;StringBuilder stringBuilder = new StringBuilder();while ((line = bfr.readLine())!=null){stringBuilder.append(line);}//将JSON数据转化为字符串 JSONObject root = new JSONObject(stringBuilder.toString());//根据键名获取键值信息 System.out.println("root:"+root.getString("cat"));JSONArray array = root.getJSONArray("student");for (int i = 0;i < array.length();i++){JSONObject stud = array.getJSONObject(i);bfr.close();isr.close();is.close();//依次关闭流 }
----------Gson解析(Google的开源库)--------
https://www.jianshu.com/p/e740196225a4解析原理:基于事件驱动解析流程:根据所需取的数据 建立1个对应于JSON数据的JavaBean类,即可通过简单操作解析出所需数据具体使用****步骤1:创建一个与JSON数据对应的JavaBean类(用作存储需要解析的数据)Gson解析的关键 = 根据JSON数据 写出一个对应的JavaBean,
******2.导入GSON库导入依赖dependencies {compile 'com.google.code.gson:gson:2.3.1' }
*********3.使用GJson解析
*****简单Jason
1. 创建Gson对象Gson gson = newGson(); 2. 创建JavaBean类的对象Student student = newEntityStudent(); 3. 使用Gson解析:将JSON数据转为单个类实体String json = "{\"id\":1,\"name\":\"小明\",\"sex\":\"男\",\"age\":18,\"height\":175}"; student = gson.fromJson(json,Student.class);// 解析:JavaBean对象 = gson.fromJson(son,javaBean类类名.class); 4. 调用student方法展示解析的数据 student.show(); 5. 将Java集合转换为 jsonString json2 = gson.toJson(List);
********复杂jason
// {"translation":["车"], // "basic": // { // "phonetic":"kɑː", // "explains":["n. 汽车;车厢","n. (Car)人名;(土)贾尔;(法、西)卡尔;(塞)察尔"] // }, // "query":"car", // "errorCode":0, // "web":[ // {"value":["汽车","车子","小汽车"],"key":"Car"}, // {"value":["概念车","概念车","概念汽车"],"key":"concept car"}, // {"value":["碰碰车","碰撞用汽车","碰碰汽车"],"key":"bumper car"} // ] // } public String[] translation; //["车"]数组 public basic basic; //basic对象里面嵌套着对象,创建一个basic内部类对象 public static class basic{ //建立内部类,也可以在外部单独建立一个类 public String phonetic;public String[] explains;}public String query;public int errorCode;public List<wb> web; //web是一个对象数组,创建一个web内部类对象 public static class wb{public String[] value;public String key;}
---------Jackson解析----------
- 解析原理:基于事件驱动
嵌套json解析:https://blog.csdn.net/qq_25176763/article/details/68062381
https://github.com/alibaba/fastjson
https://segmentfault.com/a/1190000011212806
https://blog.csdn.net/flysun3344/article/details/54707965
https://www.cnblogs.com/jtlgb/p/6170833.html
https://blog.csdn.net/eddie233/article/details/73730283