Android:JSON 简介 & 解析方式 讲解(Gson、AS自带org.json、Jackson)
前言
现今最主流的数据交换格式 非JSON
莫属今天,我将全面介绍JSON
& 解析方式(Gson
、AS
自带org.json
、Jackson
),希望你们会喜欢同样 作为主流的数据交换格式
XML
,有兴趣的读者请看文章:XML简介 & 解析方式(DOM、SAX、PULL)
目录
示意图1. 简介
示意图2. 语法
1个JSON文件里含多个数据,这些数据 以JSON
值 的形式 存在// JSON实例{"skill":{"web":[{"name":"html","year":"5"},{"name":"ht","year":"4"}],"database":[{"name":"h","year":"2"}]`}}
1个JSON
值的内容形式可以是:”名称 - 值“对、数组 或 对象,下面将详细说明示意图
3. 解析方式
Android
解析JSON
数据的方式 类似XML
解析,主要分为2大类:
示意图
下面,我将详细介绍每种方式
3.1 Android Studio自带org.json解析
解析原理:基于文档驱动解析流程:把全部文件读入到内存中 ->> 遍历所有数据 ->> 根据需要检索想要的数据具体使用类似于
XML
的DOM
解析方式
// 创建需解析的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"}// 具体解析import android.os.Bundle;import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);EntityStudent student = new EntityStudent();try {//从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);System.out.println("------------------");System.out.print("id="+stud.getInt("id")+ ","));System.out.print("name="+stud.getString("name")+ ","));System.out.print("sex="+stud.getString("sex")+ ","));System.out.print("age="+stud.getInt("age")+ ","));System.out.println("height="+stud.getInt("height")+ ","));bfr.close();isr.close();is.close();//依次关闭流}} catch (IOException e) {e.printStackTrace();} catch (JSONException e) {e.printStackTrace();}}}
3.2 Gson解析
解析原理:基于事件驱动解析流程:根据所需取的数据 建立1个对应于
JSON
数据的JavaBean
类,即可通过简单操作解析出所需数据具体使用步骤1:创建一个与JSON数据对应的JavaBean类(用作存储需要解析的数据)
Gson
解析的关键 = 根据JSON
数据 写出一个对应的JavaBean
,规则是:
示意图
下面用2个例子说明 如何通过JSON
文档创建JavaBean
类
/** * 简单转换*/ // JSON数据1String json = "{\"id\":1,\"name\":\"小明\",\"sex\":\"男\",\"age\":18,\"height\":175}";// 对应的JavaBean类public class EntityStudent {private int id;private String name;private String sex;private int age;private int height;public void setId(int id){this.id = id;}public void setName(String name){this.name = name;}public void setSex(String sex){this.sex = sex;}public void setAge(int age){this.age = age;}public void setHeight(int height){this.height = height;}public int getId(){return id;}public String getName(){return name;}public String getSex(){return sex;}public int getAge(){return age;}public int getHeight(){return height;}public void show(){System.out.print("id=" + id + ",");System.out.print("name=" + name+",");System.out.print("sex=" + sex+",");System.out.print("age=" + age+",");System.out.println("height=" + height + ",");}}/** * 复杂转换*/ // JSON数据2(具备嵌套){"translation":["车"],"basic":{"phonetic":"kɑː","explains":["n. 汽车;车厢","n. (Car)人名;(土)贾尔;(法、西)卡尔;(塞)察尔"]},"query":"car","errorCode":0,"web":[{"value":["汽车","车子","小汽车"],"key":"Car"},{"value":["概念车","概念车","概念汽车"],"key":"concept car"},{"value":["碰碰车","碰撞用汽车","碰碰汽车"],"key":"bumper car"}]}// 对应的复杂的JSON数据对应的JavaBean类public class student {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;}public void show(){//输出数组for (int i = 0;i<translation.length;i++){System.out.println(translation[i]);}//输出内部类对象System.out.println(basic.phonetic);//输出内部类数组for (int i = 0;i<basic.explains.length;i++){System.out.println(basic.explains[i]);}System.out.println(query);System.out.println(errorCode);for (int i = 0;i<web.size();i++){for(int j = 0; j<web.get(i).value.length;j++){System.out.println(web.get(i).value[j]);}System.out.println(web.get(i).key);}}}
若觉得转换过于复杂,请直接使用工具:JSON字符串 转 Java实体类
步骤2:导入GSON库
在Android Gradle
导入依赖
dependencies {compile 'com.google.code.gson:gson:2.3.1'}
步骤3:使用Gson进行解析
public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);// 1. 创建Gson对象Gson gson = new Gson();// 2. 创建JavaBean类的对象Student student = new EntityStudent();// 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); System.out.println(json2);}}
3.3 Jackson解析
解析原理:基于事件驱动解析过程:类似GSON
,先创建1个对应于JSON
数据的JavaBean
类,再通过简单操作即可解析与Gson
解析不同的是:GSON
可按需解析,即创建的JavaBean
类不一定完全涵盖所要解析的JSON
数据,按需创建属性;但Jackson
解析对应的JavaBean
必须把Json
数据里面的所有key
都有所对应,即必须把JSON
内的数据所有解析出来,无法按需解析具体使用但Jackson的解析速度、效率都 高于 GSON
步骤1:建立Json
数据对应的javaBean(规则同GSON)
// 创建需解析的JSON数据:student.json// 将该文件放入到本地assets文件夹里{"student":[{"id":1,"name":"小明","sex":"男","age":18,"height":175,"date":[,8,11]},{"id":2,"name":"小红","sex":"女","age":19,"height":165,"date":[,8,23]},{"id":3,"name":"小强","sex":"男","age":20,"height":185,"date":[,9,1]}],"grade":"2"}// JavaBean类class test {private List<stu> student = new ArrayList<stu>();private int grade;public void setStudent(List<stu> student){this.student = student;}public List<stu> getStudent(){return student;}public void setGrade(int grade){this.grade = grade;}public int getGrade(){return grade;}private static class stu {private int id;private String name;private String sex;private int age;private int height;private int[] date;public void setId(int id){this.id = id;}public int getId(){return id;}public void setName(String name){this.name = name;}public String getName(){return name;}public void setSex(String sex){this.sex = sex;}public String getSex(){return sex;}public void setAge(int age){this.age = age;}public int getAge(){return age;}public void setHeight(int height){this.height = height;}public int getHeight(){return height;}public void setDate(int[] date){this.date = date;}public int[] getDate(){return date;}}public String tostring(){String str = "";for (int i = 0;i<student.size();i++){str += student.get(i).getId() + " " + student.get(i).getName() + " " + student.get(i).getSex() + " " + student.get(i).getAge() + " " + student.get(i).getHeight() ;for (int j = 0;j<student.get(i).getDate().length;j++) {str += student.get(i).getDate()[j]+ " " ;}str += "\n";}str += "\n"+getGrade();return str;}}
步骤2:利用Jackson方法进行解析
public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);ObjectMapper objectMapper = new ObjectMapper();try {// 1. //从assets获取json文件InputStreamReader isr = new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("assets/" + "student.json"),"utf-8");BufferedReader bfr = new BufferedReader(isr);String line;StringBuilder stringBuilder = new StringBuilder();while ((line = bfr.readLine())!=null){stringBuilder.append(line);}// 2. 将JSON数据转化为字符串System.out.println(stringBuilder.toString());System.out.println(tes.tostring());} catch (IOException e) {e.printStackTrace();}}}
4. 解析方式对比
示意图5. 与XML解析对比
对于 同样作为主流的数据交换格式XML
来说,二者对比如下:示意图总的来说,相比于XML
,JSON
大小更小、解析方法更简单、解析速度更快。所以,JSON
一定是你在数据交换格式选型中的首选
6. 总结
本文全面介绍了现今主流的数据传输格式:JSON