fastjson 使用NameFilter修改name字段后,用JSONField设置serializeUsing没有起作用

wmvff8tz  于 2021-11-27  发布在  Java
关注(0)|答案(5)|浏览(450)

我使用NameFilter把驼峰转成了下划线,然而当属性上设置JSONField的seserializeUsing时,没有起作用。当取消NameFilter时serializeUsing才有用。版本1.2.39

klsxnrf1

klsxnrf11#

问题没有重现,能否提供重现问题的testcase?

oymdgrw7

oymdgrw72#

测试程序:

public class ExampleExample {
    public static void main(String[] args) {
        Result result = new Result();
        result.setName("huang");
        result.setDate(new Date());
        result.setApplyOperation(ApplyOperation.CANCEL);
        SerializeFilter[] filters = new SerializeFilter[]{new FastJsonHumpToUnderline()};
        log.info(JSON.toJSONString(result, filters));
        log.info(JSON.toJSONString(result));
    }
    @Data
    static class Result {
        String name;
        String age;
        @JSONField(format = "yyyy-MM-dd HH:mm:ss")
        Date date;
        @JSONField( serializeUsing = IntEnumValueSerializer.class)
        ApplyOperation applyOperation;
    }
    @AllArgsConstructor
    enum ApplyOperation implements BaseIntEnum {
        DELETE(0, "删除"),
        PUSH(1,"确认提交"),
        CANCEL(2, "返回修改"),
        ;
        @Getter
        private final int value;
        @Getter
        private final String name;
    }
}

IntEnumValueSerializer类

public class IntEnumValueSerializer implements ObjectSerializer {

    @Override
    public void write(JSONSerializer jsonSerializer, Object o, Object o1, Type type, int i) throws IOException {
        if (o != null && o instanceof BaseIntEnum) {
            BaseIntEnum baseIntEnum = (BaseIntEnum) o;
            jsonSerializer.write(baseIntEnum.getName());
        }
    }
}

FastJsonHumpToUnderline类

public class FastJsonHumpToUnderline implements NameFilter {

    @Override
    public String process(Object o, String s, Object o1) {
        if (StringUtils.isEmpty(s)){
            return "";
        }
        StringBuilder stringBuilder = new StringBuilder();
        for(int i = 0; i < s.length() ; ++i){
            char c = s.charAt(i);
            if (Character.isUpperCase(c)){
                stringBuilder.append("_");
                stringBuilder.append(Character.toLowerCase(c));
            }else{
                stringBuilder.append(c);
            }
        }
        return stringBuilder.toString();
    }
}

输出结果

[ExampleExample.java:38] {"apply_operation":"CANCEL","date":1508081134608,"name":"huang"}
 [ExampleExample.java:39] {"applyOperation":"返回修改","date":"2017-10-15 23:25:34","name":"huang"}
vs3odd8k

vs3odd8k3#

有解决吗?1.2.62 还是有这个问题

xtupzzrd

xtupzzrd4#

遇到同样的问题,在使用NameFilter后,@JSONField失效了

8gsdolmq

8gsdolmq5#

@wenshao1.2.75 版本依然有问题,在使用NameFilter后,@JSONField 的 serializeUsing = ToStringSerializer.class 依然不起作用

相关问题