-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathClassWithAdapter.java
44 lines (37 loc) · 1.06 KB
/
ClassWithAdapter.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.example;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
@JsonAdapter(ClassWithAdapter.Adapter.class)
public class ClassWithAdapter {
static class Adapter extends TypeAdapter<ClassWithAdapter> {
@Override
public ClassWithAdapter read(JsonReader in) throws IOException {
in.beginObject();
String name = in.nextName();
if (!name.equals("custom")) {
throw new IllegalArgumentException("Unexpected name: " + name);
}
int i = in.nextInt();
in.endObject();
return new ClassWithAdapter(i);
}
@Override
public void write(JsonWriter out, ClassWithAdapter value) throws IOException {
out.beginObject();
out.name("custom");
out.value(value.i);
out.endObject();
}
}
public Integer i;
public ClassWithAdapter(int i) {
this.i = i;
}
@Override
public String toString() {
return "ClassWithAdapter[" + i + "]";
}
}