Skip to content

Commit 022de4c

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

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

java-extension.md

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,3 +151,53 @@ public class Binding {
151151
```
152152

153153
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.
154+
155+
# Your own annotation support
156+
157+
It is very common to support `@JsonProperty` to rename field. By registering your own extension, you can implement them very easily.
158+
159+
```java
160+
@Target({ElementType.ANNOTATION_TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
161+
@Retention(RetentionPolicy.RUNTIME)
162+
public @interface JsonProperty {
163+
String USE_DEFAULT_NAME = "";
164+
String value() default USE_DEFAULT_NAME;
165+
}
166+
167+
public class MyAnnotationSupport extends EmptyExtension {
168+
169+
public static void enable() {
170+
JsonIterator.registerExtension(new JsoniterAnnotationSupport());
171+
}
172+
173+
@Override
174+
public boolean updateBinding(Binding field) {
175+
JsonProperty jsonProperty = field.getAnnotation(JsonProperty.class);
176+
if (jsonProperty == null) {
177+
String alternativeField = jsonProperty.value();
178+
if (!alternativeField.isEmpty()) {
179+
field.fromNames = new String[]{alternativeField};
180+
return true;
181+
}
182+
}
183+
return false;
184+
}
185+
}
186+
```
187+
188+
Then you can annotate
189+
190+
```
191+
public static class AnnotatedObject {
192+
@JsonProperty("field-1")
193+
public int field1;
194+
}
195+
196+
JsonIterator iter = JsonIterator.parse("{'field-1': 100}".replace('\'', '"'));
197+
AnnotatedObject obj = iter.read(AnnotatedObject.class);
198+
assertEquals(100, obj.field1);
199+
```
200+
201+
If you do not want to write annotation support yourself, you can use built-in `com.jsoniter.annotation.JsoniterAnnotationSupport`.
202+
203+

0 commit comments

Comments
 (0)