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

Triển khai custom JsonAdapter với Gson trong Java


Annotation @JsonAdapter có thể được dùng ở cấp field hoặc class để chỉ định cho Gson. Lớp TypeAdapter có thể được dùng để chuyển đổi đối tượng Java sang và từ JSON. Mặc định, thư viện Gson chuyển đổi các lớp ứng dụng sang JSON bằng các type adapter tích hợp sẵn nhưng chúng ta có thể ghi đè bằng cách cung cấp custom type adapter.

Cú pháp

@Retention(value=RUNTIME)
@Target(value={TYPE,FIELD})
public @interface JsonAdapter

Ví dụ

import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

public class JsonAdapterTest {
    public static void main(String[] args) {
        Gson gson = new Gson();
        System.out.println(gson.toJson(new Customer()));
    }
}

// Lớp Customer
class Customer {
    @JsonAdapter(CustomJsonAdapter.class)
    Integer customerId = 101;
}

// Lớp CustomJsonAdapter
class CustomJsonAdapter extends TypeAdapter<Integer> {
    @Override
    public Integer read(JsonReader jreader) throws IOException {
        return null;
    }
    
    @Override
    public void write(JsonWriter jwriter, Integer customerId) throws IOException {
        jwriter.beginObject();
        jwriter.name("customerId");
        jwriter.value(String.valueOf(customerId));
        jwriter.endObject();
    }
}

Kết quả

{"customerId":{"customerId":"101"}}

Giải thích: CustomJsonAdapter ghi ra một object JSON lồng nhau thay vì giá trị số đơn giản. Phương thức write() tùy chỉnh định dạng đầu ra.