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)

答案 1

存在于 .您需要分层解析 JSON 才能正确获取数据。namedata

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.JSONObjectorg.json.simple.JSONObject


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

请尝试改用 。但是,如果您无法更改JSON库,则可以参考此示例,该示例使用与您的库相同的库,并检查如何从中读取json部分。org.json.JSONObject

提供的链接中的示例:

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

答案 2

您将获得 NullPointerException,因为当 while 循环结束时,“输出”为 null。您可以在某个缓冲区中收集输出,然后使用它,如下所示 -

    StringBuilder buffer = new StringBuilder();
    String output;
    System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {
        System.out.println(output);
        buffer.append(output);
    }
    output = buffer.toString(); // now you have the output
    conn.disconnect();