Java String to JSON转换 [英] Java String to JSON conversion

查看:1998
本文介绍了Java String to JSON转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从String变量中的restful api获取数据现在我想转换为JSON对象但是我在转换时遇到问题它会抛出异常。这是我的代码:

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 :

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中显示异常

this is the string which i want in json but it shows me Exception in thread "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)


推荐答案

名称存在于数据中。您需要分层解析JSON以便能够正确获取数据。

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

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 class而不是 org.json.simple.JSONObject

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

正如Matthew在评论中提到他正在使用 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.JSONObject 。但是如果你不能改变你的JSON库,你可以参考此示例,它使用与您相同的库,并检查如何从中读取json部分。

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

来自提供的链接的示例:

Sample from the link provided:

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

这篇关于Java String to JSON转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆