• Android中多种方式解析JSON数据格式


    JSON简介

    json:javascripse对象表示法

    json是储存和交换文本信息的语法

    •     json是轻量级文本数据交换格式
    •    json独立于语言和平台
    •    json具有自我描述性,便于自我理

    json特点:

    • 比xml更小、更快、更容易解析
    •   使用数组
    •   不适用保留字
    •   内容短
    •   读写速度快 

    JSON语法格式

    • 数据在 名称/值(键值对) 对中
    • 数据有逗号分隔
    • 花括号{}保存对象,用Map储存
    • 方括号[]保存数组,可以用数组或List储存
    {
        "resultcode":"200",//红色背景的就是一队键值对
        "reason":"Return Successd!",
        "result":{
            "province":"江西",
            "city":"赣州",
            "areacode":"0797",
            "zip":"341000",
            "company":"移动",
            "card":""
        },
        "error_code":0
    }

    其中对象和数组都可以作为json的值互相穿插

    普通解析JSON数据格式(下面以查询手机号归属地为例)

    json数据内容

    解析json数据内容后在控件中输出效果

      

     1           String province = "";//省份
     2                 String city = "";//城市
     3                 String areacode = "";//区号
     4                 String zip = "";//邮编
     5                 String company = "";//所属公司
     6                 JSONObject jsonObject = new JSONObject(s);//获得第一层对象的内容,s是json数据
     7                 JSONObject jsonObject1 = null;
     8                 jsonObject1 = jsonObject.getJSONObject("result");//获得对象为result中的对象内容
     9 
    10 //                从json数据中获取需要的五个数据:省份,城市,区号,邮编,公司
    11                 province = jsonObject1.getString("province");
    12                 city = jsonObject1.getString("city");
    13                 areacode = jsonObject1.getString("areacode");
    14                 zip = jsonObject1.getString("zip");
    15                 company = jsonObject1.getString("company");

    输出代码这里省去,因为不同的地方使用方法不一样

    使用Gson.jar高效解析json数据格式:

    步骤一:自定义一个类,里面存放需要解析的json数据中的对象名,对象名要和json数据中的相同

    package com.contentprovide.liuliu.fresco_demo;
    
    /**
     * Created by liuliu on 2018/3/15.
     */
    
    public class Book {
    
        String reason;
        String resultcode;
    
        public String getReason() {
            return reason;
        }
    
        public void setReason(String reason) {
            this.reason = reason;
        }
    
        public String getResultcode() {
            return resultcode;
        }
    
        public void setResultcode(String resultcode) {
            this.resultcode = resultcode;
        }
    }

    步骤二:将获取到的json数据通过Gson高效解析:

    package com.contentprovide.liuliu.fresco_demo;
    
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.Toast;
    
    import com.android.volley.Request;
    import com.android.volley.Response;
    import com.android.volley.VolleyError;
    import com.android.volley.toolbox.StringRequest;
    import com.android.volley.toolbox.Volley;
    import com.google.gson.Gson;
    
    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Get_json();
    
        }
    
    
        //    通过Volley获取json数据内容
        public void Get_json() {
    
            String url = "http://v.juhe.cn/weather/index?cityname=%E4%B9%9D%E6%B1%9F&dtype=&format=&key=480532cf40c60e30518afdd9b9ff9a91";
            StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
    //                将获得的json数据放进To_json方法中,方便使用Gson进行解析
                    To_json(s);
                    Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
    
                }
            });
    //        将网络请求添加进消息队列中
            Volley.newRequestQueue(getApplicationContext()).add(stringRequest);
        }
    
    //形参s是获得的json格式的数据内容
        public void To_json(String s) {
            Gson gson = new Gson();
            Book book = gson.fromJson(s, Book.class);
            Log.e("------------------", book.getReason()+book.getResultcode());
        }
    
    
    }

    使用Gson.jar高效解析多层json数据格式:

    json数据格式

    定义一个javabean- Book类,存放三个对象,两个普通对象resultcode和reason,一个键值对象result。其中对象result中是{}内容所以是Map类

    package com.contentprovide.liuliu.fresco_demo;
    
    import java.util.Map;
    
    /**
     * Created by liuliu on 2018/3/15.
     */
    
    public class Book {
    
        String reason;
        String resultcode;
    
        Map result;
    
        public Map getResult() {
            return result;
        }
    
        public void setResult(Map result) {
            this.result = result;
        }
    
        public String getReason() {
            return reason;
        }
    
        public void setReason(String reason) {
            this.reason = reason;
        }
    
        public String getResultcode() {
            return resultcode;
        }
    
        public void setResultcode(String resultcode) {
            this.resultcode = resultcode;
        }
    
    }

    定义一个javabean-result类用于存放sk等多个键值对象,同样sk对象也是Map类

    package com.contentprovide.liuliu.fresco_demo;
    
    import java.util.Map;
    
    /**
     * Created by liuliu on 2018/3/16.
     */
    
    public class result {
    
        Map sk;
    
        public Map getSk() {
            return sk;
        }
    
        public void setSk(Map sk) {
            this.sk = sk;
        }
    
    
    }

    定义一个Javabean-sk类用于存放sk类中的String类对象

    package com.contentprovide.liuliu.fresco_demo;
    
    /**
     * Created by liuliu on 2018/3/16.
     */
    
    public class SK {
    
        String temp;
        String wind_direction;
        String wind_strength;
        String humidity;
        String time;
    
        public String getTemp() {
            return temp;
        }
    
        public void setTemp(String temp) {
            this.temp = temp;
        }
    
        public String getWind_direction() {
            return wind_direction;
        }
    
        public void setWind_direction(String wind_direction) {
            this.wind_direction = wind_direction;
        }
    
        public String getWind_strength() {
            return wind_strength;
        }
    
        public void setWind_strength(String wind_strength) {
            this.wind_strength = wind_strength;
        }
    
        public String getHumidity() {
            return humidity;
        }
    
        public void setHumidity(String humidity) {
            this.humidity = humidity;
        }
    
        public String getTime() {
            return time;
        }
    
        public void setTime(String time) {
            this.time = time;
        }
    }

    在主类中获取json数据,并通过Map获取key得到对应的键值

    package com.contentprovide.liuliu.fresco_demo;
    
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.widget.TextView;
    
    import com.android.volley.Request;
    import com.android.volley.Response;
    import com.android.volley.VolleyError;
    import com.android.volley.toolbox.StringRequest;
    import com.android.volley.toolbox.Volley;
    import com.google.gson.Gson;
    
    import java.util.Map;
    
    public class MainActivity extends AppCompatActivity {
    
        TextView tv;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            tv = (TextView) findViewById(R.id.tv);
    
            Get_json();
    
        }
    
    
        //    通过Volley获取json数据内容
        public void Get_json() {
    
            String url = "http://v.juhe.cn/weather/index?cityname=%E4%B9%9D%E6%B1%9F&dtype=&format=&key=480532cf40c60e30518afdd9b9ff9a91";
            StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
    //                将获得的json数据放进To_json方法中,方便使用Gson进行解析
                    To_json(s);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
    
                }
            });
    //        将网络请求添加进消息队列中
            Volley.newRequestQueue(getApplicationContext()).add(stringRequest);
        }
    
    
        public void To_json(String s) {
    
            Gson gson = new Gson();
    //        把json数据转化为对象
            Book book = gson.fromJson(s, Book.class);
    
    //        取出book类中result对象的集合
            Map map_result = book.getResult();
    
    //        取出result类中sk对象的集合
            Map map_sk = (Map) map_result.get("sk");
    
    //        通过键值对获取对应的键值
            tv.setText("温度:"+map_sk.get("temp")+"风向:"+map_sk.get("wind_direction")
                        +"风力:"+map_sk.get("wind_strength")+"湿度:"+map_sk.get("humidity")
                        +"time:"+map_sk.get("time"));
        }
    
    
    }
  • 相关阅读:
    sicnu 区域赛选拔赛
    LeetCode 7 反转整数
    2018 CCPC网络赛 Dream&&Find Integer
    矩阵快速幂的总结以及模版
    通过event 找到tableview 上的某一个cell
    mac 安装完成phpsorm 运行提示 503解决办法
    指纹验证
    旋转图片
    xcrun: error: active developer path ("/Users/apple/Desktop/Xcode5.app/Contents/Developer") does not exist, use xcode-select to change
    我所了解的block
  • 原文地址:https://www.cnblogs.com/lyd447113735/p/8214411.html
Copyright © 2020-2023  润新知