Android JSON 数据解析

JSON 全称 (J ava S cript O bject N otation ),中文名 JavaScript 对象表示方法

JSON 是存储和交换文本信息的语法,类似 XML,但比 XML 更流行

因为 JSON 比 XML 更小、更快,更易解析

Java 有很多第三方解析 JSON 的库 : Gson,Fastjson,jackson

不过本节我们并不会去用这些第三方的解析库,而是使用 Android 自带的 JSON 解析器来解析 JSON

Android 提供的 JSON 解析类

Androidorg.json 包下内置了解析 JSON 要用到的类

说明
JSONObject JSON 对象,可以完成 JSON 字符串与 Java 对象的相互转换
JSONArray JSON 数组,可以完成 JSON 字符串与 Java 集合或对象的相互转换
JSONStringer JSON 文本构建类,可以帮助快速和便捷的创建 JSON text,每个 JSONStringer 实体只能对应创建一个 JSON text
JSONTokener JSON 解析类
JSONException JSON 异常

范例

简单的 JSON 字符串

我们写一个范例来解析 2018 年 4 月编程语言排行榜前三名的 JSON 数据

[
    {"name":"Java", "rank":1,"rating":"15.777%"},
    {"name":"C","rank":2,"rating":"13.589%"},
    {"name":"C++","rank":3,"rating":"7.218%"}
]
  1. 创建一个 空的 Android 项目 cn.twle.android.SimpleJSON

  2. app 上点右键,选择 Folder - Assets Folder 创建 assets 目录,并在 assets 目录下新建文件 language.json ,内容如下

    [
        {"name":"Java", "rank":1,"rating":"15.777%"},
        {"name":"C","rank":2,"rating":"13.589%"},
        {"name":"C++","rank":3,"rating":"7.218%"}
    ]
    
  3. 创建一个 LanguageBean.java

    package cn.twle.android.simplejson;
    
    public class LanguageBean {
        private int id;
        private String name;
        private int    rate;
        private String rating;
    
        public LanguageBean(){}
    
        public LanguageBean(int id, String name,
                            int rate, String rating) {
            this.id = id;
            this.name = name;
            this.rate = rate;
            this.rating = rating;
        }
    
        public void setId(int id){
            this.id = id;
        }
        public int getId(){
            return this.id;
        }
        public void setName(String name){
            this.name = name;
        }
        public String getName(){
            return this.name;
        }
        public void setRate(int rate){
            this.rate = rate;
        }
        public int getRate(){
            return this.rate;
        }
    
        public void setRating(String rating){
            this.rating = rating;
        }
        public String getRating(){
            return this.rating;
        }
    
        @Override
        public String toString() {
            return this.name + " 排名:" + this.rate;
        }
    }
    
  4. 然后修改 MainActivity.java 解析 JSON 数据并显示出来

    package cn.twle.android.simplejson;
    
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.widget.Toast;
    
    import org.json.JSONArray;
    import org.json.JSONObject;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.List;
    
    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            StringBuilder sb = new StringBuilder();
    
            // 读取 assets/language.json 内容
            try {
                InputStream is = getResources().getAssets().open("language.json");
                InputStreamReader isr = new InputStreamReader(is,"UTF-8");
                BufferedReader br = new BufferedReader(isr);
                String str = "";
    
                while((str = br.readLine()) != null){
                    sb.append(str);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            List<LanguageBean> languages = new ArrayList<LanguageBean>();
    
            try{
                JSONArray jsonArray = new JSONArray(sb.toString());
                for(int i = 0;i < jsonArray.length();i++){
    
                    JSONObject jsonObject = (JSONObject) jsonArray.get(i);
    
                    LanguageBean languageBean = new LanguageBean();
    
                    languageBean.setId(i);
                    languageBean.setName(jsonObject.getString("name"));
                    languageBean.setRate(jsonObject.getInt("rank"));
                    languageBean.setRating(jsonObject.getString("rating"));
    
                    languages.add(languageBean);
                }
            }catch (Exception e){e.printStackTrace();}
    
            sb = new StringBuilder();
            for ( LanguageBean lang : languages ) {
                sb.append(lang.toString() + "\n");
            }
    
            Toast.makeText(this, sb.toString(),Toast.LENGTH_LONG).show();
        }
    }
    

复杂的 JSON

如果是更为复杂一点的 JSON 数据呢,比如这样的呢?

{"city":[
    {
        "name":"PEK",
        "area":["东城区","西城区","朝阳区","海淀区"],
        "code":[1,2,3,4]
    },
    {
        "name":"Shanghai",
        "area":["黄埔区","徐汇区","长宁区","静安区"],
        "code":[11,12,13,14]
    }
]}
  1. 创建一个 空的 Android 项目 cn.twle.android.ComplexJSON

  2. app 上点右键,选择 Folder - Assets Folder 创建 assets 目录,并在 assets 目录下新建文件 city.json ,内容如下

    {"city":[
        {
            "name":"PEK",
            "area":["东城区","西城区","朝阳区","海淀区"],
            "code":[1,2,3,4]
        },
        {
            "name":"Shanghai",
            "area":["黄埔区","徐汇区","长宁区","静安区"],
            "code":[11,12,13,14]
        }
    ]}
    
  3. 创建一个 CityBean.java

    package cn.twle.android.complexjson;
    
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.widget.Toast;
    
    import org.json.JSONArray;
    import org.json.JSONObject;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.List;
    
    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            StringBuilder sb = new StringBuilder();
    
            // 读取 assets/language.json 内容
            try {
                InputStream is = getResources().getAssets().open("city.json");
                InputStreamReader isr = new InputStreamReader(is, "UTF-8");
                BufferedReader br = new BufferedReader(isr);
                String str = "";
    
                while ((str = br.readLine()) != null) {
                    sb.append(str);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            List<CityBean> cities = new ArrayList<CityBean>();
    
            try {
                JSONObject jsonObject1 = new JSONObject(sb.toString());
    
                JSONArray jsonArray = jsonObject1.getJSONArray("city");
                for (int i = 0; i < jsonArray.length(); i++) {
    
                    JSONObject jsonObject = (JSONObject) jsonArray.get(i);
    
                    CityBean city = new CityBean();
    
                    city.setId(i);
    
                    //取出name
                    city.setName(jsonObject.getString("name"));
    
                    JSONArray ja = jsonObject.getJSONArray("area");
    
                    List<String> list = new ArrayList<String>();
    
                    for (int j = 0; j < ja.length(); j++) {
                        list.add(ja.getString(i));
                    }
    
                    city.setArea(list);
                    list = null;
    
                    List<Integer> codes = new ArrayList<Integer>();
    
                    ja = jsonObject.getJSONArray("code");
                    for (int j = 0; j < ja.length(); j++) {
                        codes.add(ja.getInt(i));
                    }
                    city.setCode(codes);
    
                    cities.add(city);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            sb = new StringBuilder();
            for ( CityBean city: cities) {
                sb.append(city.getName() + ":" + city.getArea().toString()+"\n");
            }
    
            Toast.makeText(this, sb.toString(),Toast.LENGTH_LONG).show();
        }
    
    }
    
  4. 然后修改 MainActivity.java 解析 JSON 数据并显示出来

    package cn.twle.android.complexjson;
    
    import java.util.List;
    
    public class CityBean {
        private int id;
        private String name;
        private List<String> area;
        private List<Integer> code;
    
        public CityBean(){}
    
        public CityBean(int id, String name,
                        List<String> area , List<Integer> code) {
            this.id = id;
            this.name = name;
            this.area = area;
            this.code = code;
        }
    
        public void setId(int id){
            this.id = id;
        }
        public int getId(){
            return this.id;
        }
        public void setName(String name){
            this.name = name;
        }
        public String getName(){
            return this.name;
        }
        public void setArea(List<String> area){
            this.area= area;
        }
        public List<String> getArea(){
            return this.area;
        }
    
        public void setCode(List<Integer> code){
            this.code = code;
        }
        public List<Integer> getCode(){
            return this.code;
        }
    }
    

Android 基础教程

关于   |   FAQ   |   我们的愿景   |   广告投放   |  博客

  简单教程,简单编程 - IT 入门首选站

Copyright © 2013-2022 简单教程 twle.cn All Rights Reserved.