【Android基础】JSON数据解析

一、常用的Json解析类

1、JSONObject

Json对象
有两个不同的取值方法:

  • get×××(String name)
    在确定数值存在的条件下使用,否则当无法检索到相关Key时,将会抛出一个Exception信息。
  • opt×××(String name)
    这个方法相对比较灵活,当无法获取所指定数值时,将会返回一个默认数值,并不会抛出异常。

2、JSONArray

Json数组

二、案例

1、源码

下载Json资源

public class MyAsync extends AsyncTask<String, Void, String> {
    private Handler handler;

    public MyAsync(Handler handler) {
        this.handler = handler;
    }

    @Override
    protected String doInBackground(String... strings) {
        try {
            URL url = new URL(strings[0]);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("GET");

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                //拿到输入流
                InputStream is = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                StringBuilder result = new StringBuilder();
                char[] buffer = new char[512];
                int bufsize;
                while ((bufsize = reader.read(buffer)) > 0) {
                    result.append(buffer, 0, bufsize);
                }
                return result.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        Message message = Message.obtain();
        message.obj = s;
        handler.sendMessage(message);

    }
}
public class MainActivity extends AppCompatActivity {
    String url = "https://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&page=1&limit=5";
    String result = null;

    private TextView resultTextView;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            result = (String) msg.obj;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        MyAsync myAsync = new MyAsync(handler);
        myAsync.execute(url);

        resultTextView = findViewById(R.id.result_text);
    }
}

下载成功的json数据使用JSON数据格式化验证结果如下

{
    "ret":1,
    "data":[
        {
            "id":"8289",
            "title":"油焖大虾",
            "pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/9/8289.jpg",
            "collect_num":"1670",
            "food_str":"大虾 葱 生姜 植物油 料酒",
            "num":1670
        },
        {
            "id":"2127",
            "title":"四川回锅肉",
            "pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/3/2127.jpg",
            "collect_num":"1591",
            "food_str":"猪肉 青蒜 青椒 红椒 姜片",
            "num":1591
        },
        {
            "id":"30630",
            "title":"超简单芒果布丁",
            "pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/31/30630.jpg",
            "collect_num":"1549",
            "food_str":"QQ糖 牛奶 芒果",
            "num":1549
        },
        {
            "id":"9073",
            "title":"家常红烧鱼",
            "pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/10/9073.jpg",
            "collect_num":"1426",
            "food_str":"鲜鱼 姜 葱 蒜 花椒",
            "num":1426
        },
        {
            "id":"10097",
            "title":"家常煎豆腐",
            "pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/11/10097.jpg",
            "collect_num":"1419",
            "food_str":"豆腐 新鲜红椒 青椒 葱花 油",
            "num":1419
        }
    ]
}

解析

    private String parseJson(String json) {
        StringBuffer sb = new StringBuffer();
        try {
            JSONObject object = new JSONObject(json);
            String retString = object.getString("ret");
            Log.d("jsonTest", "ret = " + retString + "\n");
            JSONArray dataJSONArray = object.getJSONArray("data");
            for(int i = 0; i < dataJSONArray.length(); i++) {
                JSONObject jsonObject = dataJSONArray.getJSONObject(i);
                String idString = jsonObject.getString("id");
                String titleString = jsonObject.getString("title");
                String picString = jsonObject.getString("pic");
                String collect_numString = jsonObject.getString("collect_num");
                String food_strString = jsonObject.getString("food_str");
                int numInt = jsonObject.getInt("num");

                String message = "id = " + idString
                        + " , title = " + titleString
                        + " , pic = " + picString
                        + " , collect_num = " + collect_numString
                        + " , food_str = " + food_strString
                        + " , num = " + numInt
                        + "\n\n";
                Log.d("jsonTest", message);

                sb.append(message);
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

显示

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            result = (String) msg.obj;
            resultTextView.setText(parseJson(result));

        }
    };

2、效果图

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值