從網絡獲取 JSON 數據並轉換成對應的數據結構

功能描述

工具類實現了從網絡 url 獲取到 不同數據結構的 json 數據,並轉換成指定的格式。

工具代碼

package com.xzy.util;

import android.util.Log;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 從internet獲取json數據,並轉換爲 list json 處理工具類
 *
 * @author xzy
 */
@SuppressWarnings("unused")
public class DealJsonUtils {

    /**
     * 獲取"數組形式"的JSON數據
     * 要解析的數據結構 [{"stuNo":100,"name":"小明"},{"stuNo":101,"name":"小張"}]
     *
     * @param path 請求 url
     * @return list
     * @throws Exception 異常處理
     */
    public static List<Map<String, String>> getJSONArray(String path) throws Exception {
        String json;
        List<Map<String, String>> list = new ArrayList<>();
        Map<String, String> map;
        URL url = new URL(path);
        // HttpURLConnection對象,從網絡中獲取網頁數據
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        // 設置超時時間爲5秒
        conn.setConnectTimeout(5 * 1000);
        // HttpURLConnection是通過HTTP協議請求path路徑的,所以需要設置請求方式,可以不設置,因爲默認爲GET
        conn.setRequestMethod("GET");
        // 判斷請求是否成功,成功時請求碼爲200,否則失敗
        if (conn.getResponseCode() == 200) {
            // 獲取數據輸入流
            InputStream is = conn.getInputStream();
            // 把輸入流轉換成字符數組
            byte[] data = readStream2Array(is);
            // 字符數組轉換成字符串
            json = new String(data);
            // 數據形式:[{"stuNo":100,"name":"小明"},{"stuNo":101,"name":"小張"}]數據爲數組形式,直接用 android框架
            JSONArray jsonArray = new JSONArray(json);
            for (int i = 0; i < jsonArray.length(); i++) {
                // 獲取每條數據中的對象
                JSONObject item = jsonArray.getJSONObject(i);
                // 注意key值要一致*/
                String stuNo = item.getString("stuNo");
                String name = item.getString("name");

                map = new HashMap<>();
                map.put("stuNo", stuNo);
                map.put("name", name);

                list.add(map);
            }
        }
        return list;
    }

    /**
     * 獲取"對象形式"的JSON數據
     * 數據形式:{"total":2,"success":true,"appList":[{"id":1,"name":"小豬"},{"id":2,"name":"小貓"}]}
     * 返回的數據形式是一個Object類型,所以可以直接轉換成一個Object
     *
     * @param path 請求 url
     * @return 返回List
     */
    public static List<Map<String, String>> getJSONObject(String path) throws Exception {
        List<Map<String, String>> list = new ArrayList<>();
        Map<String, String> map;
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        // 單位是毫秒,設置超時時間爲5秒
        conn.setConnectTimeout(5 * 1000);
        conn.setRequestMethod("GET");
        if (conn.getResponseCode() == 200) {
            InputStream is = conn.getInputStream();
            byte[] data = readStream2Array(is);
            String json = new String(data);
            JSONObject jsonObject = new JSONObject(json);
            // json對象中有一個數組數據,又可以使用getJSONArray獲取數組
            JSONArray jsonArray = jsonObject.getJSONArray("appList");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject item = jsonArray.getJSONObject(i);
                String id = item.getString("id");
                String name = item.getString("name");

                map = new HashMap<>();
                map.put("id", id);
                map.put("name", name);
                list.add(map);
            }
        }
        return list;
    }

    /**
     * 獲取類型複雜的JSON數據
     *
     * 數據形式: {"name":"小豬", "age":23, "content":{"questionsTotal":2, "questions": [ { "question": "what's your name?",
     * "answer": "小豬"}, {"question": "what's your age", "answer": "23"}] } }
     *
     * @param path 請求 url
     * @return list
     * @throws Exception 異常處理
     */
    public static List<Map<String, String>> getComplexJSON(String path) throws Exception {
        List<Map<String, String>> list = new ArrayList<>();
        Map<String, String> map;
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5 * 1000);
        conn.setRequestMethod("GET");
        if (conn.getResponseCode() == 200) {
            InputStream is = conn.getInputStream();
            byte[] data = readStream2Array(is);
            String json = new String(data);

            JSONObject jsonObject = new JSONObject(json);
            String name = jsonObject.getString("name");
            int age = jsonObject.getInt("age");
            Log.i("abc", "name:" + name + " | age:" + age);
            JSONObject contentObject = jsonObject.getJSONObject("content");
            String questionsTotal = contentObject.getString("questionsTotal");
            JSONArray contentArray = contentObject.getJSONArray("questions");
            for (int i = 0; i < contentArray.length(); i++) {
                JSONObject item = contentArray.getJSONObject(i);
                String question = item.getString("question");
                String answer = item.getString("answer");

                map = new HashMap<>();
                map.put("question", question);
                map.put("answer", answer);
                map.put("total", questionsTotal);
                list.add(map);
            }
        }
        return list;
    }

    /**
     * 把輸入流轉換成字符數組
     */
    private static byte[] readStream2Array(InputStream inputStream) throws Exception {
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) != -1) {
            bout.write(buffer, 0, len);
        }
        bout.close();
        inputStream.close();
        return bout.toByteArray();
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章