为什么我从服务器得到错误的对象属性?

时间:2016-03-23 19:25:24

标签: java json spring

当我从带有弹簧的服务器获取List时,我会像这样进入客户端对象用户:

{
  "id": 1,
  "name": "hgfhj",
  "age": 120,
  "createdDate": 1457211138000,
  "admin": true
}

UserController.java方法:

@RequestMapping(value = "/user/", method = RequestMethod.GET)
    public ResponseEntity<List<User>> getList() {

        List usersList = userService.getList();

        ResponseEntity<List<User>> respEntity = null;

        if(usersList.isEmpty()){
            respEntity =new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);
            return respEntity;
        }

        respEntity =new ResponseEntity<List<User>>(usersList, HttpStatus.OK);

        return respEntity;

    }

当我使用Gson时,我会像这样进入客户端对象用户:

{
  "id": 1,
  "name": "hgfhj",
  "age": 120,
  "isAdmin": true,
  "createdDate": "Mar 5, 2016 10:52:18 PM"
}

UserController.java方法:

 @RequestMapping(value = "/user/", method = RequestMethod.GET)
    public String getList() {

        List usersList = userService.getList();

        ResponseEntity<List<User>> respEntity = null;

          respEntity =new ResponseEntity<List<User>>(usersList, HttpStatus.OK);

        Gson gson = new Gson();
        String json = gson.toJson(usersList);

        return json;
    }

在所有项目用户属性名称“isAdmin”中,我不明白为什么它被更改为“admin”。如何使用spring但是在没有gson的情况下进入客户端“isAdmin”?

User.java:

@Entity
public class User {
    /*@Column(name="id")*/
    @Id
    @GeneratedValue
    private int id;

    @Column(name="name")
    private String name;

    @Column(name="age")
    private int age;

    @Column(name="isAdmin")
    private boolean isAdmin;

    @Column(name="createdDate")
    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(pattern = "dd.MM.yyyy")
    private Date createdDate;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public boolean isAdmin() {
        return isAdmin;
    }

    public Date getCreatedDate() {
        return createdDate;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void setIsAdmin(boolean isAdmin) {
        this.isAdmin = isAdmin;
    }

    public void setCreatedDate(Date createdDate) {
        this.createdDate = createdDate;
    }
}

2 个答案:

答案 0 :(得分:1)

使用@JsonProperty注释您的用户对象属性,以便将您想要的名称作为输出。

实施例

public class User {
    ...

    @SerializedName("isAdmin")
    @Column(name="isAdmin")
    private boolean admin;

    ...
}

这将返回类似

的内容
{
    "isAdmin" : true
}

了解更多信息:http://www.javacreed.com/gson-annotations-example/

更新: 为了将来的参考,@ jsonProperty(“name”)需要在gson的getter上,而不是属性。

答案 1 :(得分:1)

请对您的User类的setter方法进行以下更改

@JsonProperty("isAdmin") // i guess you want isAdmin into response..
public void setIsAdmin(boolean isAdmin) {
        this.isAdmin = isAdmin;
}