最近写了一个简单的定制解析。
fastjson 解析 Map key value时有bug.
public static class KVPair {
private K key;
private V value;
public KVPair(){}
public KVPair(K key, V value){
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public void setKey(K key) {
this.key = key;
}
public V getValue() {
return value;
}
public void setValue(V value) {
this.value = value;
}
}
public static void main(String[] args) {
KVPair kv = new KVPair("aaa", "bbb");
System.out.println(JSON.toJSONString(kv));
}
输出结果为:
{"key":"aaa","value":"bbb"}
改动后的 setValue(V value) 方法为:
public V setValue(V value) {
this.value = value;
return this.value;
}
输出结果为:
{"aaa":"bbb"}
输出结果:
{"key":"aaa","value":"bbb"}
{"aaa":"bbb"}
这样占用的资源更少,并且也很清楚的表达了意思。这怎么写?fastjson提供的specialConfig 来提供特殊的序列化配置。
首先我们先对这个class创建一个特殊的序列化方法:
public static final SerializeConfig JSON_WRITE_CONFIG = new SerializeConfig();
static {
JSON_WRITE_CONFIG.put(KVPair.class, new KVPairSerailzer());
}
public class KVPairSerailzer implements ObjectSerializer{
@SuppressWarnings("rawtypes")
@Override
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType) throws IOException {
SerializeWriter out = serializer.getWriter();
if (object ==null) {
return ;
}
KVPair pair = (KVPair)object;
out.write("{");
write(out,pair.getKey());
out.write(":");
write(out,pair.getValue());
out.write("}");
}
public void write(SerializeWriter out, Object value) {
if (value == null) {
return;
} else if (value instanceof Integer) {
out.writeInt((Integer)value);
} else if (value instanceof Long) {
out.writeLong((Long)value);
} else if (value instanceof String) {
out.write("\"");
out.write((String)value);
out.write("\"");
} else if (value instanceof Double) {
out.write(Double.toString((Double)value));
} else if (value instanceof Float) {
out.write(Float.toString((Float)value));
} else {
throw new RuntimeException("not support value:"+value);
}
}
}
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType)
另外 1.1.46 之前的版本如果不希望将某些field不放在序列化后的json中,需要加入一个 实现了PropertyPreFilter的类才行。例如下面这个类:
public class FieldJsonIgnoreFilter implements PropertyPreFilter {
private Set excludes;
@Override
public boolean apply(JSONSerializer serializer, Object object, String name) {
if(object instanceof ComputerCluster) {
return !excludes.contains(name);
}
return true;
}
public FieldJsonIgnoreFilter() {
this.excludes = Sets.newHashSet();
}
public void add(String excludeFieldName) {
excludes.add(excludeFieldName);
}
public static final FieldJsonIgnoreFilter FIELD_JSON_IGNORE_FILTER = new FieldJsonIgnoreFilter();
static {
FIELD_JSON_IGNORE_FILTER.add("aaa"); // 如果fieldName 为 aaa 则不进行序列化。
FIELD_JSON_IGNORE_FILTER.add("bbb");
FIELD_JSON_IGNORE_FILTER.add("ccc");
}
}
@JSONField(serialize=false)
private String aaa;