FastJSON个性化序列化-创新互联

FastJSON个性化序列化

10年积累的成都网站建设、网站建设经验,可以快速应对客户对网站的新想法和需求。提供各种问题对应的解决方案。让选择我们的客户得到更好、更有力的网络服务。我虽然不认识你,你也不认识我。但先制作网站后付款的网站建设流程,更有平顺免费网站建设让你可以放心的选择与我们合作。
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 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

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


网站栏目:FastJSON个性化序列化-创新互联
标题来源:http://bzwzjz.com/article/esddd.html

其他资讯

Copyright © 2007-2020 广东宝晨空调科技有限公司 All Rights Reserved 粤ICP备2022107769号
友情链接: 专业网站设计 成都定制网站建设 高端网站设计 四川成都网站设计 做网站设计 成都做网站建设公司 企业网站设计 企业网站建设 成都品牌网站建设 网站建设公司 成都网站建设 定制级高端网站建设 手机网站制作 成都网站设计 成都网站建设 成都企业网站建设公司 重庆手机网站建设 网站建设费用 成都网站设计制作公司 成都网站设计 成都网站建设流程 阿坝网站设计