FastJson学习笔记

1.测试实体类

/**
 * 
 * @Description: 测试
 * @date 2017年7月12日 下午6:04:09
 * @version V1.0
 */
public class Person {
    /**
     * 姓名
     */
    private String name;
    /**
     * 年龄
     */
    private Integer age;
    /**
     * 地址
     */
    private String address;
    /**
     * 电话
     */
    private String tellphone;
    
    
    public Person(){}
    /**
     * @param name
     * @param age
     */
    public Person(String name, Integer age) {
        super();
        this.name = name;
        this.age = age;
    }
    public Person(String name, Integer age, String address, String tellphone) {
        this.name = name;
        this.age = age;
        this.address = address;
        this.tellphone = tellphone;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name
     *            the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the age
     */
    public Integer getAge() {
        return age;
    }

    /**
     * @param age
     *            the age to set
     */
    public void setAge(Integer age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getTellphone() {
        return tellphone;
    }

    public void setTellphone(String tellphone) {
        this.tellphone = tellphone;
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]";
    }
}

2.FastJson常用API

/**
 * com.alibaba.fastjson.JSON;
 * This is the main class for using Fastjson
 * You usually call these two methods toJSONString(Object) and parseObject(String, Class).
 */
public class FastJsonTest {


    /**
     * deserializes json into  model
     */
    public void jsonToModel(){
        StringBuilder jsonBuilder = new StringBuilder(128);
        jsonBuilder.append("{\"name\":\"xiaoming\",\"age\":\"25\"}");
        Person person = JSON.parseObject(jsonBuilder.toString(),Person.class);
        System.out.println(person);
        // Person [name=xiaoming, age=25]
    }

    /**
     *  the object that your are serializing/deserializing is a ParameterizedType
     *  then you must use the  parseObject(String, Type, Feature[]) method
     */
    public void jsonToList(){
        StringBuilder jsonBuilder = new StringBuilder(128);
        jsonBuilder.append("[");
        jsonBuilder.append("{\"name\":\"Tom\",\"age\":\"23\"},");
        jsonBuilder.append("{\"name\":\"Cat\",\"age\":\"21\"}");
        jsonBuilder.append("]");
        Type type = new TypeReference<List<Person>>() {}.getType();
        // This method deserializes the specified Json into an object of the specified type.
        // This method is useful if the specified object is a generic type(泛型)
        // For non-generic objects, use parseObject(String, Class, Feature[]) instead
        List<Person> list = JSON.parseObject(jsonBuilder.toString(), type);
        for(Person p : list){
            System.out.println(p);
        }
      //  Person [name=Tom, age=23]
       // Person [name=Cat, age=21]
    }

    public void jsonToMap(){
        StringBuilder jsonBuilder = new StringBuilder(128);
        jsonBuilder.append("{\"name\":\"xiaoming\",\"age\":\"25\"}");
        Type type = new TypeReference<Map<String, Object>>() {}.getType();
        Map  map = JSON.parseObject(jsonBuilder.toString(), type);
        System.out.println(map);
        //{name=xiaoming, age=25}
    }

    /**
     * serializes model to Json
     */
    public void  modelToJson(){
        String json = JSON.toJSONString(new Person("tocmat",22));
        System.out.println(json);
        // {"age":22,"name":"tocmat"}
         //格式化
        System.out.println(JSON.toJSONString(new Person("测试",25),true));
        /**
         * {
         "age":25,
         "name":"测试"
         }
         */
    }

    /**
     * 集合转json字符串
     */
    public void listToJson(){
        Person one = new Person("Tom",21);
        Person two = new Person("Cat",25);
        List<Person> list = new ArrayList<>();
        list.add(one);
        list.add(two);
        String json = JSON.toJSONString(list,true);
        System.out.println(json);
        /**
          [
            {
         "age":21,
         "name":"Tom"
         },
         {
         "age":25,
         "name":"Cat"
         }
         ]
         */
    }

    /**
     * 自定义反序列化
     */
   public void customerJsonToObject(){
     //  Feature.AllowSingleQuotes  允许单引号  默认已使用
       //  Feature.AllowUnQuotedFieldNames  允许没有引号的key 默认已使用
       // ....
       StringBuilder jsonBuilder = new StringBuilder(128);
       jsonBuilder.append("{\"name\":\'xiaoming\',age:\"25\"}");
       Person person = JSON.parseObject(jsonBuilder.toString(), Person.class, Feature.AllowSingleQuotes);
       System.out.println(person);
       //Person [name=xiaoming, age=25]
   }

    /**
     * 自定义序列化
     * 在fastjson中,缺省是不输出空值的。无论Map中的null和对象属性中的null,序列化的时候都会被忽略不输出,这样会减少产生文本的大小
     */
   public void customerObjectToJson(){
       // SerializerFeature.QuoteFieldNames 用引号包裹key 默认已使用
       // SerializerFeature.SortField 排序输出字段  默认已使用
      //  SerializerFeature.PrettyFormat  格式化
      //  SerializerFeature.UseSingleQuotes  key和字符串值  使用单引号
       // .....

       String json = JSON.toJSONString(new Person("tomcat",22), SerializerFeature.PrettyFormat,SerializerFeature.UseSingleQuotes);
       System.out.println(json);
       /**
        {
        'age':22,
        'name':'tomcat'
        }
        */
       //忽略的字段和包含字段
       SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
       filter.getExcludes().add("name"); //忽略name字段
       filter.getExcludes().add("age"); // 忽略age字段
       Person person = new Person("张三",25,"某某地址","1534587787");
       String personjson = JSON.toJSONString(person, filter);
       System.out.println(personjson);
       // {"address":"某某地址","tellphone":"1534587787"}

       filter = new SimplePropertyPreFilter();
       filter.getIncludes().add("address"); //包含address字段
       filter.getIncludes().add("age");  //包含age字段
       System.out.println(JSON.toJSONString(person,filter));
       // {"address":"某某地址","age":25}
   }



    public static void main(String[] args){
        FastJsonTest  test = new FastJsonTest();
        test.customerObjectToJson();

    }



}

3.com.alibaba.fastjson.annotation.JSONField

package com.alibaba.fastjson.annotation;

public @interface JSONField {
    // 配置序列化和反序列化的顺序,1.1.42版本之后才支持
    int ordinal() default 0;

     // 指定字段的名称
    String name() default "";

    // 指定字段的格式,对日期格式有用
    String format() default "";

    // 是否序列化
    boolean serialize() default true;

    // 是否反序列化
    boolean deserialize() default true;
}

例如

public class Person {
	@JSONField(name="NAME")
	private String name;
	@JSONField(serialize=false)
	private int age;
	@JSONField(name="ORG_CODE")
	private String orgCode;
	// 配置date序列化和反序列使用yyyyMMdd日期格式
    @JSONField(format="yyyyMMdd")
    public Date date;
    ......
Person person = new Person("tom", 22,"350001");
String result = JSON.toJSONString(person);
System.out.println(result);

输出为
{“NAME”:“tom”,“ORG_CODE”:“350001”}

[1]fastjson官方地址

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值