Java 字符串到 JSON 的转换

Posted

技术标签:

【中文标题】Java 字符串到 JSON 的转换【英文标题】:Java String to JSON conversion 【发布时间】:2013-12-02 22:29:16 【问题描述】:

我正在从 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)

【问题讨论】:

【参考方案1】:

使用 ObjectMapper 对象将 String 转换为 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);

【讨论】:

【参考方案2】:

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


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

尝试改用org.json.JSONObject。但是,如果您无法更改 JSON 库,您可以 refer to this example 使用与您相同的库并检查如何从中读取 json 部分。

来自所提供链接的示例:

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

【讨论】:

我的org.json.simple.JSONObject没有String的构造函数,只有一个默认的构造函数和一个带Map的构造函数? @MatthewMoisen - 尝试改用org.json.JSONObject。但是,如果您无法更改 JSON 库,您可以参考 this example,它使用与您相同的库并检查如何从中读取 json 部分。应该对你相当有用:)【参考方案3】:

当 while 循环结束时,您将收到 NullPointerException,因为“输出”为 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();

【讨论】:

【参考方案4】:

可以使用 ObjectMapper 代替 JSONObject 将 java 对象转换为 json 字符串

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

【讨论】:

问题是关于将 Java 字符串转换为 JSON 而不是反之亦然 它将用斜杠(java字符串)给出数据。不是正确的 Json 格式 [\"date\":\"2020-01-03\"]。

以上是关于Java 字符串到 JSON 的转换的主要内容,如果未能解决你的问题,请参考以下文章

Spark 将 JSON 字符串转换为 JSON 对象(Java)

json字符串怎么转换为java对象

JSON-JSON字符串转换成JSON对象JSON对象数组java实体类以及保存到List列表中

Jackson 对象和JSON的相互转换

java中把json怎么转换成数组

JAVA对象转换成JSON字符串与JAVA String有啥区别