fastjson

作者: 张明学 | 来源:发表于2020-07-18 11:45 被阅读0次

fastjson是阿里巴巴的开源JSON解析库,它可以解析JSON格式的字符串,支持将Java Bean序列化为JSON字符串,也可以从JSON字符串反序列化到JavaBean。fastjson地址

引用

<!-- fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
</dependency>

下面例子中所使用的对象:

@Data
public class EmployeeVo implements Serializable {
    private Long id;
    private String name;
    private Short sex;
    private Date birthday;
    private String telephone;
    private BigDecimal salary;
    private Boolean isOfficial;
    private String hobby;

    public String getAbc() {
        return "abc方法";
    }
}

默认序列化(JSON.toJSONString)

    @Test
    public void serializeTest() {
        EmployeeVo employeeVo = new EmployeeVo();
        employeeVo.setId(1000L)
                .setName("haha")
                .setBirthday(new Date())
                .setSalary(new BigDecimal("19865.32"))
                .setIsOfficial(true)
                .setSex(new Short("0"))
                .setTelephone("021-2546589");
        String jsonStr = JSON.toJSONString(employeeVo);
        log.info(jsonStr);
    }

结果:

{"abc":"abc方法","birthday":1595037120123,"id":1000,"isOfficial":true,"name":"haha","salary":19865.32,"sex":0,"telephone":"021-2546589"}

默认反序列化(JSON.parseObject)

    @Test
    public void deserializeTest() {
        String jsonStr = "{\"abc\":\"abc方法\",\"birthday\":1592872441001,\"id\":1000,\"isOfficial\":true,\"name\":\"haha\",\"salary\":19865.32,\"sex\":0,\"telephone\":\"021-2546589\"}";
        EmployeeVo employeeVo = JSON.parseObject(jsonStr, EmployeeVo.class);
        log.info(employeeVo.toString());
    }

结果:EmployeeVo(id=1000, name=haha, sex=0, birthday=Tue Jun 23 08:34:01 CST 2020, telephone=021-2546589, salary=19865.32, isOfficial=true, hobby=null)


序列化个性化设置(SerializerFeature)

API接口:(JSON.toJSONString)

public static String toJSONString(Object object, SerializerFeature... features) {
     return toJSONString(object, DEFAULT_GENERATE_FEATURE, features);
}

常用的SerializerFeature在jar包中com.alibaba.fastjson.serializer.SerializerFeature枚举中都有定义,常用的有如配置:

  • SerializerFeature.SortField 按字段名称排序后输出,默认为false不排序
  • SerializerFeature.PrettyFormat 结果是否格式化,默认为false不格式化
  • SerializerFeature.WriteDateUseDateFormat 全局修改日期格式,默认为false不使用全局日期格式
  • SerializerFeature.WriteMapNullValue 将空值属性输出为null,默认空值属性不输出
  • SerializerFeature.WriteNullStringAsEmpty 将空值属性输出为“”(空字符串),默认空值属性不输出

序列化过滤器设置(SerializeFilter)

SerializeFilter可以序列化前和后做一些定制,如PropertyFilter,PropertyPreFilter,BeforeFilter,AfterFilter,LabelFilter,NameFilter,ValueFilter

  • PropertyFilter 根据PropertyName和PropertyValue来判断是否序列化,接口定义如下:

    public class SamplePropertyFilter implements PropertyFilter {
    
        /**
         * 根据 属性的name与value判断是否进行序列化
         *
         * @param object
         * @param name
         * @param value
         * @return
         */
        @Override
        public boolean apply(Object object, String name, Object value) {
            if("telephone".equals(name)){
               return false;
            }
            return true;
        }
    
    }
    
  • AfterFilter 在序列化对象的所有属性之后执行某些操作

    public class SampleAfterFilter extends AfterFilter {
        @Override
        public void writeAfter(Object object) {
            log.info("writeAfter==" + object);
        }
    }
    

使用:

    @Test
    public void propertyFilterTest() {
        EmployeeVo employeeVo = new EmployeeVo();
        employeeVo.setId(1000L).setName("haha").setBirthday(new Date()).setSalary(new BigDecimal("19865.32")).setIsOfficial(true).setSex(new Short("0")).setTelephone("021-2546589");
        SamplePropertyFilter samplePropertyFilter = new SamplePropertyFilter();
        SampleAfterFilter sampleAfterFilter = new SampleAfterFilter();
        String jsonStr1 = JSON.toJSONString(employeeVo, new SerializeFilter[]{samplePropertyFilter, sampleAfterFilter});
        // {"abc":"abc方法","birthday":1592873561942,"id":1000,"isOfficial":true,"name":"haha","salary":19865.32,"sex":0,"telephone":"021-2546589"}
        log.info(jsonStr1);
    }

自定义序列化、反序列化及@JSONField和@JSONType

  • 自定义的序列化

    // 将性别0和1序列化成“男”和“女”
    public class SexSerializer implements ObjectSerializer {
    
        @Override
        public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
            Short value = (Short) object;
            String text;
            if (value != null && value == 0) {
                text = "男";
            } else {
                text = "女";
            }
            serializer.write(text);
        }
    }
    
  • 自定义的反序列化

    // 将性别“男”和“女”反序列化成0和1
    public class SexDeserialize implements ObjectDeserializer {
    
        @Override
        public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
            String sex = parser.parseObject(String.class);
            if ("男".equals(sex)) {
                return (T) new Short("0");
            } else {
                return (T) new Short("1");
            }
    
        }
    
        @Override
        public int getFastMatchToken() {
            return 0;
        }
    }
    

    使用:配合@JSONField定义的属性上表示对该class适用

    @JSONField(serializeUsing = SexSerializer.class, deserializeUsing = SexDeserialize.class)
    private Short sex;
    
  • @JSONField,标注在属性上,部分配置如下:

    @Retention(RetentionPolicy.RUNTIME)
    @Target({ ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER })
    public @interface JSONField {
        // 配置序列化和反序列化的顺序
        int ordinal() default 0;
        // 指定字段的名称
        String name() default "";
        // 指定字段的格式,对日期格式有用
        String format() default "";
          // 是否序列化
        boolean serialize() default true;
        // 是否反序列化
        boolean deserialize() default true;
        // 字段级别的SerializerFeature
        SerializerFeature[] serialzeFeatures() default {};
        
        Feature[] parseFeatures() default {};
        // 给属性打上标签, 相当于给属性进行了分组
        String label() default "";
        
        boolean jsonDirect() default false;
        // 自定义的序列化类
        Class<?> serializeUsing() default Void.class;
        // 自定义的反序列化类
        Class<?> deserializeUsing() default Void.class;
        
        String[] alternateNames() default {};
    
        boolean unwrapped() default false;
    }
    
  • @JSONType,标注在类上面

    @Retention(RetentionPolicy.RUNTIME)
    @Target({ ElementType.TYPE })
    public @interface JSONType {
    
        boolean asm() default true;
        // 输出json的字段顺序
        String[] orders() default {};
        // 包含的字段
        String[] includes() default {};
          // 不包含的字段
        String[] ignores() default {};
          // 类级别的序列化特性定义
        SerializerFeature[] serialzeFeatures() default {};
        Feature[] parseFeatures() default {};
        // 按字母顺序进行输出
        boolean alphabetic() default true;
        
        Class<?> mappingTo() default Void.class;    
        Class<?> builder() default Void.class;
        String typeName() default "";
        String typeKey() default "";
        Class<?>[] seeAlso() default{};
        // 序列化类
        Class<?> serializer() default Void.class;
        // 反序列化类
        Class<?> deserializer() default Void.class;
    
        boolean serializeEnumAsJavaBean() default false;
        PropertyNamingStrategy naming() default PropertyNamingStrategy.CamelCase;
        Class<? extends SerializeFilter>[] serialzeFilters() default {};
    }
    

泛型反序列化(TypeReference)

泛型反序列化是指反序列化结果的对象是一个泛型,如ResponseVO<BaseVo>

public class ResponseVO<T extends BaseVo> {
    private int resultCode;
    private BaseVo resultData;
}

public class EmployeeVo extends BaseVo {
    // ...
}

如果对:{"resultCode":100,"resultData":{"abc":"abc方法","birthday":1595040655594,"id":1000,"isOfficial":true,"name":"haha","salary":19865.32,"sex":0,"telephone":"021-2546589"}} JSON串反序列化成ResponseVO<EmployeeVo>对象则需要:

ResponseVO<EmployeeVo> response = JSON.parseObject(jsonString, new TypeReference<ResponseVO<EmployeeVo>>(){});

综合API及相关概念

最全的JSON.toJSONString()方法:

public static String toJSONString(Object object, // 对象
                                  SerializeConfig config, // 配置并记录每种Java类型对应的序列化类
                                  SerializeFilter[] filters, // 序列化过滤器
                                  String dateFormat, // 日期的格式化
                                  int defaultFeatures, // 默认的格式化设置
                                  SerializerFeature... features) {// 对于对输出的json做各种格式化设置
    // ...
}
public static <T> T parseObject(String input, //json串
                                Type clazz, //对象clazz
                                ParserConfig config, //保存各种ObjectDeserializer
                                ParseProcess processor,//定制反序列化,类似于SerializeFilter
                                int featureValues,
                                Feature... features) {//反序列化的特性
    // ...
}

相关文章

网友评论

      本文标题:fastjson

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