简体   繁体   中英

How to get only the 1st element of an large array in JSON?

I have been looking at the Streaming implementation of the Gson Library. But I cannot determine if it would be a good practice to do like the following to get the 1st element of an array. The URL returns an InputStream which contains a Json array.

JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
reader.beginArray();
Message message = new gson().fromJson(reader, Message.class);
reader.endArray(); // this line
reader.close();

My question lies on the line that has the comment beside. Should I do that if I want only to get the first element?

Note that here I want to know about the efficiency of the code. The code is directly copied from the gson streaming example [with some modification to describe the situation correctly].

The actual array is very large. That's why I cannot just wait to get the whole array and then get the element. So I want to break the process as soon as I get the first element and then close the stream.

Also please recommend me of any better approach if there are any.

Note that here I want to know about the efficiency of the code

Well, then look at the code :) Source for JsonReader

It does pretty much what you would expect. It's using the provided InputStreamReader and only reading what it needs to fulfill an operation (in your case, getting the first object from the JSON array).

However ... when you call endArray() ... it's going to read from the stream until it finds the closing ] of that array. You don't actually care about that, and certainly don't want to spend the time reading all that data from the wire. Just call close() .

Since you're closing the JsonReader (and thus the underlying stream) ... that's about as good as you're going to get. You only read the data you wanted from the underlying stream then closed it.

Edit from comments: You can make your cases nice and tidy by doing:

public Message getFirstMessageFromArray(JsonReader reader) {
    reader.beginArray();
    return getMessageFromJson(reader);
}

public Message getMessageFromJson(JsonReader reader) {
    return new gson().fromJson(reader, Message.class);
}

And when you wanted to use it:

JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
Message message = getFirstMessageFromArray(reader);
reader.close();

or

JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
Message message = getMessageFromJson(reader);
reader.close();

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