How to convert Java String to JSON Object

后端 未结 5 1269
暖寄归人
暖寄归人 2020-12-29 12:07

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


I am trying to convert a java s

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-29 12:42

    Your json -

    {
        "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"
        }
        ]
        }
    

    Using the JSON library from json.org -

    JSONObject o = new JSONObject(jsonString);
    

    NOTE:

    The following information will be helpful to you - json.org.

    UPDATE:

    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.toString());
     System.out.println(jsonString);
     System.out.println("---------------------------");
     System.out.println(jsonObj);
    

提交回复
热议问题