fastjson其他常用方法

来源:互联网 发布:laradock访问mysql 编辑:程序博客网 时间:2024/05/17 03:27

(1)@JSONField

     我们使用fastjson进行序列化的时候,默认情况下,都是使用属性的名称作为json中的key名称

     但是有时候我们需要序列化为其他的名称,@JSONField注解就是这个作用

    

import java.util.Date;import com.alibaba.fastjson.annotation.JSONField;public class Product {@JSONField(name = "productId")private long id;private String name;private double price;private Date gmtCreate;private Date gmtModifieDate;        ....省略getter\setter}
        序列化操作

@Testpublic void test() {Product product = new Product();product.setId(1L);product.setName("testJson");product.setPrice(1.23);product.setGmtCreate(new Date());product.setGmtModifieDate(new Date());String jsonString = JSON.toJSONString(product);System.out.println(jsonString);}

            结果为:

{"gmtCreate":1446184823686,"gmtModifieDate":1446184823686,"name":"testJson","price":1.23,"productId":1}

(2)指定需要序列化的属性

     有时候我们可能不需要将所有的属性进行序列化,这个时候就需要

public static void main(String[] args) {Product product = new Product();product.setId(1L);product.setName("testJson");product.setPrice(1.23);product.setGmtCreate(new Date());product.setGmtModifieDate(new Date());SimplePropertyPreFilter filter = new SimplePropertyPreFilter(Product.class, "productId","name");String result = JSON.toJSONString(product, filter);System.out.println(result);}
       结果为:

{"name":"testJson","productId":1}
            注意:使用了@JSONField注解!!







0 0
原创粉丝点击