如何正确选择json结构

时间:2016-07-22 09:09:20

标签: java mysql arrays json

您好我有一个PHP脚本将用户数据输入到mysql中,我从mysql中获取数据结果,最后通过PHP的json_encode functino获取json格式。该文件的内容如下。

[{"priority":"1","rule_body":"person(?x),pid(?y),haspid(?x,?y)","cons":"patient(?x)","boolean":"1"},
{"priority":"1","rule_body":"patient(?x),hasbp(high)","cons":"situation(emergency)","boolean":"1"},
{"priority":"1","rule_body":"patient(?x),hasbp(high)","cons":"situation(emergency)","boolean":"1"},
{"priority":"1","rule_body":"patient(?x),hasbp(high)","cons":"situation(emergency)","boolean":"1"},
{"priority":"1","rule_body":"aaa(bbb)","cons":"z(x)","boolean":"1"},
{"priority":"1","rule_body":"aaa(bbb)","cons":"z(x)","boolean":"1"},
{"priority":"1","rule_body":"aaa(bbb)","cons":"z(x)","boolean":"1"}]

但是现在我需要在JAVA中读取json,并且为了方便起见,我将json文件的内容复制并粘贴到字符串中。我能够阅读内容但位置已更改为以下序列

这是输出

    LENGTH IS____7
{"priority":"1","boolean":"1","rule_body":"person(?x),pid(?y),haspid(?x,?y)","cons":"patient(?x)"}
{"priority":"1","boolean":"1","rule_body":"patient(?x),hasbp(high)","cons":"situation(emergency)"}
{"priority":"1","boolean":"1","rule_body":"patient(?x),hasbp(high)","cons":"situation(emergency)"}
{"priority":"1","boolean":"1","rule_body":"patient(?x),hasbp(high)","cons":"situation(emergency)"}
{"priority":"1","boolean":"1","rule_body":"aaa(bbb)","cons":"z(x)"}
{"priority":"1","boolean":"1","rule_body":"aaa(bbb)","cons":"z(x)"}
{"priority":"1","boolean":"1","rule_body":"aaa(bbb)","cons":"z(x)"}

你可以看到布尔值必须在最后,但它会弹出第二个数字。我从教程中剔除了不同的代码并按照下面的方式做了一些我自己的代码但结果是一样的:在这个问题上需要帮助。

jsonInput=[....as shown above the json contents....]
JSONArray ja = new JSONArray(jsonInput);
System.out.println("LENGTH IS____"+ja.length());
  for(int x=0;x<ja.length();x++)
  {
      JSONObject jb = ja.getJSONObject(x);
      System.out.println(jb);
  }
  System.out.println("KKKKKKKKKKKKKKKKKKKKKKKKKKKKKK");

1 个答案:

答案 0 :(得分:2)

JSON未指定键As Adrian Smith said :

的订单
  

JSON库可以根据需要重新排列元素的顺序。这不是一个错误。

您可能使用org.json。您可以使用getString("myKey")访问JSONObject中的值,而无需知道他的位置。

另一种解决方案是创建一个代表您的数据的类:

public class myClass{
    private int priority;
    private String rule_body;
    private String cons;
    private String boolean; //STRING ! 1 is not a valid boolean value.
}

然后创建一个类的ArrayList,并用Gson反序列化它的JSON。

Gson myGsonTool = new Gson();
ArrayList<myClass> myData = gson.fromJson(myJsonString, ArrayList<myClass>.class);

然后,您有一个包含所有数据的POJO。您现在可以轻松访问您的数据:

//If i want the value of rule body:
myData.get(0).getRule_Body();

我不知道你的程序的目的,所以这可能不是最好的解决方案。

编辑:Gson维护记录的顺序。