Android干货Android开发实战总结知识 | 解析

Android:JSON 简介 & 解析方式 讲解(Gs

2016-03-27  本文已影响17757人  Carson带你学安卓

前言

同样 作为主流的数据交换格式 XML,有兴趣的读者请看文章:XML简介 & 解析方式(DOM、SAX、PULL)


目录

示意图

1. 简介

示意图

2. 语法

// JSON实例
{"skill":{
          "web":[
                 {
                  "name":"html",
                  "year":"5"
                 },
                 {
                  "name":"ht",
                  "year":"4"
                 }],
           "database":[
                  {
                  "name":"h",
                  "year":"2"
                 }]
`}}
示意图

3. 解析方式

3.1 Android Studio自带org.json解析

类似于XMLDOM解析方式

// 创建需解析的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 {

    @Override
    protected 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解析

Google的开源库

步骤1:创建一个与JSON数据对应的JavaBean类(用作存储需要解析的数据)
Gson解析的关键 = 根据JSON数据 写出一个对应的JavaBean,规则是:

示意图

下面用2个例子说明 如何通过JSON文档创建JavaBean

/** 
  * 简单转换
  */ 
        // JSON数据1
        String 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 {

    @Override
    protected 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集合转换为json
        String json2 = gson.toJson(List);        
        System.out.println(json2);
    }
}

3.3 Jackson解析

但Jackson的解析速度、效率都 高于 GSON

步骤1:建立Json数据对应的javaBean(规则同GSON)

// 创建需解析的JSON数据:student.json
// 将该文件放入到本地assets文件夹里
{"student":
          [
           {"id":1,"name":"小明","sex":"男","age":18,"height":175,"date":[2013,8,11]},
           {"id":2,"name":"小红","sex":"女","age":19,"height":165,"date":[2013,8,23]},
           {"id":3,"name":"小强","sex":"男","age":20,"height":185,"date":[2013,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 {
    @Override
    protected 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解析对比


6. 总结


请点赞!因为你的鼓励是我写作的最大动力!

相关文章阅读
Android开发:最全面、最易懂的Android屏幕适配解决方案
Android事件分发机制详解:史上最全面、最易懂
Android开发:史上最全的Android消息推送解决方案
Android开发:最全面、最易懂的Webview详解
Android开发:JSON简介及最全面解析方法!
Android四大组件:Service服务史上最全面解析
Android四大组件:BroadcastReceiver史上最全面解析


欢迎关注Carson_Ho的简书!

不定期分享关于安卓开发的干货,追求短、平、快,但却不缺深度

上一篇 下一篇

猜你喜欢

热点阅读