我有一个很大的 JSON 文件 (2.5MB),包含大约 80000 行。
它看起来像这样:
{
"a": 123,
"b": 0.26,
"c": [HUGE irrelevant object],
"d": 32
}
我只想为键存储整数值a
, b
and d
并忽略 JSON 的其余部分(即忽略 JSON 中的任何内容)c
value).
我无法修改原始 JSON,因为它是由第三方服务创建的,我从其服务器下载该服务。
如何在不将整个文件加载到内存中的情况下执行此操作?
我尝试使用gson https://github.com/google/gson库并创建了这样的 bean:
public class MyJsonBean {
@SerializedName("a")
@Expose
public Integer a;
@SerializedName("b")
@Expose
public Double b;
@SerializedName("d")
@Expose
public Integer d;
}
但即便如此,为了使用 Gson 反序列化它,我需要先下载并读取内存中的整个文件,然后将其作为字符串传递给 Gson?
File myFile = new File(<FILENAME>);
myFile.createNewFile();
URL url = new URL(<URL>);
OutputStream out = new BufferedOutputStream(new FileOutputStream(myFile));
URLConnection conn = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) conn;
InputStream in = conn.getInputStream();
byte[] buffer = new byte[1024];
int numRead;
while ((numRead = in.read(buffer)) != -1) {
out.write(buffer, 0, numRead);
}
FileInputStream fis = new FileInputStream(myFile);
byte[] data = new byte[(int) myFile.length()];
fis.read(data);
String str = new String(data, "UTF-8");
Gson gson = new Gson();
MyJsonBean response = gson.fromJson(str, MyJsonBean.class);
System.out.println("a: " + response.a + "" + response.b + "" + response.d);
有什么方法可以避免加载整个文件并只获取我需要的相关值?