简体   繁体   English

如何在Java中读取JSON?

[英]How to read JSON in Java?

I have a JSON String and I got the data element's data to JSONObject . 我有一个JSON字符串,并且将data元素的数据存储到JSONObject After I read this that resultant string is as follows. 在我读完这篇文章之后,结果字符串如下。 I'm using org.json library. 我正在使用org.json库。

String dataStr = "[{\"name\":\"jhonny\",\"counts\":[\"50\",\"44\",\"46\"],\"url\":\"google\"},
 {\"name\":\"john\",\"counts\":[\"344\",\"4\",\"18\"],\"url\":\"yahoo\"}]";

I tried to read the each element like following, 我试图读取每个元素,如下所示:

String dataStr = report.get("data").toString();
JSONObject data = new JSONObject(dataStr.substring(1));
System.out.println(data);

But my output is, 但是我的输出是

{"name":"jhonny","counts":["50","44","46"],"url":"google"}

The output contains only one element. 输出仅包含一个元素。 How can I fix this? 我怎样才能解决这个问题?

Using the org.json library: 使用org.json库:

JSONObject obj = new JSONObject("{interests : [{interestKey:Dogs}, {interestKey:Cats}]}");

List<String> list = new ArrayList<String>();
JSONArray array = obj.getJSONArray("interests");
for(int i = 0 ; i < array.length() ; i++){
    list.add(array.getJSONObject(i).getString("interestKey"));
}
JSONArray jsonarray = new JSONArray(datastr);
for(int i=0; i<jsonarray.length(); i++){
    JSONObject data= jsonarray.getJSONObject(i);

    System.out.println(data);
}   

The problem is you are trying to read JSONArray as JSONObject. 问题是您试图将JSONArray读取为JSONObject。

To parse JSONArray you need to do something like: (Not sure which library you are using) 要解析JSONArray,您需要执行以下操作:(不确定使用的是哪个库)

for (int i = 0; i < jsonarray.length(); i++) {
    JSONObject jsonobject = jsonarray.getJSONObject(i);
    // jsonobject holds the desired element.
}

If you analyze your json string, you will notice that your json string contains multiple json object without outer object like :- 如果您分析json字符串,您会注意到json字符串包含多个json对象,而没有外部对象,例如:

{ 
"outer":{
          {\"name\":\"jhonny\",\"counts\":[\"50\",\"44\",\"46\"],\"url\":\"google\"},
          {\"name\":\"jhonny\",\"counts\":[\"50\",\"44\",\"46\"],\"url\":\"google\"}
        }
}

The way you are parsing require this kind of json structure. 您解析的方式需要这种json结构。 Your json string is actually just a jsonarray. 您的json字符串实际上只是一个jsonarray。 So do like this way : 所以喜欢这样:

JSONArray jsonarray = new JSONArray(datastr);
for(int i=0; i<jsonarray.length(); i++){
    JSONObject data= jsonarray.getJSONObject(i);
}

For more you can visit this link that gives you good explanation to how to read json in java 有关更多信息,您可以访问此链接,该链接为您提供了有关如何在Java中读取json的良好解释

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM