【发布时间】:2019-02-21 23:46:49
【问题描述】:
我有一个包含大约 80000 行的大型 JSON 文件 (2.5MB)。
看起来像这样:
{
"a": 123,
"b": 0.26,
"c": [HUGE irrelevant object],
"d": 32
}
我只想要为键 a、b 和 d 存储整数值并忽略 JSON 的其余部分(即忽略 c 值中的任何内容)。
我无法修改原始 JSON,因为它是由我从其服务器下载的第 3 方服务创建的。
如何在不将整个文件加载到内存的情况下执行此操作?
我尝试使用 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);
有什么方法可以避免加载整个文件而只获取我需要的相关值?
【问题讨论】:
-
我觉得您将不得不下载整个文件并将其转换为字符串,但如果您没有关联的对象,您至少不会有任何不必要的对象。也许如果数据是静态的,你可以在两者之间做一个层,一个小的服务器来获取数据,修改它,然后你可以从那里获取。
-
2.5MB 不算大。
-
with jackson:将字段排除在外并使用@JsonIgnoreProperties(ignoreUnknown = true)进行注释