-3

我第一次尝试解析 JSON。在我的 JSON 数据中,单个 JSON 数组中有多个 JSON 对象。数据样本:

{ "root":[ {"Sc_we":[ ]}, {"Sc_wesam":[ {"head":"欢迎页面"}, {"color":"Black"} ]} ] }

这是我的代码:

 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    try {
        website = new URL(
                    "http://xxxxxxx");
        InputStream in = website.openStream();
        parseMovie(in);
    }
    catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}


protected void parseMovie(InputStream json) throws IOException,
JSONException {
    // TODO Auto-generated method stub

    BufferedReader reader = new BufferedReader(new InputStreamReader(json));
    StringBuilder sb = new StringBuilder();
    String line = reader.readLine();
    while (line != null) {
        sb.append(line);
        line = reader.readLine();
    }
    reader.close();
    System.out.println(sb);
    JSONObject jobj = new JSONObject(sb.toString());
    System.out.println("jsonobj:" + jobj);

    JSONArray array = jobj.getJSONArray("root");

    System.out
        .println("jsonobject   :+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
                + array);
}

我得到了上面的 JSON 数据,但我需要S_we值和Sc_wesam数据。

我该怎么做呢?

4

1 回答 1

3

您可以使用 迭代单个元素JSONArray,并对您的数据做出一些假设:

JSONArray array = jobj.getJSONArray("root");
JSONObject subObj;
JSONArray subArray;

for (int i = 0; i < array.length(); i++)
{
    subObj = array.getJSONObject(i);

    if (subObj.has("Sc_wesam")) // handle Se_wesam
    {
        subArray = subObj.getJSONArray("Sc_wesam");

        for (int j = 0; j < subArray.length(); j++)
        {
            subObj = subArray.getJSONObject(j);
            if (subObj.has("head"))
                System.out.println("Sc_wesam head value: " +
                                   subObj.getString("head"));
            else if (subObj.has("color"))
                System.out.println("Sc_wesam color value: " +
                                   subObj.getString("color"));
        }
    }
    else if (subObj.has("Sc_we")) // handle Se_we
    {
        subArray = subObj.getJSONArray("Sc_wesam");

        // ... etc.
    }
}
于 2012-09-26T20:17:13.083 回答