如何从Android中的JSON解析多个值?

时间:2012-09-26 20:01:28

标签: java android json

我第一次尝试解析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数据。

我该怎么做?

1 个答案:

答案 0 :(得分: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.
    }
}