JSON読み書き

6936 ワード

import android.util.Log;

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

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

public class JSONutil {
    /**
     *   "    " JSON  ,
     *     :[{"id":1,"name":"  ","age":22},{"id":2,"name":"  ","age":23}]
     * @param path
     *                
     * @return   List
     * @throws Exception
     */
    public static List> getJSONArray(String path) throws Exception{
        String json = null;
        List> list = new ArrayList>();
        Map map=null;
        URL url = new URL(path);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setConnectTimeout(5 * 1000);//      ,       5 
        // HttpURLConnection   HTTP    path   ,          ,     ,     GET
        con.setRequestMethod("GET");
        //         200 ,    
        if (con.getResponseCode() == 200){//      
            InputStream input = con.getInputStream();//            
            byte[] data = readStream(input); //            
            json = new String(data);

            //            ,        android     JSONArray  JSON  ,   Array
            JSONArray jsonArray = new JSONArray(json);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject item = jsonArray.getJSONObject(i);
                int id = item.getInt("id");
                String name = item.getString("name");
                int age = item.getInt("age");
                map = new HashMap();
                map.put("id", id + "");
                map.put("name", name);
                map.put("age", age + "");
                list.add(map);
            }
        }
        return list;
    }

    /**
     *   "    " JSON  ,
     *     :{"total":2,"success":true,"arrayData":[{"id":1,"name"
     * :"  ","age":23},{"id":2,"name":"  ","age":25}]}
     *
     * @param path
     *                
     * @return   List
     * @throws Exception
     */
    public static List> getJSONObject(String path)
            throws Exception {
        List> list = new ArrayList>();
        Map map = null;
        URL url = new URL(path);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setConnectTimeout(5 * 1000);//      ,       5 
        // HttpURLConnection   HTTP    path   ,          ,     ,     GET
        con.setRequestMethod("GET");
        if (con.getResponseCode() == 200) {
            InputStream input = con.getInputStream();
            byte[] bb = readStream(input);
            String json = new String(bb);
            //System.out.println(json);
            JSONObject jsonObject = new JSONObject(json);
            //          ,   getJSONArray    
            JSONArray jsonArray = jsonObject.getJSONArray("arrayData");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject item = jsonArray.getJSONObject(i); //       
                int id = item.getInt("id"); //         
                String name = item.getString("name");
                int age = item.getInt("age");
                map = new HashMap(); //    Map  
                map.put("id", id + "");
                map.put("name", name);
                map.put("age", age + "");
                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     
     * @return   List
     * @throws Exception
     */
    public static List> getJSON(String path)
            throws Exception {
        List> list = new ArrayList>();
        Map map = null;
        URL url = new URL(path);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setConnectTimeout(5 * 1000);//      ,       5 
        // HttpURLConnection   HTTP    path   ,          ,     ,     GET
        con.setRequestMethod("GET");
        if (con.getResponseCode() == 200) {
            InputStream input = con.getInputStream();
            byte[] bb = readStream(input);
            String json = new String(bb);

            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  
                map.put("question", question);
                map.put("answer", answer);
                list.add(map);
            }
        }
        return list;
    }


    /**
     *            
     *
     * @param inputStream
     *               
     * @return     
     * @throws Exception
     */
    public static byte[] readStream(InputStream input)throws Exception{
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = input.read(buffer)) != -1){
            bos.write(buffer, 0, len);
        }
        bos.close();
        input.close();

        return bos.toByteArray();
    }
}