Java - @JsonProperty

@JsonProperty介绍

作用

@JsonProperty 用于属性上,将属性的名称序列化为另外一个名称。

实例

LoginController.java

@RestController
public class LoginController {
    @GetMapping("test01")
    public ResponseEntity<ResponseResult<User>> test01() {
        User user = User.builder().name("Bill").credential("123456").build();

        return new ResponseEntity<>(ResponseResult.success(user), HttpStatus.OK);
    }

    @GetMapping("test02")
    public ResponseEntity<ResponseResult<User>> test02() {
        User user = new User("Jim", "2345678");

        return new ResponseEntity<>(ResponseResult.success(user), HttpStatus.OK);
    }
}

User.java

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class User {
    @JsonProperty("username")
    private String name;

    @JsonProperty("password")
    private String credential;
}

ResponseResult.java

import lombok.Data;

@Data
public class ResponseResult<T> {
    private final Integer code;
    private final String message;
    private final T data;

    private ResponseResult(ResultStatusType resultStatusType, T data) {
        this.code = resultStatusType.getCode();
        this.message = resultStatusType.getMessage();
        this.data = data;
    }

    private ResponseResult(ResultStatusType resultStatusType, String message, T data) {
        this.code = resultStatusType.getCode();
        this.message = message;
        this.data = data;
    }

    public static <T> ResponseResult<T> success(T data) {
        return new ResponseResult<>(ResultStatusType.SUCCESS, data);
    }

    public static <T> ResponseResult<T> failure(ResultStatusType resultStatusType, String message, T data) {
        return new ResponseResult<>(resultStatusType, message, data);
    }
}

ResultStatusType.java

import lombok.Getter;
import org.springframework.http.HttpStatus;

@Getter
public enum ResultStatusType {
    SUCCESS(0, "OK"),
    BAD_REQUEST(HttpStatus.BAD_REQUEST.value(), "Bad Request"),
    INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR.value(), "Internal Server Error"),
    ;

    private final Integer code;
    private final String message;

    ResultStatusType(Integer code, String message) {
        this.code = code;
        this.message = message;
    }
}

代码使用Spring Boot框架,端口6061,使用Swagger测试结果如下:

解析

@JsonProperty 注入的名称为username & password,因此传给前段的JSON中 name & credential 分别转为username & password

构造User对象采用2种方式,builder与new。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值