我是 Android 的新手。我在 JAVA 中有一个有效的 JSON 阅读代码,如下所示。将文件保存为字符串,然后从中创建 JSON数组。我想在android中做同样的事情,但它说错误(如下所示)
String jsonInput = new Scanner(new File("c:\\patient.txt")).useDelimiter("\\Z").next();
JSONArray ja = new JSONArray(jsonInput);
System.out.println("LENGTH IS____"+ja.length());
String[][] table = new String[ja.length()][4];
for(int y=0;y<ja.length();y++)
{
JSONObject jb = ja.getJSONObject(y);
System.out.println(jb.length());
String p=jb.getString("priority");
String r=jb.getString("rule_body");
String c=jb.getString("cons");
String b=jb.getString("boolean");
System.out.println("Priority: "+p+"- Rule Body: "+r+"- Consequence: "+c+"- flag: "+b);
table[y][0]=p;
table[y][1]=r;
table[y][2]=c;
table[y][3]=b;
}
按预期正常工作。我想在Android中做同样的事情(将文本文件复制到assets文件夹)但我得到错误
Call require API 19 and the MIN is 8
我需要一个帮助,如何在工作API中对此进行排序。我试图从JSON文件中获取数组,正如我在这里看到的,大多数示例都是针对JSON对象的。发布的问题JSONArray not supported before Android API 19没有像我所说的那样清楚地提到问题。
InputStream json= getAssets().open("patient.txt");
JSONArray ja=new JSONArray(json);
System.out.println("LENGTH IS____"+ja.length());
String[][] table = new String[ja.length()][4];
JSON的结构是
[{"priority":"1","rule_body":"person(?x),patientid(?y),hasid(?x,?y)","cons":"patient(?x)","boolean":"1"},{"priority":"2","rule_body":"patient(?x),hasbp(?x,high)","cons":"hassituation(?x,emergency)","boolean":"1"},{"priority":"3","rule_body":"patient(?x),hassituation(?x,emergency)","cons":"calldr(emergency)","boolean":"1"},{"priority":"4","rule_body":"patient(?x),calldr(emergency)","cons":"calling_in_dr(emergency)","boolean":"1"},{"priority":"5","rule_body":"patient(?x),calling_in_dr(emergency)","cons":"cured(?x)","boolean":"1"}]
使用php编码方法编码。
答案 0 :(得分:2)
用这个代替你的代码。这也适用于较低的API。您将InputStream
对象作为参数传递,而不是通过String
。
InputStream is = getAssets().open("patient.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String json = new String(buffer, "UTF-8");
JSONArray ja = new JSONArray(json);
System.out.println("LENGTH IS____"+ ja.length());
String[][] table = new String[ja.length()][4];
答案 1 :(得分:0)
这是获取JsonArray的正确方法
JSONArray resultArray = obj.getJSONArray("results");