我有以下示例,在解析 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/