gpt4 book ai didi

Java 字符串到 JSON 的转换

转载 作者:太空狗 更新时间:2023-10-29 22:32:50 24 4
gpt4 key购买 nike

我正在从 String 变量中的 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)

最佳答案

name 出现在 data 中。您需要分层解析 JSON 才能正确获取数据。

JSONObject jObject  = new JSONObject(output); // json
JSONObject data = jObject.getJSONObject("data"); // get data object
String projectname = data.getString("name"); // get the name from data.

注意:此示例使用 org.json.JSONObject 类而不是 org.json.simple.JSONObject


正如“Matthew”在评论中提到的,他正在使用 org.json.simple.JSONObject,我将在答案中添加我的评论详细信息。

Try to use the org.json.JSONObject instead. But then if you can't change your JSON library, you can refer to this example which uses the same library as yours and check the how to read a json part from it.

所提供链接中的示例:

JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");

关于Java 字符串到 JSON 的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20070382/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com