[alibaba/fastjson]fastjson有没有类似于jackson的类级别的JsonNaming注解,实现下划线驼峰(json property)和大小写驼峰(java jean property)转换?

2025-11-11 284 views
9

fastjson有没有类似于jackson的JsonNaming注解? jackson用法:

@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public class Test{
    private String studentName;
}

可以在类级别实现下划线驼峰(json property)和大小写驼峰转换(java jean property)? eg: java property:studentName <---> json property: student_name PropertyNamingStrategy.SnakeCase目前看只有全局config可以设定,并没有类级别的注解。

回答

4

目前看不满足,我想要一个注解,实现字段名转换的定制方便。

类名设置了转换策略: 1、如果属性名定制了要转换的名字,按照属性名为准 2、其他未定制名字的属性,将按照类上的注解转换策略为准。 贴一下jackson的使用方式测试代码:

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
public class Test {
    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        Student student = new Student();
        student.setStudentName("hahah");
        student.setStudentAddress("123");
        String json = mapper.writeValueAsString(student);
        System.out.println(json);
    }

    @JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
    static class Student {
        private String studentName;
        @JsonProperty("studentAddress")
        private String studentAddress;

        public String getStudentName() {
            return studentName;
        }

        public void setStudentName(String studentName) {
            this.studentName = studentName;
        }

        public String getStudentAddress() {
            return studentAddress;
        }

        public void setStudentAddress(String studentAddress) {
            this.studentAddress = studentAddress;
        }
    }
}

执行结果为:

{"student_name":"hahah","studentAddress":"123"}

反之也成立

6

明白你的意思了,谢谢你这么好的建议,将会在周末发布新版本支持

1

太棒啦