[英]How to change a field name in JSON using 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 中顯示為“值”,而“名稱”則顯示為“標簽”。 傑克遜的文檔對此並不清楚,我已經嘗試了每一個注釋,即使遠程看起來它也能滿足我的需要,但我無法讓name
作為label
出現,而id
在 json 中作為value
出現。
有誰知道如何做到這一點,或者這是否可能?
您是否嘗試過使用@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; }
}
請注意,Jackson 1.x 中有org.codehaus.jackson.annotate.JsonProperty
,Jackson 2.x 中有com.fasterxml.jackson.annotation.JsonProperty
。 檢查您正在使用哪個 ObjectMapper(來自哪個版本),並確保使用正確的注釋。
如果您使用的是 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
}
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.