Fastjson 简介


Fastjson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Fastjson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.

入口类:

package com.alibaba.fastjson;
public abstract class JSON {
      public static final String toJSONString(Object object);
      public static final <T> T parseObject(String text, Class<T> clazz, Feature... features);
}

序列化:

String jsonString = JSON.toJSONString(obj);

反序列化:

VO vo = JSON.parseObject("...", VO.class);

泛型反序列化:

import com.alibaba.fastjson.TypeReference;

List<VO> list = JSON.parseObject("...", new TypeReference<List<VO>>() {});

TypeReference可以正确反序列化嵌套多层的List或Map,比如List<Map<String,String>>这种类型的序列化对象。

fastjson 处理日期:

JSON.toJSONStringWithDateFormat(date, "yyyy-MM-dd HH:mm:ss.SSS")

使用ISO-8601日期格式

JSON.toJSONString(obj, SerializerFeature.UseISO8601DateFormat);

全局修改日期格式

JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd";
JSON.toJSONString(obj, SerializerFeature.WriteDateUseDateFormat);

反序列化能够自动识别如下日期格式:

  • ISO-8601日期格式
  • yyyy-MM-dd
  • yyyy-MM-dd HH:mm:ss
  • yyyy-MM-dd HH:mm:ss.SSS
  • 毫秒数字
  • 毫秒数字字符串
  • .NET JSON日期格式
  • new Date(198293238)

可以使用SimplePrePropertyFilter过滤字段

String toJSONString(Object, SerializeFilter, SerializerFeature...);

VO vo = new VO();
vo.setId(123);
vo.setName("flym");
      
SimplePropertyPreFilter filter = new SimplePropertyPreFilter(VO.class, "name");
Assert.assertEquals("{\"name\":\"flym\"}", JSON.toJSONString(vo, filter));

当需要处理超大JSON文本时,需要Stream API,在fastjson-1.1.32版本中开始提供Stream API。
如果你的JSON格式是一个巨大的JSON数组,有很多元素,则先调用startArray,然后挨个写入对象,然后调用endArray。

JSONWriter writer = new JSONWriter(new FileWriter("/tmp/huge.json"));
writer.startArray();
for (int i = 0; i < 1000 * 1000; ++i) {
    writer.writeValue(new VO());
}
writer.endArray();
writer.close();
  
JSONReader reader = new JSONReader(new FileReader("/tmp/huge.json"));
reader.startArray();
while(reader.hasNext()) {
    VO vo = reader.readObject(VO.class);
    // handle vo ...
}
reader.endArray();
reader.close();

如果你的JSON格式是一个巨大的JSONObject,有很多Key/Value对,则先调用startObject,然后挨个写入Key和Value,然后调用endObject。

JSONWriter writer = new JSONWriter(new FileWriter("/tmp/huge.json"));
writer.startObject();
for (int i = 0; i < 1000 * 1000; ++i) {
    writer.writeKey("x" + i);
    writer.writeValue(new VO());
}
writer.endObject();
writer.close();

JSONReader reader = new JSONReader(new FileReader("/tmp/huge.json"));
reader.startObject();
while(reader.hasNext()) {
    String key = reader.readString();
    VO vo = reader.readObject(VO.class);
    // handle vo ...
}
reader.endObject();
reader.close();

本文由个人 hexo 博客 co2fe.com 迁移
date: 2017-09-18 17:09:18

猜你喜欢

转载自www.cnblogs.com/manastudent/p/10190885.html