fastjson序列化时去掉null字段


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jiepu.rpc.thrift.server.entity.User;

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

/**
 * Created by Administrator on 2016/1/5.
 */
public class TestFastJson {

    public static void main(String[] args){


        List list=new ArrayList<>();
        for(int i=0;i<3;i++)
        {
            User entity=new User();
            entity.setId((long) i);
            entity.setPassword("");
            entity.setUsername("来自中文"+i);
            entity.setToken(UUID.randomUUID().toString());
            //list.add(entity);
            list.add(0,entity);
        }
        String json=JSON.toJSONString(list);
        System.out.println(json);
        /*
        QuoteFieldNames———-输出key时是否使用双引号,默认为true
        WriteMapNullValue——–是否输出值为null的字段,默认为false
        WriteNullNumberAsZero—-数值字段如果为null,输出为0,而非null
        WriteNullListAsEmpty—–List字段如果为null,输出为[],而非null
        WriteNullStringAsEmpty—字符类型字段如果为null,输出为”“,而非null
        WriteNullBooleanAsFalse–Boolean字段如果为null,输出为false,而非null
        */
        //使用双引号
        System.out.println(JSONObject.toJSONString(list, SerializerFeature.QuoteFieldNames));
        //输出值为null的字段
        System.out.println(JSONObject.toJSONString(list, SerializerFeature.WriteMapNullValue));
        System.out.println(JSONObject.toJSONString(list, SerializerFeature.WriteNullNumberAsZero));
        System.out.println(JSONObject.toJSONString(new ArrayList<>(), SerializerFeature.WriteNullListAsEmpty));
        System.out.println(JSONObject.toJSONString(list, SerializerFeature.WriteNullStringAsEmpty));
        System.out.println(JSONObject.toJSONString(list, SerializerFeature.SortField));
    }
}

import com.alibaba.fastjson.annotation.JSONField;


public class User {

    private Long id;
    @JSONField(serialize = false)
    private String username;
    private String password;
    /**动态授权令牌*/
    private String token;
    /**过期时间 */
    private String expired;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public String getExpired() {
        return expired;
    }

    public void setExpired(String expired) {
        this.expired = expired;
    }
}


你可能感兴趣的:(java)