从对这个问题您的意见:
我有一个名为文档一个JSON数组。然后在这个数组中,我有多行,其中每行都有对象Action和Filenames(指向其他文件位置,这是html格式)。基本上我想要逐行阅读这个json文件,并单独处理这个动作和文件名。因为动作和文件名在每行中都不相同。
据我了解,你正在使用的格式是这样的:
{"Documents":[
{"Action":"action 1", "Filenames":["file 1a", "file 1b"]},
{"Action":"action 2", "Filenames":["file 2a", "file 2b"]},
// and so on for thousands more array entries
]}
而不是试图一次性加载整个顶层JSON对象,它会更有意义使用某种流媒体API并一次处理一个“行”。例如,使用Gson你可以做这样的事情与JsonReader
API:
InputStream is = new URL(url).openStream();
BufferedReader r = new BufferedReader(new InputStreamReader(
is, Charset.forName("UTF-8")));
JsonReader reader = new JsonReader(r);
JsonParser parser = new JsonParser();
reader.beginObject(); // the initial '{'
String name = reader.nextName();
assert "Documents".equals(name);
reader.beginArray(); // the opening '[' of the Documents array
while(reader.hasNext()) {
JsonObject doc = parser.parse(reader).getAsJsonObject();
String action = doc.get("Action").getAsString();
JsonArray filenames = doc.getAsJsonArray("Filenames");
// do something with the document here
// ...
}
reader.endArray(); // ending ']' of Documents
reader.endObject(); // final '}'
reader.close();
这样,你只能有一个时间保留在内存中一个“行”。
还有其他JSON库类似的API,尽管有些人比其他人更繁琐(例如与json.org JSONTokener
你必须处理:
和,
分离自己明确)。
你的代码有问题吗? – MxyL
你的代码有什么问题?该文件只是一个大的JSON对象? –
你在使用哪个JSON库?如果您知道您期望的JSON的一般格式,大多数图书馆都可以使用某种流API。 –