如何使用 Java 中的 Jackson 在 JSON 中更改一個欄位名稱?
在 **JSON** 的 **序列化 **或 **反序列化 **過程中,Jackson 註解 @JsonProperty 用於某個屬性或方法。它採用一個可選的“name”引數 ,當 **JSON** 中的屬性名稱與“key”名稱 不同時,此引數很有用。預設情況下,如果鍵名稱與屬性名稱匹配,則值對映到屬性值。
在以下示例中,我們可以在 JSON 中使用 @JsonProperty 註解 更改欄位名稱。
示例
import java.io.IOException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.annotation.JsonProperty;
public class JsonPropertyAnnotationTest {
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
User user = new User("Sai", "Adithya", "9959984000", "0402358700");
String data = mapper.writeValueAsString(user);
System.out.println(data);
}
}
// User class
class User {
@JsonProperty("first-name")
public String firstName;
@JsonProperty("last-name")
public String lastName;
@JsonProperty("mobile-phone")
public String mobilePhone;
@JsonProperty("home_phone")
public String workPhone;
public User(String firstName, String lastName, String mobilePhone, String workPhone) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.mobilePhone = mobilePhone;
this.workPhone = workPhone;
}
}輸出
{
"first-name" : "Sai",
"last-name" : "Adithya",
"mobile-phone" : "9959984000",
"home_phone" : "0402358700"
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP