简体   繁体   中英

Parsing and retrieving information from JSON in Java — JSONObject vs. JSONArray?

I'm just starting to mess around with some web programming, and am trying to retrieve information about certain musical artists from a music website's API. I'm using the JSON.simple toolkit found here.

Here's my code. Two classes, one is JSONReader :

import org.json.simple.*;
import org.json.simple.parser.*;

import java.net.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;

public class JSONReader {

private static String readAll(Reader rd) throws IOException {
    StringBuilder sb = new StringBuilder();
    int cp;
    while ((cp = rd.read()) != -1) {
      sb.append((char) cp);
    }
    return sb.toString();
  }

public static JSONObject readJsonFromUrl(String url) throws IOException, ParseException {
    JSONParser parser = new JSONParser();
    InputStream is = new URL(url).openStream();
    try {
      BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
      String jsonText = readAll(rd);
      Object obj = parser.parse(jsonText);
      JSONObject result = (JSONObject) obj;
      return result;

    } finally {
      is.close();
    }
  }

}

Okay, and here's my Main class:

public class Main {

public static void main(String[] args) throws Exception {
    System.out.println("Starting execution of program...");
    String searchQuery = args[0];
    JSONReader reader = new JSONReader();

    System.out.println("Beginning HTTP request...");
    String baseURL = "http://api.discogs.com/database/search?q=" + searchQuery + "&type=artist";

    JSONObject json = reader.readJsonFromUrl(baseURL);
    System.out.println(json);

The print statement at the end of the main gives me this:

{"results":[{"id":22898,"title":"Tool","type":"artist","resource_url":"http:\/\/api.discogs.com\/artists\/22898","uri":"\/artist\/Tool","thumb":null},{"id":5481,"title":"DJ Tool","type":"artist","resource_url":"http:\/\/api.discogs.com\/artists\/5481","uri":"\/artist\/DJ+Tool","thumb":null},{"id":186087,"title":"Tool (3)","type":"artist","resource_url":"http:\/\/api.discogs.com\/artists\/186087","uri":"\/artist\/Tool+%283%29","thumb":null},{"id":108078,"title":"Rave Tool","type":"artist","resource_url":"http:\/\/api.discogs.com\/artists\

with about a dozen more artists, all distinguished individually by curly braces with commas in-between.

So I "get" the results by doing:

System.out.println(json.get("results"));

And end up with:

[{"id":22898,"title":"Tool","type":"artist","resource_url":"http:\/\/api.discogs.com\/artists\/22898","uri":"\/artist\/Tool","thumb":null},{"id":5481,"title":"DJ Tool", ... ]

The problem is, I want to be able to, say, extract all dozen or so artists from the search result.

I cast the above to a JSONArray as below, and I can then 'get' indexes of the search result. My question, after this long post, is: why is this? What, essentially, is the point of the JSONObject in the first place, if it needs to be a JSONArray for accessing index of the results to work? Also, is there a reason I can't set the result of parsing jsonText directly to a JSONArray ? When I try and change all of the "JSONObject"s in the readJsonFromUrl method to JSONArrays , an error occurs, saying that it is unable to cast a JSONObject to a JSONArray . Why is this?

JSONArray json1 = (JSONArray) reader.readJsonFromUrl(baseURL).get("results");
System.out.println(json1);
System.out.println(json1.get(0));

The reason is simply the structure of your JSON input data: it is a JSON object with only a results property, whose value is an array, this array containing the data you actually want.

Since you have an object, whose single property is an array with the data that you want, you must parse the whole object to get at the array.

This seems like a rather trivial object having only a single property, but this isn't uncommon in JSON responses, indeed in any sort of network communication: the result that you actually want is wrapped in an object that will sometimes contain additional properties that provide meta-information associated with the actual result data.

Think of this outer object as an envelope that contains your result.

You can make the result of parsing the response - the result of your readJsonFromUrl method - the array, by discarding the outer object in your read method, but sometimes there will be more to the containing object that you might want to preserve, for instance some header data/meta-information that comes along with the results list, that may influence how you use the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM