背景
最近工作有一个需求,需要读取一个约2GB的json文件(存储了约3千万个json对象的集合),解析其中的每个json对象,并进行一些数据转换,最后把转换后的json对象存储到es中。json文件格式大概是这样的:
[
{
lng: 116.22
lat: 22.00,
count: xxxx
},
{
lng: 116.22
lat: 22.00,
count: xxxx
},
...
]
一次性将这个json文件加载到内存中进行json解析肯定是不行的,因此,我想到的是利用fastjson中的JSONReader流式读取文件逐步解析,快速看了一下JSONReader的API及demo,便开始coding,很快便写出了如下简化版的代码,fastjson 版本 1.2.70
private final static int BATCH_SIZE = 20000;
public int importDataToEs(String jsonPath) {
int count = 0;
List<JSONObject> items = new ArrayList<>(BATCH_SIZE);
try (Reader fileReader = new FileReader(jsonPath)) {
JSONReader jsonReader = new JSONReader(fileReader);
jsonReader.startArray();
while (jsonReader.hasNext()) {
JSONObject object = (JSONObject) jsonReader.readObject();
JSONObject item = processObject