1. 程式人生 > >FastJSON個性化序列化

FastJSON個性化序列化

jsonfield fastjson serializefilter valuefilter beforefilter

FastJSON個性化序列化



public class JstJobGoods implements Serializable {
    @JSONField(serialize = false)
    private Long id;          //ID
    @JSONField(name = "shop_id")
    private String shopId;          //店鋪編號
    @JSONField(name = "i_id")
    private Long iId;          //商品款號,商品ID
    @JSONField(name = "shop_i_id")
    private String shopIId;          //外部款號
    @JSONField(name = "name")
    private String name;          //名稱
    @JSONField(name = "sale_price")
    private Long salePrice;          //銷售價格
    @JSONField(name = "enabled")
    private Integer enabled;          //是否啟用
    @JSONField(name = "brand_name")
    private String brandName;          //品牌名稱
    @JSONField(name = "market_price")
    private Long marketPrice;          //市場價格
    @JSONField(serialize = false)
    private int realSkuQt = 0;          //真實SKU數量
    @JSONField(serialize = false)
    private String digit;          //數據MD5(不含id和uptime計算所得)
    @JSONField(serialize = false)
    private java.util.Date uptime;          //更新時間

    @JSONField(name = "skus")
    private List<JstJobGoodsSku> goodsSkuList;

    @JSONField(serialize = false)
    private Opt opt = Opt.DO_NOTHING;

    private static Pattern pnv = Pattern.compile("(.+):(.+)");
    public static SerializeFilter[] serializeFilters = new SerializeFilter[]{
            new ValueFilter() {
                @Override
                public Object process(Object object, String name, Object value) {
                    if (object instanceof JstJobGoods) {
                        JstJobGoods goods = (JstJobGoods) object;
                        if (name.equals("sale_price"))
                            return numberFormat2((long) value / 100);
                        if (name.equals("market_price"))
                            return numberFormat2((long) value / 100);
                    } else if (object instanceof JstJobGoodsSku) {
                        JstJobGoodsSku sku = (JstJobGoodsSku) object;
                        if (name.equals("sale_price"))
                            return numberFormat2((long) value / 100);
                        if (name.equals("market_price"))
                            return numberFormat2((long) value / 100);
                    }
                    return value;
                }
            },
            new BeforeFilter() {
                @Override
                public void writeBefore(Object object) {
                    //尺碼:22,顏色:黑色
                    if (object instanceof JstJobGoods) {
                        JstJobGoods goods = (JstJobGoods) object;
                        goods.setDigit(goods.getDigit());
                    } else if (object instanceof JstJobGoodsSku) {
                        JstJobGoodsSku sku = (JstJobGoodsSku) object;
                        sku.setDigit(sku.getDigit());
                        String properties = sku.getProperties();
                        if (properties == null || properties.trim().length() == 0) return;
                        String[] nvs = properties.split(",");
                        StringBuffer propertiesNames = new StringBuffer();
                        StringBuffer propertiesValues = new StringBuffer();
                        for (String nv : nvs) {
                            Matcher m = pnv.matcher(nv);
                            if (m.find()) {
                                propertiesNames.append(m.group(1).trim()).append(',');
                                propertiesValues.append(m.group(2).trim()).append(',');
                            }
                        }
                        wipeEndSeparator(propertiesNames, ',');
                        wipeEndSeparator(propertiesValues, ',');
                        sku.setPropertiesName(propertiesNames.toString());
                        sku.setPropertiesValue(propertiesValues.toString());
                    }
                }

                private void wipeEndSeparator(StringBuffer sb, char separator) {
                    if (sb.length() > 0 && sb.charAt(sb.length() - 1) == separator)
                        sb.deleteCharAt(sb.length() - 1);
                }
            }
    };
    
    
    //getter and setter...
public static Double numberFormat2(double value) {
    DecimalFormat df = new DecimalFormat("0.00");
    df.setRoundingMode(RoundingMode.DOWN);
    return Double.parseDouble(df.format(value));
}


String req = JSON.toJSONString(needSynGoodsList, JstJobGoods.serializeFilters, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
[
	{
		"brand_name":"",
		"enabled":1,
		"i_id":1174,
		"market_price":188.0,
		"name":"皮豆豆6620真皮戰鬥短靴大棉",
		"sale_price":158.0,
		"shop_i_id":"1174_001",
		"shop_id":"10039844",
		"skus":[
			{
				"brand_name":"",
				"color":"",
				"enabled":1,
				"market_price":188.0,
				"name":"皮豆豆6620真皮戰鬥短靴大棉",
				"pic":"",
				"pic_big":"",
				"properties_name":"尺碼,顏色",
				"properties_value":"21,紅色",
				"sale_price":158.0,
				"shop_sku_id":"v_1572_001",
				"sku_id":"r_1572"
			},
			{
				"brand_name":"",
				"color":"",
				"enabled":1,
				"market_price":188.0,
				"name":"皮豆豆6620真皮戰鬥短靴大棉",
				"pic":"",
				"pic_big":"",
				"properties_name":"尺碼,顏色",
				"properties_value":"21,黑色",
				"sale_price":158.0,
				"shop_sku_id":"v_1573_001",
				"sku_id":"r_1573"
			}
		]
	}
]


{"code":0,"issuccess":true,"msg":null}


再給個例子:

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.serializer.AfterFilter;
import com.alibaba.fastjson.serializer.BeforeFilter;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.alibaba.fastjson.serializer.ValueFilter;

import java.util.ArrayList;
import java.util.List;


public class FastJSONTest {
    public static void main(String[] args) {
        Foo f0 = new Foo("asan", 1100,24);
        System.out.println("原始的Foo:\n"+f0);
        String json1 = JSON.toJSONString(f0, new ValueFilter() {
            @Override
            public Object process(Object object, String name, Object value) {
                switch (name){
                    case "_val": return (Integer) value / 10;
                    case "age": return (Integer) value +1;
                    default: return value;
                }
            }
        });
        System.out.println("第1次序列化後的Foo:\n"+f0);
        System.out.println(">>>JSON1"+json1);


        List  list = new ArrayList();
        list.add(f0);
        String json2 = JSON.toJSONString(f0,new SerializeFilter[]{
                new BeforeFilter() {
                    @Override
                    public void writeBefore(Object object) {
                        if(!(object instanceof Foo))return;
                        Foo f = (Foo)object;
                        f.setName(f.getName()+"++");
                        f.setAge(f.getAge()+100);
                    }
                },
                new AfterFilter() {
                    @Override
                    public void writeAfter(Object object) {
//                        if(!(object instanceof Foo))return;
//                        Foo f = (Foo)object;
//                        f.setName(f.getName().substring(0,f.getName().length()-2));
//                        f.setAge(f.getAge()-100);
                    }
                }
        });
        System.out.println("第2次序列化後的Foo:\n"+f0);

        System.out.println(">>>JSON2"+json2);
    }

}

class Foo {
    private String name;
    @JSONField(name = "_val",serialize = true)
    private int val;
    private int age;

    public Foo(String name, int val, int age) {
        this.name = name;
        this.val = val;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getVal() {
        return val;
    }

    public void setVal(int val) {
        this.val = val;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Foo{" +
                "name='" + name + '\'' +
                ", val=" + val +
                ", age=" + age +
                '}';
    }
}
原始的Foo:
Foo{name='asan', val=1100, age=24}
第1次序列化後的Foo:
Foo{name='asan', val=1100, age=24}
>>>JSON1{"_val":110,"age":25,"name":"asan"}
第2次序列化後的Foo:
Foo{name='asan++', val=1100, age=124}
>>>JSON2{"_val":1100,"age":124,"name":"asan++"}

Process finished with exit code 0


https://www.w3cschool.cn/fastjson/fastjson-api.html


fastjson SerializerFeature詳解

http://blog.csdn.net/u010246789/article/details/52539576


FastJSON個性化序列化