Skip to content

Commit c3eef03

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

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

java-extension.md

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,3 +104,50 @@ JsonIterator iter = JsonIterator.parse("{'field1': '100'}".replace('\'', '"'));
104104
TestObject2 myObject = iter.read(TestObject2.class);
105105
assertEquals(100, myObject.field1);
106106
```
107+
108+
# Rename field
109+
110+
Besides controlling how to decode a value, changing which JSON field bind to which object field is a very common requirement. Instead of only provide a `@JsonProperty` to change the mapping, jsoniter provide a much more powerful solution, a callback interface `Extension`. There are many things a extension can customize, here we focus on field renaming.
111+
112+
```java
113+
public class TestObject4 {
114+
public int field1;
115+
}
116+
117+
JsonIterator.registerExtension(new EmptyExtension() {
118+
@Override
119+
public boolean updateBinding(Binding field) {
120+
if (field.clazz == TestObject4.class && field.name.equals("field1")) {
121+
field.fromNames = new String[]{"field_1", "Field1"};
122+
return true;
123+
}
124+
return false;
125+
}
126+
});
127+
JsonIterator iter = JsonIterator.parse("{'field_1': 100}".replace('\'', '"'));
128+
TestObject4 myObject1 = iter.read(TestObject4.class);
129+
assertEquals(100, myObject1.field1);
130+
```
131+
132+
The callback `updateBinding` change the data source or decoder for a field. The `fromNames` is a `String[]`, with following options:
133+
134+
* null: do not customize this field
135+
* empty array: disable this field binding. works like `@JsonIgnore`
136+
* one or many: you can map multiple possible json field to one object field
137+
138+
The input is a concept called `Binding`, which not only represent field, but also constructor parameter and setter parameter. It contains the necessary information about what is binding, and you can customize how to bind it:
139+
140+
```
141+
public class Binding {
142+
// input
143+
public Class clazz;
144+
public String name;
145+
public Type valueType;
146+
public Annotation[] annotations;
147+
// output
148+
public String[] fromNames;
149+
public Decoder decoder;
150+
}
151+
```
152+
153+
So we can also customize the field decoder using `Extension` to update bindings. Actually type decoder and field decoder callback is just a shortcut. The `Extension` interface can do all the job.

0 commit comments

Comments
 (0)