java - 如何制作 JSON 字符串?

标签 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?

编辑: 错误是:无法评估 org.json.jsonobject.tostring()

最佳答案

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

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

关于java - 如何制作 JSON 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36981807/

相关文章:

java - 在 JSONArray 中的给定位置添加值

java - 为什么在 switch 语句中不能使用对象,而可以使用枚举

android - ActionBarSherlock 静态附件菜单

json - pdf2json 页面单元 : What is it?

javascript - 为什么 D3 无法正确渲染 TopoJSON?

java - 将 ArrayList 转换为 JSON(在 Java 中)并使用 Javascript 访问它

java - 如何在 Selenium 网络驱动程序中将鼠标悬停在图像上以获取菜单列表

java - 如何在java中更改现有Excel(xlsx或xls)单元格的颜色

android - 在 Android 的谷歌地图中添加了多少个最大标记?

android - 如何在 Flutter 应用中播放 .mp3 文件?