美文网首页
FastJson-简单使用

FastJson-简单使用

作者: KeBook | 来源:发表于2018-12-27 19:07 被阅读0次
    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONArray;
    import com.alibaba.fastjson.JSONObject;
    import com.alibaba.fastjson.annotation.JSONField;
    import com.alibaba.fastjson.serializer.*;
    import org.junit.Before;
    import org.junit.Test;
    
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    
    import static junit.framework.TestCase.assertEquals;
    
    public class fastjson {
    
        private List<Person> listOfPersons = new ArrayList<Person>();
        private List<Person2> listOfPersons2 = new ArrayList<Person2>();
    
        @Before
        public void setUp() {
            listOfPersons.add(
                    new Person(15, "John Doe", new Date()));
            listOfPersons.add(
                    new Person(20, "Janette Doe", new Date()));
        }
    
        @Test
        public void whenJavaList_thanConvertToJsonCorrect() {
            String jsonOutput= JSON.toJSONString(listOfPersons);
            System.out.println(jsonOutput);
        }
    
        @Before
        public void setUp2() {
            listOfPersons2.add(
                    new Person2(15, "John", "Doe", new Date()));
            listOfPersons2.add(
                    new Person2(20, "Janette", "Doe", new Date()));
        }
    
        @Test
        public void whenJavaList_thanConvertToJsonCorrect2() {
            String jsonOutput= JSON.toJSONString(listOfPersons2);
            System.out.println(jsonOutput);
            String jsonOutput2= JSON.toJSONString(listOfPersons2,
                    SerializerFeature.BeanToArray);
            System.out.println(jsonOutput2);
        }
    

    创建JSON对象

        @Test
        public void whenGenerateJson_thanGenerationCorrect() {
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < 2; i++) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("AGE", 10);
                jsonObject.put("FULL NAME", "Doe " + i);
                jsonObject.put("DATE OF BIRTH", "2016/12/12 12:12:12");
                jsonArray.add(jsonObject);
            }
            String jsonOutput = jsonArray.toJSONString();
            System.out.println(jsonOutput);
        }
    

    JSON字符串转换为java对象
    ATTENTION: class need default constructor

        @Test
        public void whenJson_thanConvertToObjectCorrect() {
            Person2 person = new Person2(20, "John", "Doe", new Date());
            String jsonObject = JSON.toJSONString(person);
            System.out.println(jsonObject);
            Person2 newPerson = JSON.parseObject(jsonObject, Person2.class);
            System.out.println(newPerson);
    
            assertEquals(newPerson.getAge(), 0); // 如果我们设置序列化为 false
            assertEquals(newPerson.getLastName(),
                    listOfPersons2.get(0).getLastName());
        }
    

    使用 ContextValueFilter 配置 JSON 转换

        @Test
        public void givenContextFilter_whenJavaObject_thanJsonCorrect() {
            ContextValueFilter valueFilter = new ContextValueFilter () {
                public Object process(
                        BeanContext context, Object object, String name, Object value) {
                    if (name.equals("DATE OF BIRTH")) {
                        return "NOT TO DISCLOSE";
                    }
                    if (value.equals("John")) {
                        return ((String) value).toUpperCase();
                    } else {
                        //return null;//过滤其余
                        return value;//返回其余
                    }
                }
            };
            String jsonOutput = JSON.toJSONString(listOfPersons2, valueFilter);
            System.out.println(jsonOutput);
            String jsonOutput2 = JSON.toJSONString(listOfPersons2);
            System.out.println(jsonOutput2);
        }
    

    使用 NameFilter 和 SerializeConfig
    NameFilter: 序列化时修改 Key。
    SerializeConfig:内部是个map容器主要功能是配置并记录每种Java类型对应的序列化类。
    toJSONStringWithDateFormat()可以更快速的格式化日期

        @Test
        public void givenSerializeConfig_whenJavaObject_thanJsonCorrect() {
            NameFilter formatName = new NameFilter() {
                public String process(Object object, String name, Object value) {
                    return name.toLowerCase().replace(" ", "_");
                }
            };
    
            SerializeConfig.getGlobalInstance().addFilter(Person.class,  formatName);
            String jsonOutput =
                    JSON.toJSONStringWithDateFormat(listOfPersons, "yyyy-MM-dd");
            System.out.println(jsonOutput);
        }
    
    }
    

    Person.class

    /**
     * {"AGE":15,"DATE OF BIRTH":1545900124680,"FULL NAME":"John Doe"}
     */
    class Person {
    
        @JSONField(name = "AGE")
        private int age;
    
        @JSONField(name = "FULL NAME")
        private String fullName;
    
        @JSONField(name = "DATE OF BIRTH")
        private Date dateOfBirth;
    
         Person(int age, String fullName, Date dateOfBirth) {
            this.age = age;
            this.fullName= fullName;
            this.dateOfBirth = dateOfBirth;
        }
    
        public int getAge() {
            return age;
        }
    
        public String getFullName() {
            return fullName;
        }
    
        public Date getDateOfBirth() {
            return dateOfBirth;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        public void setFullName(String fullName) {
            this.fullName = fullName;
        }
    
        public void setDateOfBirth(Date dateOfBirth) {
            this.dateOfBirth = dateOfBirth;
        }
    }
    

    Person2.class
    format 参数用于格式化 date 属性。
    默认情况下, FastJson 库可以序列化 Java bean 实体, 但我们可以使用 serialize 指定字段不序列化。
    使用 ordinal 参数指定字段的顺序

    /**
     *  {"FIRST NAME":"Doe","LAST NAME":"John","DATE OF BIRTH":"27/12/2018"}
     */
    class Person2{
        @JSONField(name="AGE", serialize=false, deserialize = false)
        private int age;
    
        @JSONField(name="LAST NAME", ordinal = 2)
        private String lastName;
    
        @JSONField(name="FIRST NAME", ordinal = 1)
        private String firstName;
    
        @JSONField(name="DATE OF BIRTH", format="HH:mm:ss", ordinal = 3)
        private Date dateOfBirth;
    
    
        public Person2() {
        }
    
        Person2(int age, String lastName, String firstName, Date dateOfBirth) {
            this.age = age;
            this.lastName = lastName;
            this.firstName = firstName;
            this.dateOfBirth = dateOfBirth;
        }
    
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
    
        public String getLastName() {
            return lastName;
        }
    
        public void setLastName(String lastName) {
            this.lastName = lastName;
        }
    
        public String getFirstName() {
            return firstName;
        }
    
        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }
    
        public Date getDateOfBirth() {
            return dateOfBirth;
        }
    
        public void setDateOfBirth(Date dateOfBirth) {
            this.dateOfBirth = dateOfBirth;
        }
    
        @Override
        public String toString() {
            return "Person2{" +
                    "age=" + age +
                    ", lastName='" + lastName + '\'' +
                    ", firstName='" + firstName + '\'' +
                    ", dateOfBirth=" + dateOfBirth +
                    '}';
        }
    }
    

    dependencies

    <dependencies>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.2.54</version>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>RELEASE</version>
            </dependency>
        </dependencies>
    

    相关文章

      网友评论

          本文标题:FastJson-简单使用

          本文链接:https://www.haomeiwen.com/subject/lrudlqtx.html