温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

FastJSON个性化序列化

发布时间:2020-07-21 11:32:07 来源:网络 阅读:8567 作者:leizhimin 栏目:软件技术

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


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI