您的位置:首页 > 编程语言 > Java开发

java中,通过FastJson对海量数据的Json文件,边读取边解析

2015-02-10 09:44 1276 查看
当读取json文件的时候,如果json文件巨大,比如json文件中有900万条数据,大小有300多M,就不可以一次把数据都读到内存再解析。

第一内存受不了,第二CPU更受不了,所有的硬件和软件都受不了。

需要一种边读取,边解析的json操作类,FastJson可以实现这个功能,实测这个速度还真是比较快。

fastjson的下载地址:http://repo1.maven.org/maven2/com/alibaba/fastjson/

建议下载最新版本的fastjson

比如有下边一段json:

{
"array": [
1,
2,
3
],
"arraylist": [
{
"a": "b",
"c": "d",
"e": "f"
},
{
"a": "b",
"c": "d",
"e": "f"
},
{
"a": "b",
"c": "d",
"e": "f"
}
],
"object": {
"a": "b",
"c": "d",
"e": "f"
},
"string": "Hello World"
}
如果我们不一次性将其读到内存中进行解析,就要使用FastJson的JSONReader类,解析代码如下:

/**
* FastJson逐行解析json
* @author drlyee
* @date 2015-02-10
*/
public void ReadWithFastJson()
{
String jsonString = "{\"array\":[1,2,3],\"arraylist\":[{\"a\":\"b\",\"c\":\"d\",\"e\":\"f\"},{\"a\":\"b\",\"c\":\"d\",\"e\":\"f\"},{\"a\":\"b\",\"c\":\"d\",\"e\":\"f\"}],\"object\":{\"a\":\"b\",\"c\":\"d\",\"e\":\"f\"},\"string\":\"HelloWorld\"}";

// 如果json数据以形式保存在文件中,用FileReader进行流读取!!
// path为json数据文件路径!!
// JSONReader reader = new JSONReader(new FileReader(path));

// 为了直观,方便运行,就用StringReader做示例!
JSONReader reader = new JSONReader(new StringReader(jsonString));
reader.startObject();
System.out.print("start fastjson");
while (reader.hasNext())
{
String key = reader.readString();
System.out.print("key " + key);
if (key.equals("array"))
{
reader.startArray();
System.out.print("start " + key);
while (reader.hasNext())
{
String item = reader.readString();
System.out.print(item);
}
reader.endArray();
System.out.print("end " + key);
}
else if (key.equals("arraylist"))
{
reader.startArray();
System.out.print("start " + key);
while (reader.hasNext())
{
reader.startObject();
System.out.print("start arraylist item");
while (reader.hasNext())
{
String arrayListItemKey = reader.readString();
String arrayListItemValue = reader.readObject().toString();
System.out.print("key " + arrayListItemKey);
System.out.print("value " + arrayListItemValue);
}
reader.endObject();
System.out.print("end arraylist item");
}
reader.endArray();
System.out.print("end " + key);
}
else if (key.equals("object"))
{
reader.startObject();
System.out.print("start object item");
while (reader.hasNext())
{
String objectKey = reader.readString();
String objectValue = reader.readObject().toString();
System.out.print("key " + objectKey);
System.out.print("value " + objectValue);
}
reader.endObject();
System.out.print("end object item");
}
else if (key.equals("string"))
{
System.out.print("start string");
String value = reader.readObject().toString();
System.out.print("value " + value);
System.out.print("end string");
}
}
reader.endObject();
System.out.print("start fastjson");
}


通过JsonReader可以顺序读取。类似于剥橘子,一层一层解开json,不需要把json都读到内存中。

其中比较重要的几个方法为:

startArray(); 开始解析数组

endArray(); 结束解析数组

startObject(); 开始解析键值对

endObject(); 结束解析键值对

只要掌握了以上几个关键的方法,FastJson大数据读取导入就不难。

还有一些其他的json大数据读取导入技术,后续介绍。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: