我使用jackson将我的对象转换为json。
对象有2个字段:
@Entity
public class City {
@id
Long id;
String name;
public String getName() { return name; }
public void setName(String name){ this.name = name; }
public Long getId() { return id; }
public void setName(Long id){ this.id = id; }
}
因为我想使用jQuery自动完成功能,我想“id”显示为json中的“值”和“名称”显示为“标签”。杰克逊的文档不清楚这一点,我已经尝试了每一个注释,甚至远程看起来像它做什么我需要的,但我不能让名称出现为标签和id出现为json中的值。
有人知道怎么做吗,或者这是否可能?
杰克逊
如果您正在使用Jackson,那么您可以使用@JsonProperty注释来定制给定JSON属性的名称。
因此,你只需要用@JsonProperty注释实体字段,并提供一个自定义的JSON属性名,就像这样:
@Entity
public class City {
@Id
@JsonProperty("value")
private Long id;
@JsonProperty("label")
private String name;
//Getters and setters omitted for brevity
}
JavaEE或JakartaEE JSON-B
JSON- b是用于在Java对象与JSON之间进行转换的标准绑定层。如果你正在使用JSON- b,那么你可以通过@JsonbProperty注释覆盖JSON属性名:
@Entity
public class City {
@Id
@JsonbProperty("value")
private Long id;
@JsonbProperty("label")
private String name;
//Getters and setters omitted for brevity
}