java - 如何将 Java 字符串转换为 JSON 对象

标签 java json org.json

之前有人问过这个问题,但我无法从对这些问题的回答中找出我的代码中的错误。


我正在尝试将 java 字符串转换为 json 对象。 这是代码:

import org.json.JSONObject;
//Other lines of code
URL seatURL = new URL("http://freemusicarchive.org/api/get/genres.json?api_key=60BLHNQCAOUFPIBZ&limit=2");
//Return the JSON Response from the API
BufferedReader br = new BufferedReader(new InputStreamReader(seatURL.openStream(),Charset.forName("UTF-8")));
String readAPIResponse = " ";
StringBuilder jsonString = new StringBuilder();
while((readAPIResponse = br.readLine()) != null){
    jsonString.append(readAPIResponse);
}
JSONObject jsonObj = new JSONObject(jsonString);
System.out.println(jsonString);
System.out.println("---------------------------");
System.out.println(jsonObj);

输出是:

{"title":"Free Music Archive - Genres","message":"","errors":[],"total":"163","total_pages":82,"page":1,"limit":"2","dataset":[{"genre_id":"1","genre_parent_id":"38","genre_title":"Avant-Garde","genre_handle":"Avant-Garde","genre_color":"#006666"},{"genre_id":"2","genre_parent_id":null,"genre_title":"International","genre_handle":"International","genre_color":"#CC3300"}]}
---------------------------
{}

因此,如您所见,jsonstring 正在获取数据,但 jsonObj 没有。 我正在使用 org.json JAR。

最佳答案

您正在向 JSONObject 构造函数传递一个 StringBuilder 类的实例。

这是使用 JSONObject(Object) 构造函数,而不是 JSONObject(String) 构造函数。

您的代码应该是:

JSONObject jsonObj = new JSONObject(jsonString.toString());

关于java - 如何将 Java 字符串转换为 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29182842/

相关文章:

android - 更改或升级内置 org.json 库是否可能且是个好主意?

java - 无法将 Visualvm 远程连接到 JBoss EAP 7

java - 使用 While 循环从字符串末尾删除逗号

java - logger(java.util.logging) 突然停止将输出打印到控制台,尽管它在文件中打印

c# - 从 web api JSON C# 中删除斜线

android - 加速 JSON 对象

java - 为什么在转换为 XML 时对 JSON 内容属性进行特殊处理?

java - 如何使用 Jackson 将对象附加到现有 JSON 文件

ios - 你如何在 swift 中从 JSON 中排序 NSMutableArray?

json - 从json数据制作表格时出现jq "object cannot be tsv-formatted, only array"错误