fastjson序列化空属性、指定字段名,SerializerFeature.WriteMapNullValue 、 @JSONField

package com.company;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.serializer.SerializerFeature;

/**
 * @Author
 * @Date 2020/4/22 11:16
 * @Version 1.0
 * @Desc
 */
public class Main7 {

    class User {
        String name;
        String addr;

        public User(String name, String addr) {
            this.name = name;
            this.addr = addr;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getAddr() {
            return addr;
        }

        public void setAddr(String addr) {
            this.addr = addr;
        }
    }


    class UserB {

        @JSONField(name = "first_name")
        String firstName;

        @JSONField(name = "addr_city")
        String addrCity;

        public UserB(String firstName, String addrCity) {
            this.firstName = firstName;
            this.addrCity = addrCity;
        }

        public String getFirstName() {
            return firstName;
        }

        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }

        public String getAddrCity() {
            return addrCity;
        }

        public void setAddrCity(String addrCity) {
            this.addrCity = addrCity;
        }
    }

    public void f1() {
        User user = new User("zhangsan", null);
        System.out.println(JSONObject.toJSONString(user));//{"name":"zhangsan"}
        System.out.println(JSONObject.toJSONString(user, SerializerFeature.WriteMapNullValue));//{"addr":null,"name":"zhangsan"}

        User user1 = new User("zhangsan1", "");
        System.out.println(JSONObject.toJSONString(user1));//{"addr":"","name":"zhangsan1"}


        UserB userB = new UserB("lisi", "西安");
        System.out.println(JSONObject.toJSONString(userB));//{"addrCity":"西安","firstName":"lisi"}

        //只在set方法上用@JSONField(name = "addr_city")无效,输出{"addrCity":"西安","firstName":"lisi"}
        //只在get方法上用@JSONField(name = "addr_city")有效,{"addr_city":"西安","first_name":"lisi"}
        //只在属性名上用@JSONField(name = "addr_city")有效果 ,输出{"addr_city":"西安","first_name":"lisi"}


        UserB userB2 = new UserB("lisi", "");
        System.out.println(JSONObject.toJSONString(userB2));//{"addr_city":"","first_name":"lisi"}


    }

    public static void main(String[] args) {
        Main7 aClass = new Main7();
        aClass.f1();
    }
}

 

你可能感兴趣的:(Java)