android JSON資料格式 解析,androidjson

來源:互聯網
上載者:User

android JSON資料格式 解析,androidjson

一、   JSON (JavaScript Object Notation)一種簡單的資料格式,比xml更輕巧。
 Json建構於兩種結構:  最後再加一種格式在文章的最後顯示出來很少有的格式
     1、“名稱/值”對的集合(A collection of name/value pairs)。不同的語言中,它被理解為對象(object),紀錄(record),結構(struct),字典(dictionary),雜湊表(hash table),有鍵列表(keyed list),或者關聯陣列 (associative array)。 如:     
        {
            “name”:”jackson”,
            “age”:100
         }


    2、值的有序列表(An ordered list of values)。在大部分語言中,它被理解為數組(array)如:
     {
        “students”:
        [
            {“name”:”jackson”,“age”:100},
            {“name”:”michael”,”age”:51}
        ]
     }
二、java解析JSON步驟
    A、伺服器端將資料轉換成json字串
      首先、伺服器端項目要匯入json的jar包和json所依賴的jar包至builtPath路徑下(這些可以到JSON-lib官網下載:http://json-lib.sourceforge.net/)
 
 JSON <wbr>之JAVA <wbr>解析
    然後將資料轉為json字串,核心函數是:
 public static String createJsonString(String key, Object value)
    {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(key, value);
        return jsonObject.toString();
    }
B、用戶端將json字串轉換為相應的javaBean
   1、用戶端擷取json字串(因為android項目中已經整合了json的jar包所以這裡無需匯入)
public class HttpUtil
{
   
    public static String getJsonContent(String urlStr)
    {
        try
        {// 擷取HttpURLConnection連線物件
            URL url = new URL(urlStr);
            HttpURLConnection httpConn = (HttpURLConnection) url
                    .openConnection();
            // 設定串連屬性
            httpConn.setConnectTimeout(3000);
            httpConn.setDoInput(true);
            httpConn.setRequestMethod("GET");
            // 擷取相應碼
            int respCode = httpConn.getResponseCode();
            if (respCode == 200)
            {
                return ConvertStream2Json(httpConn.getInputStream());
            }
        }
        catch (MalformedURLException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "";
    }


   
    private static String ConvertStream2Json(InputStream inputStream)
    {
        String jsonStr = "";
        // ByteArrayOutputStream相當於記憶體輸出資料流
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        // 將輸入資料流轉移到記憶體輸出資料流中
        try
        {
            while ((len = inputStream.read(buffer, 0, buffer.length)) != -1)
            {
                out.write(buffer, 0, len);
            }
            // 將記憶體流轉換為字串
            jsonStr = new String(out.toByteArray());
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return jsonStr;
    }
}
2、擷取javaBean
    public static Person getPerson(String jsonStr)
    {
        Person person = new Person();
        try
        {// 將json字串轉換為json對象
            JSONObject jsonObj = new JSONObject(jsonStr);
            // 得到指定json key對象的value對象
            JSONObject personObj = jsonObj.getJSONObject("person");
            // 擷取之對象的所有屬性
            person.setId(personObj.getInt("id"));
            person.setName(personObj.getString("name"));
            person.setAddress(personObj.getString("address"));
        }
        catch (JSONException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        return person;
    }


    public static List<Person> getPersons(String jsonStr)
    {
        List<Person> list = new ArrayList<Person>();


        JSONObject jsonObj;
        try
        {// 將json字串轉換為json對象
            jsonObj = new JSONObject(jsonStr);
            // 得到指定json key對象的value對象
            JSONArray personList = jsonObj.getJSONArray("persons");
            // 遍曆jsonArray
            for (int i = 0; i < personList.length(); i++)
            {
                // 擷取每一個json對象
                JSONObject jsonItem = personList.getJSONObject(i);
                // 擷取每一個json對象的值
                Person person = new Person();
                person.setId(jsonItem.getInt("id"));
                person.setName(jsonItem.getString("name"));
                person.setAddress(jsonItem.getString("address"));
                list.add(person);
            }
        }
        catch (JSONException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        return list;
    }




這裡是第三種格式 
{"state":"true","classNo":["HA_2012","4567","4566","test001"]}
解析的方法為
if (result.getString("state").equals("true")) {
try {


JSONArray show=result.getJSONArray("classNo");

List<String> list=new ArrayList<String>();
for(int i=0;i<show.length();i++){
list.add(show.getString(i));
}

到這裡三種結束

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.