Skip to content

Commit 1b4a06d

Browse files
authored
Update java-extension.md
1 parent d09815d commit 1b4a06d

File tree

1 file changed

+41
-1
lines changed

1 file changed

+41
-1
lines changed

java-extension.md

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ The general direction to provide extensiblity, is to give the user a callback, i
1212
All kinds of annotation support can be implemented using the callback. Also the callback should control the codegen if possible, not
1313
slowing down the runtime execution.
1414

15-
# Decoder interface
15+
# Customize type decoding
1616

1717
```java
1818
public interface Decoder {
@@ -64,3 +64,43 @@ JsonIterator iter = JsonIterator.parse("\"1481365190000\"");
6464
List<Integer> listOfInt = iter.read(listOfIntType);
6565
System.out.println(listOfInt); // [1, 4, 8, 1, 3, 6, 5, 1, 9, 0, 0, 0, 0]
6666
```
67+
68+
# Customize field decoding
69+
70+
Sometimes, we can not just customize the type, all different occurence of the type will need different encoding. So we can precisely control individual field decoding. The callback interface is still `Decoder`, we just need to register it to field instead of type.
71+
72+
```java
73+
public class TestObject1 {
74+
public String field1;
75+
}
76+
77+
JsonIterator.registerFieldDecoder(TestObject1.class, "field1", new Decoder() {
78+
79+
@Override
80+
public Object decode(JsonIterator iter) throws IOException {
81+
return Integer.toString(iter.readInt());
82+
}
83+
});
84+
JsonIterator iter = JsonIterator.parse("{'field1': 100}".replace('\'', '"'));
85+
TestObject1 myObject = iter.read(TestObject1.class);
86+
assertEquals("100", myObject.field1);
87+
```
88+
89+
For field decoding, there is one thing special: primitive types. If the field is of type like `int` or `long`, we do not want to return `Object` from `Decoder` then unbox it to primitive types. The decoder registered by user should not be forced to go through this process. And `IntDecoder` is what we need:
90+
91+
```java
92+
public class TestObject2 {
93+
public int field1;
94+
}
95+
96+
JsonIterator.registerFieldDecoder(TestObject2.class, "field1", new Decoder.IntDecoder() {
97+
98+
@Override
99+
public int decodeInt(JsonIterator iter) throws IOException {
100+
return Integer.valueOf(iter.readString());
101+
}
102+
});
103+
JsonIterator iter = JsonIterator.parse("{'field1': '100'}".replace('\'', '"'));
104+
TestObject2 myObject = iter.read(TestObject2.class);
105+
assertEquals(100, myObject.field1);
106+
```

0 commit comments

Comments
 (0)