Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Thay đổi tên trường JSON bằng Jackson @JsonProperty trong Java

Annotation @JsonProperty của Jackson dùng trên property hoặc method khi serialization hoặc deserialization JSON. Nó nhận tham số tùy chọn 'name' hữu ích khi tên property khác với 'key' trong JSON. Mặc định nếu key name khớp property name, giá trị sẽ map vào property value.

Ví dụ minh họa

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);
    }
}

// Lớp User
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;
    }
}

Kết quả đầu ra

{
    "first-name" : "Sai",
    "last-name" : "Adithya",
    "mobile-phone" : "9959984000",
    "home_phone" : "0402358700"
}

Mẹo: @JsonProperty cũng dùng trên getter/setter. Có thể kết hợp với @JsonAlias để chấp nhận nhiều tên key khác nhau khi deserialize.