Java 字符串到 JSON 的转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20070382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:52:29  来源:igfitidea点击:

Java String to JSON conversion

javajsonweb-services

提问by Junaid Akhtar

i am getting data from restful api in String variable now i want to convert to JSON object but i am having problem while conversion it throws exception .Here is my code :

我正在从字符串变量中的 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);

MY string contain

我的字符串包含

 {"data":{"name":"New Product","id":1,"description":"","is_active":true,"parent":{"id":0,"name":"All Projects"}}}

this is the string which i want in json but it shows me Exception in thread "main"

这是我在 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)

采纳答案by SudoRahul

The nameis present inside the data. You need to parse a JSON hierarchically to be able to fetch the data properly.

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.

Note: This example uses the org.json.JSONObjectclass and not org.json.simple.JSONObject.

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



As "Matthew" mentioned in the comments that he is using org.json.simple.JSONObject, I'm adding my comment details in the answer.

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

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

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

Sample from the link provided:

提供的链接中的示例:

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

回答by Prithvipal Singh

Instead of JSONObject , you can use ObjectMapper to convert java object to json string

您可以使用 ObjectMapper 将 java 对象转换为 json 字符串,而不是 JSONObject

ObjectMapper mapper = new ObjectMapper();
String requestBean = mapper.writeValueAsString(yourObject);

回答by Sudhanshu Umalkar

You are getting NullPointerException as the "output" is null when the while loop ends. You can collect the output in some buffer and then use it, something like this-

当 while 循环结束时,您将收到 NullPointerException,因为“输出”为空。您可以在某个缓冲区中收集输出然后使用它,就像这样 -

    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();

回答by Rahul Chauhan

Converting the String to JsonNode using ObjectMapper object :

使用 ObjectMapper 对象将字符串转换为 JsonNode:

ObjectMapper mapper = new ObjectMapper();

// For text string
JsonNode = mapper.readValue(mapper.writeValueAsString("Text-string"), JsonNode.class)

// For Array String
JsonNode = mapper.readValue("[\"Text-Array\"]"), JsonNode.class)

// For Json String 
String json = "{\"id\" : \"1\"}";
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = mapper.getFactory();
JsonParser jsonParser = factory.createParser(json);
JsonNode node = mapper.readTree(jsonParser);