我正在使用jackson将我的一个对象转换为json。该对象有两个字段:
@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; }
}
由于我想将其与标签自动完成功能一起使用,因此我希望'id‘在json中显示为’jQuery‘,而'name’显示为'label‘。关于这一点,jackson的文档并不清楚,我已经尝试了所有的注释,即使是很少的,看起来也能满足我的需求,但是我不能让name
在json中以label
的形式出现,而id
以value
的形式出现。
有没有人知道怎么做或者这是可能的吗?
发布于 2011-09-01 23:17:22
你试过使用@JsonProperty吗?
@Entity
public class City {
@id
Long id;
String name;
@JsonProperty("label")
public String getName() { return name; }
public void setName(String name){ this.name = name; }
@JsonProperty("value")
public Long getId() { return id; }
public void setId(Long id){ this.id = id; }
}
发布于 2015-08-28 20:35:35
请注意,在Jackson 1.x中有org.codehaus.jackson.annotate.JsonProperty
,在Jackson 2.x中有com.fasterxml.jackson.annotation.JsonProperty
。检查您使用的是哪个ObjectMapper (来自哪个版本),并确保使用了正确的注释。
发布于 2020-04-08 17:44:50
杰克逊
如果您正在使用JSON,那么您可以使用@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
}
https://stackoverflow.com/questions/7263282
复制相似问题