【问题标题】:Is there a way to parse JSON with java? [duplicate]有没有办法用java解析JSON? [复制]
【发布时间】:2016-07-10 22:15:31
【问题描述】:

这是我目前所拥有的:

 public Bitmap getAlbumCover(Context context, String song, String artist) {
    this.context = context;
    song = song.replace(" ", "%20");
    artist = artist.replace(" ", "%20");

    try {
        conn = new URL("https://api.spotify.com/v1/search?q=track" + song + ":%20artist:" + artist + "&type=track)").openConnection();
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (conn != null)
        conn.setDoOutput(true);


    try {
        reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (reader != null) {
        // Read Server Response
        String line2 = null;
        try {
            while ((line2 = reader.readLine()) != null) {
                sb.append(line2);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            json = new JSONArray(sb.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    JSONParser parser= new JSONParser();
    try {
        JSONObject jsonObject = (JSONObject) parser.parse(reader);
        try {
            array = (JSONArray) jsonObject.get("items");
        } catch (JSONException e) {
            e.printStackTrace();
        }


        // take each value from the json array separately

    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return null;

}

我使用的 JSON 位于此处: https://api.spotify.com/v1/search?q=track:Ready%20To%20Fall%20artist:rise%20against%20&type=track

我正在尝试获取位于 images 数组中的图像 url 和位于 items 中的 preview_track url。

【问题讨论】:

标签: java json


【解决方案1】:

我使用 Jackson 库将 JSON 解析为 java opbject。

如果您使用与 JSON 相同的结构创建 java 对象,则可以使用以下方法完成:

   ObjectMapper mapper = new ObjectMapper();
   mapper.readValue(jsonUrl, YourClass.class);

因此,您的 OBJECT 将具有曲目,然后曲目将具有对象专辑,而专辑将具有对象的其他详细信息。只需像 JSON 那样构建它,你就在那里。

【讨论】:

    猜你喜欢
    • 2014-02-25
    • 1970-01-01
    • 1970-01-01
    • 2020-05-16
    • 2013-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-17
    相关资源
    最近更新 更多