如何制作JSON字符串?

时间:2016-05-02 11:53:38

标签: java android json parsing

我有以下示例,其中我得到一个解析我的Json数据的异常:

String s = "{\n" +
        "\t\"foo1\": {\n" +
        "\t\t\"array1\": [\n" +
        "\t\t\t[1, \"One\"],\n" +
        "\t\t\t[2, \"Two\"],\n" +
        "\t\t\t[3, \"Three\"]\n" +
        "\t\t]\n" +
        "\t}\n" +
        "}";
JSONObject jsonObject = new JSONObject(s); // Exception because the file could not be parsed

这只是一个例子。通常我从JSON文件中读取字符串,但我的字符串内容是相同的。

在我做的真实例子中:

InputStream inputStream = assets.open(path);

int size = inputStream.available();
byte[] buffer = new byte[size];
inputStream.read(buffer);
inputStream.close();

String s = new String(buffer, "UTF-8");

我需要更改以解析我的JSON?

修改 错误是:cannot evaluate org.json.jsonobject.tostring()

3 个答案:

答案 0 :(得分:1)

您提到我尝试在我的系统中运行的示例我能够正确解析它:

String s = "{\n" +
                "\t\"foo1\": {\n" +
                "\t\t\"array1\": [\n" +
                "\t\t\t[1, \"One\"],\n" +
                "\t\t\t[2, \"Two\"],\n" +
                "\t\t\t[3, \"Three\"]\n" +
                "\t\t]\n" +
                "\t}\n" +
                "}";
        try {
            JSONObject jsonObject = new JSONObject(s);
                JSONObject foo1 = jsonObject.optJSONObject("foo1");
                    JSONArray array1 = foo1.optJSONArray("array1");
                        for (int i=0;i<array1.length();i++){
                            JSONArray list=array1.getJSONArray(i);
                            Log.e("out put "+i,list.optString(0) +":"+list.optString(1));
                        }

        } catch (JSONException e) {
            e.printStackTrace();
        }


   输出:

 output 0: 1:One
 output 1: 2:Two
 output 2: 3:Three

答案 1 :(得分:0)

可以使用Gson从Java对象创建Json字符串。

Gson gson = new Gson();

String json = gson.toJson(myObject); // myObject - instance of MyObject

答案 2 :(得分:0)

String s = "[\n" +
    "\t\t\t[1, \"One\"],\n" +
    "\t\t\t[2, \"Two\"],\n" +
    "\t\t\t[3, \"Three\"]\n" +
    "\t\t]\n" +
    "\t}\n" +
    "}";

JSONObject array1 = new JSONObject();
array1.put(s);
JSONObject foo1 = new JSONObject(); 
finaldata.put("array1", array1);