如何在 Java 中使用 Gson 实现自定义 JsonAdapter?
@JsonAdapter 注释可以用于字段或类级别,以指定 Gson。TypeAdapter 类可用于将 Java 对象转换为 JSON,再从 JSON 转换为 Java 对象。默认情况下,Gson 库使用内置类型适配器将应用程序类转换为 JSON,但我们可以通过提供自定义类型适配器来覆盖它。
语法
@Retention(value=RUNTIME)
@Target(value={TYPE,FIELD})
public @interface JsonAdapter示例
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()));
}
}
// Customer class
class Customer {
@JsonAdapter(CustomJsonAdapter.class)
Integer customerId = 101;
}
// CustomJsonAdapter class
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();
}
}输出
{"customerId":{"customerId":"101"}}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP