Skip to content

Commit c53cf8f

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

File tree

1 file changed

+62
-1
lines changed

1 file changed

+62
-1
lines changed

java-extension.md

Lines changed: 62 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ public class MyAnnotationSupport extends EmptyExtension {
173173
@Override
174174
public boolean updateBinding(Binding field) {
175175
JsonProperty jsonProperty = field.getAnnotation(JsonProperty.class);
176-
if (jsonProperty == null) {
176+
if (jsonProperty != null) {
177177
String alternativeField = jsonProperty.value();
178178
if (!alternativeField.isEmpty()) {
179179
field.fromNames = new String[]{alternativeField};
@@ -200,4 +200,65 @@ assertEquals(100, obj.field1);
200200

201201
If you do not want to write annotation support yourself, you can use built-in `com.jsoniter.annotation.JsoniterAnnotationSupport`.
202202

203+
# No default constructor? No problem!
204+
205+
Jsoniter can work with class without default constructor. The extension can customize the constructor to be used for specific class. The constructor can also be a static method, instead of real constructor.
206+
207+
```java
208+
public interface Extension {
209+
// ...
210+
CustomizedConstructor getConstructor(Class clazz);
211+
/// ...
212+
}
213+
214+
public class CustomizedConstructor {
215+
/**
216+
* set to null if use constructor
217+
* otherwise use static method
218+
*/
219+
public String staticMethodName;
220+
221+
/**
222+
* the parameters to call constructor or static method
223+
*/
224+
public List<Binding> parameters = new ArrayList<Binding>();
225+
226+
public static CustomizedConstructor DEFAULT_INSTANCE = new CustomizedConstructor();
227+
}
228+
```
229+
230+
Using this extension point, `@JsonCreator` annotation support has been implemented. You can mark it on constructor:
231+
232+
```
233+
public static class NoDefaultCtor {
234+
private int field1;
235+
236+
@JsonCreator
237+
public NoDefaultCtor(@JsonProperty("field1") int field1) {
238+
this.field1 = field1;
239+
}
240+
}
241+
```
242+
243+
Or, you can mark it on static method:
244+
245+
```
246+
public static class StaticFactory {
247+
248+
private int field1;
249+
250+
private StaticFactory() {
251+
}
252+
253+
@JsonCreator
254+
public static StaticFactory createObject(@JsonProperty("field1") int field1) {
255+
StaticFactory obj = new StaticFactory();
256+
obj.field1 = field1;
257+
return obj;
258+
}
259+
}
260+
```
261+
262+
To enable jsoniter annotation support `JsoniterAnnotationSupport.enable()` must be called first
263+
203264

0 commit comments

Comments
 (0)