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

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

问题描述:

这个问题先前已经问过了,但是我无法从对这些问题的回答中找出代码中的错误.

This question has been asked earlier, but I am unable to figure out the error in my code from the responses to those questions.

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

I am trying to convert a java string into json object. Here is the code:

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.

So, as you can see, the jsonstring is getting the data, but the jsonObj does not. I am using org.json JAR.

您正在将StringBuilder类的实例传递给JSONObject构造函数.

You are passing into the JSONObject constructor an instance of a StringBuilder class.

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

This is using the JSONObject(Object) constructor, not the JSONObject(String) one.

您的代码应为:

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