over 7 years ago
比較一下之前用過Jackson跟最近在玩阿里巴巴的fastjson
fastjson
一般轉換用法
JSON.toJSONString(npc)
使用註解過濾
@JSONField(serialize=false)
private float positionX;
//轉換方式不變
JSON.toJSONString(npc);
動態過濾
String[] ary = {"name","positionX","positionY","job","age"};
SimplePropertyPreFilter filter = new SimplePropertyPreFilter(MaleNPC.class, ary);
JSON.toJSONString(npc, filter);
這樣就去除掉father 與 mother了
客製序列化
@JsonSerialize(using=JsonDateSerializer.class)
private Date published;
@Component
public class JsonDateSerializer extends JsonSerializer<Date>{
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
@Override
public void serialize(Date date, JsonGenerator gen, SerializerProvider provider)throws IOException, JsonProcessingException {
String formattedDate = dateFormat.format(date);
gen.writeString(formattedDate);
}
}
Jackson
一般轉換
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writeValueAsString(npc);
註解過濾,在方法上增加以下註解,轉出方式不變
@JsonIgnore
動態過濾
新增一隻程式過濾使用
import com.fasterxml.jackson.annotation.*;
@JsonFilter("QueryFilter")
public class QueryFilter {
public static String[] ignorableFieldNames = { "father", "mother" };
}
轉換要改成這樣
ObjectMapper mapper = new ObjectMapper();
mapper.addMixInAnnotations(Object.class, QueryFilter.class);
FilterProvider filters = new SimpleFilterProvider().addFilter("QueryFilter",SimpleBeanPropertyFilter.serializeAllExcept(QueryFilter.ignorableFieldNames));
ObjectWriter writer = mapper.writer(filters);
writer.writeValueAsString(npc);
客製序列化
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyyMMdd'T'HHmmss.SSS'Z'")
private Date published;