Java String to JSON转换

Jun*_*tar 18 java json web-services

我正在从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);
Run Code Online (Sandbox Code Playgroud)

我的字符串包含

 {"data":{"name":"New Product","id":1,"description":"","is_active":true,"parent":{"id":0,"name":"All Projects"}}}
Run Code Online (Sandbox Code Playgroud)

这是我想要在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)
Run Code Online (Sandbox Code Playgroud)

Sud*_*hul 27

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.
Run Code Online (Sandbox Code Playgroud)

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


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

尝试使用org.json.JSONObject相反.但是如果你不能改变你的JSON库,你可以参考这个使用与你相同的库的例子,并检查如何从中读取json部分.

提供的链接示例:

JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
Run Code Online (Sandbox Code Playgroud)

  • 我的`org.json.simple.JSONObject`没有String的构造函数,只有一个默认的构造函数和一个带Map的构造函数? (3认同)