import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.junit.Test; public class JsonPropertyTest { @Test public void testJsonProperty() throws JsonProcessingException { Person john = Person.builder() .id("1") .name("john") .age(18) .build(); ObjectMapper mapper = new ObjectMapper(); System.out.println(mapper.writeValueAsString(john)); } @Data @Builder @AllArgsConstructor @NoArgsConstructor static class Person{ @JsonProperty("p_id") private String id; @JsonProperty("p_name") private String name; @JsonProperty("p_age") private int age; } }
输出结果:
注意:@JsonProperty是jackson的注解,序列化对象要使用Jackson的类库,不要用fastjson等其他json序列化类库,否则注解不会生效。