Json解析Android应用程序

时间:2010-09-29 06:34:23

标签: android json parsing

现在完成XML SAX Parsing后,我正在我的应用程序中进行JSON解析。我在这里为你提供Json

Response : {"menu": {
              "id": "file",
              "value": "File",
              "popup": {
                "menuitem": [
                  {"value": "New", "onclick": "CreateNewDoc()"},
                  {"value": "Open", "onclick": "OpenDoc()"},
                  {"value": "Close", "onclick": "CloseDoc()"}
                ]
              }
            }}

现在我已经提到了一个Json Parsing的例子,他们在这个例子中创建了一个jString对象,我对该特定行有疑问,如下所示:

private String jString = "{\"menu\":    {\"id\": \"file\", \"value\": \"File\", \"

请有人帮我说清楚。 完整示例的链接如下:

http://www.androidcompetencycenter.com/2009/10/json-parsing-in-android/

2 个答案:

答案 0 :(得分:2)

您可以从响应中获取JSON对象(我假设您知道如何处理响应):

String[] file = null;

/* Make a JSON object from your response, yourResponse is a String containing
the whole response */
JSONObject jsonObject = new JSONObject(yourResponse);

/* Your "menu": array from your response */
JSONArray infoArray = jsonObject.getJSONArray("menu"); 

/* If the array contains multiple items, loop it
through the infoArray's size */
for (int i = 0; i < infoArray.length(); i++) {  
        try {    
          //Get the value inside "id"
          file[i] = infoArray.getJSONObject(i).optString("id");                  
            } catch (JSONException e) {
            }       
}

答案 1 :(得分:1)

private String jString = "{\"menu\":    {\"id\": \"file\", \"value\": \"File\", \"

他们只是创建一个看起来像的字符串:

{"menu":    {"id": "file", "value": "File", .. etc.

他们使用\因为"字符必须被转义。