Java String to JSON转换
我正在从String变量中的restful api获取数据现在我想转换为JSON对象但我遇到问题而转换它会引发exception。这是我的代码:
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”中显示我的exception
java.lang.NullPointerException at java.io.StringReader.(Unknown Source) at org.json.JSONTokener.(JSONTokener.java:83) at org.json.JSONObject.(JSONObject.java:310) at Main.main(Main.java:37)
该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
。
正如“Matthew”在评论中提到他正在使用org.json.simple.JSONObject
,我在答案中添加了我的评论细节。
尝试使用
org.json.JSONObject
。 但是如果你不能改变你的JSON库,你可以参考这个使用与你相同的库的例子 ,并检查如何从中读取json部分。
提供的链接示例:
JSONObject jsonObject = (JSONObject) obj; String name = (String) jsonObject.get("name");
您可以使用ObjectMapper将java对象转换为json字符串,而不是JSONObject
ObjectMapper mapper = new ObjectMapper(); String requestBean = mapper.writeValueAsString(yourObject);
您正在获取NullPointerException,因为while循环结束时“output”为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();
使用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);
- 使用带有Spring Boot的Java API for WebSocket(JSR-356)
- 使用maven2使用jdk1.5编译项目
- Java – 在for循环中声明变量
- 使用Akka和Play Framework在Java中进行异步文件上载
- 如何将Enum嵌套在Enum的值中
- Maven从伟大的父母那里获取依赖版本,而不是我们父母的依赖管理
- java.lang.NoClassDefFoundError:org / openxmlformats / schemas / spreadsheetml / x2006 / main / CTWorkbook $ Factory
- 如何重新排序PDF文件的页面?
- 如何在JDK中启动eclipse?