Java 字符串到 JSON 的转换
2022-09-02 03:41:36
我正在从字符串变量中的restful api获取数据,现在我想转换为JSON对象,但我在转换时遇到了问题,它引发了异常。这是我的代码:
URL url = new URL("SOME URL");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
JSONObject jObject = new JSONObject(output);
String projecname=(String) jObject.get("name");
System.out.print(projecname);
我的字符串包含
{"data":{"name":"New Product","id":1,"description":"","is_active":true,"parent":{"id":0,"name":"All Projects"}}}
这是我想要的json字符串,但它在线程“main”中向我显示异常
java.lang.NullPointerException
at java.io.StringReader.<init>(Unknown Source)
at org.json.JSONTokener.<init>(JSONTokener.java:83)
at org.json.JSONObject.<init>(JSONObject.java:310)
at Main.main(Main.java:37)