【问题标题】:Java String to JSON conversionJava 字符串到 JSON 的转换
【发布时间】: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)

【问题讨论】:

    标签: java json web-services


    【解决方案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\"}]。
        猜你喜欢
        • 2023-04-01
        • 1970-01-01
        • 2020-07-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-16
        • 2020-04-27
        相关资源
        最近更新 更多