简体   繁体   English

从字符串JSON数据获取嵌套JSON数据

[英]Getting nested JSON data from string JSON data

I am trying to get nested JSON data from string JSON data using JSONObject and JSONArray. 我正在尝试使用JSONObject和JSONArray从字符串JSON数据中获取嵌套的JSON数据。 The code is compiling without any error but the result is coming Null rather than the string associated. 代码正在编译,没有任何错误,但是结果是Null而不是关联的字符串。 If there is any alternate way to nest JSON string please suggest. 如果还有其他嵌套JSON字符串的方法,请提出建议。

My code: 我的代码:

  import java.io.*;
  import java.net.*
  import org.json.simple.JSONObject;
  import org.json.simple.parser.JSONParser;

  public class A4 {
   public static void main(String[] args){
    String out,out1= null;
    try{
        URL a=new URL("URL");
        HttpURLConnection b=(HttpURLConnection) a.openConnection();
        b.setRequestMethod("GET");
        b.setRequestProperty("Accept", "application/json");
        BufferedReader c=new BufferedReader(new InputStreamReader(b.getInputStream()));
        StringBuilder sb=new StringBuilder();
        while((out=c.readLine())!=null){
            sb.append(out);
            out1=sb.toString();
            }

       c.close();
       b.disconnect();
    }catch (Exception e){
           e.printStackTrace();
       return;
    }
    JSONParser parser = new JSONParser();
    try{
        Object obj = parser.parse(out1);
            JSONObject jsonObject = (JSONObject) obj;
            String name = (String) jsonObject.get("Name");
        System.out.println(name);
    } 
    catch (Exception e) {
        e.printStackTrace();
    }
    }
 }

try the below code i think it should work for you: 试试下面的代码,我认为它应该为您工作:

while((out=c.readLine())!=null){
    sb=sb.append(out);
}
out1=sb.toString();

please let me know whether it's working for you or not? 请让我知道它是否对您有用?

无需使用JSONParser获取JSONObject,您可以直接使用以下代码

JSONObject jsonObj = new JSONObject(out1)

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

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