美文网首页
关于FastJSON 使用serializeUsing自定义序列

关于FastJSON 使用serializeUsing自定义序列

作者: Neil_Wong | 来源:发表于2021-09-03 17:16 被阅读0次

    在fastjson 1.2.16版本之后,JSONField支持新的定制化配置serializeUsing,可以单独对某个类的某个属性定制序列化、反序列化。

    1.序列化、反序列化接口支持

    • 序列化接口
    package com.alibaba.fastjson.serializer;
    
    import java.io.IOException;
    import java.lang.reflect.Type;
    
    public interface ObjectSerializer {
        void write(JSONSerializer var1, Object var2, Object var3, Type var4, int var5) throws IOException;
    }
    
    • 反序列化接口
    package com.alibaba.fastjson.parser.deserializer;
    
    import com.alibaba.fastjson.parser.DefaultJSONParser;
    import java.lang.reflect.Type;
    
    public interface ObjectDeserializer {
        <T> T deserialze(DefaultJSONParser var1, Type var2, Object var3);
    
        int getFastMatchToken();
    }
    

    2.自定义序列化

    @Data
    public class User {
    
        @JSONField(serializeUsing = ModelValueSerializer.class)
        public int age;
    
    }
    

    实现ObjectSerializer接口,重写write方法,自定义序列化。

    public class ModelValueSerializer implements ObjectSerializer {
        @Override
        public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
            Integer value = (Integer) object;
            String text = value + "岁";
            serializer.write(text);
        }
    }
    

    测试

        @Test
        void objectSerializerTest() {
            User model = new User();
            model.setAge(10);
            String s = JSON.toJSONString(model);
            System.out.println(s);
        }
    

    输出

    {"age":"10岁"}

    3.自定义反序列化

    @Data
    public class User {
    
        @JSONField(deserializeUsing = ModelValueDeserializer.class)
        private Date birthday;
    
    }
    

    实现ObjectDeserializer接口,重写deserialze方法,自定义反序列化

    public class ModelValueDeserializer implements ObjectDeserializer {
    
        @Override
        public Date deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
            JSONLexer lexer = parser.getLexer();
            String timestamp = lexer.stringVal();
            Long longObject = Long.valueOf(timestamp);
            Date date = new Date(longObject*1000);
            return date;
        }
    
        @Override
        public int getFastMatchToken() {
            return 0;
        }
    
    }
    

    测试

       @Test
        void objectDeserializerTest() {
            String json = "{\"birthday\":\"1630656260\"}";
            User t = JSON.parseObject(json, User.class);
            System.out.println(t);
        }
    

    输出

    User(birthday =Fri Sep 03 16:04:20 CST 2021)

    相关文章

      网友评论

          本文标题:关于FastJSON 使用serializeUsing自定义序列

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