将String转换为JSONObject时获取所有Json元素

时间:2014-09-25 12:43:14

标签: android json jsonobject

我在此链接中有一个json代码:here

我正在尝试用该代码解析它:

  JSONObject jsonObj;
        try {
            jsonObj = new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
            System.out.println("jsonObj: "+jsonObj);

            jArray = new JSONArray();
            jArray.put(jsonObj);

        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

但它只给出了第一个元素。如何获取JSON的所有元素?

1 个答案:

答案 0 :(得分:1)

这是一个无效的JSON,你需要添加' {"":your_JSON_here}' andit将工作

您的代码将是这样的:

JSONObject jsonObj;
        try {
            jsonObj = new JSONObject(json.substring(json.indexOf("{\"\":"), json.lastIndexOf("}") + 1));
            System.out.println("jsonObj: "+jsonObj);

            jArray = new JSONArray();
            jArray.put(jsonObj);

        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }