从字符串JSON数据获取嵌套的JSON数据
问题描述:
我想从使用JSONObject和JSONArray的字符串JSON数据嵌套JSON数据。该代码正在编译没有任何错误,但结果即将到来空而不是关联的字符串。如果有任何替代方法嵌套JSON字符串,请建议。从字符串JSON数据获取嵌套的JSON数据
我的代码:
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();
}
}
}
答
尝试下面的代码,我认为它应该为你工作:
while((out=c.readLine())!=null){
sb=sb.append(out);
}
out1=sb.toString();
请让我知道它是为你工作或没有?
+0
达部分代码没有问题。问题是这部分代码使用我需要创建一个嵌套的JSON。 JSONParser parser = new JSONParser(); 尝试{obj = parser.parse(out1); JSONObject jsonObject =(JSONObject)obj; String name =(String)jsonObject.get(“Name”); System.out.println(name); } – codehacker
答
而不是使用JSONParser得到的JSONObject你可以直接使用下面的代码
JSONObject jsonObj = new JSONObject(out1)
这是怎么从你问一个小时前的问题有什么不同? https://stackoverflow.com/questions/40648754/pasring-json-data-using-java – rafid059
它的一个不同的代码 – codehacker
发布你的完整堆栈跟踪,也是你的json文件的样本 – rafid059