序列化时如何更改对象属性名称?

时间:2018-12-22 16:11:09

标签: java json serialization

我有一个这样的对象。

public class Profile {
  private String email;
  private String phone;

  @SerializedName("userCode")
  private String user_code;

  public String getEmail() {
      return email;
  }

  public String getPhone() {
      return phone;
  }

  public String getUser_code() {
      return user_code;
  }
}

这是我在Rest API中返回该对象时得到的

{
   "email": "abc@gmail.com",
   "phone": 12345678,
   "user_code": "742aeaefac"
}

显然,这里的注释@SerializedName无效,我可以理解它是基于其吸气剂名称而不是在注释中获取对象属性名称的。如果我将吸气剂名称更改为getUserCode(),它将按预期工作。

我也尝试使用@JsonProperty,但也没有帮助。

有人可以解释这里解决这个问题的工作吗?

更新控制器中用于序列化过程的代码。

@PostMapping(path = "/login", produces = "application/json")
@ResponseBody
public ClientRepresentation login(@RequestBody LoginRequest login) {
    Map<String, Object> resObj = new HashMap<String, Object>();
    ProfileResponse profileResponse = userService.findUserProfileByUserCode(login.getUserCode());

    //Code logic to process object data...

    resObj.put("profile", profileResponse);

    return ClientRepresentationBuilder.buildClientRep(HttpStatus.OK.value(), "Success", resObj);
}

ClientRepresentation类

public class ClientRepresentation implements Serializable {
    private Integer code;
    private String message;
    private Object data;
}

0 个答案:

没有答案
相关问题