如何在Java中使用Gson实现自定义JsonAdapter?
@JsonAdapteř注释可以在现场或类级别用于指定GSON。该TypeAdapter类可用于Java对象转换为从JSON。默认情况下,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()));
}
}
//客户分类
class Customer {
@JsonAdapter(CustomJsonAdapter.class)
Integer customerId = 101;
}
//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();
}
}输出结果
{"customerId":{"customerId":"101"}}热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便