java 中解析json步驟

1、   JSON (JavaScript Object Notation)一種簡單的數據格式,比xml更輕巧。
Json建構於兩種結構:
     一、「名稱/值」對的集合(A collection of name/value pairs)。不一樣的語言中,它被理解爲對象(object),紀錄(record),結構(struct),字典(dictionary),哈希表(hash table),有鍵列表(keyed list),或者關聯數組 (associative array)。 如:    
        {
            「name」:」jackson」,
            「age」:100
         }

二、值的有序列表(An ordered list of values)。在大部分語言中,它被理解爲數組(array)如:
     {
        「students」:
        [
            {「name」:」jackson」,「age」:100},
            {「name」:」michael」,」age」:51}
        ]
     }
2、java解析JSON步驟
    A、服務器端數據轉換成json字符串
      首先、服務器端項目要導入json的jar包和json所依賴的jar包至builtPath路徑下(這些能夠到JSON-lib官網下載:http://json-lib.sourceforge.net/

而後將數據轉爲json字符串,核心函數是:
public static String createJsonString(String key, Object value)
    {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(key, value);
        return jsonObject.toString();
    }
B、客戶端將json字符串轉換爲相應的javaBean
   一、客戶端獲取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;
    }
}
二、獲取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;
    }html

相關文章
相關標籤/搜索