Skip to content

Commit

Permalink
minor refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
tonivade committed May 7, 2024
1 parent 2385e84 commit c14fb4e
Showing 1 changed file with 20 additions and 17 deletions.
37 changes: 20 additions & 17 deletions lib/src/main/java/com/github/tonivade/purejson/JsonDecoder.java
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@
@FunctionalInterface
public interface JsonDecoder<T> {


@Nullable
T decode(JsonNode json);

Expand Down Expand Up @@ -125,27 +124,31 @@ static <T> JsonDecoder<T> pojoDecoder(Class<T> clazz) {
.toList();
return json -> {
if (json instanceof JsonNode.JsonObject object) {
try {
var constructor = findConstructor(clazz);
if (constructor.trySetAccessible()) {
if (constructor.getParameterCount() > 0 && constructor.isAnnotationPresent(JsonCreator.class)) {
return createPojoFromAnnotatedConstructor(constructor, fields, object);
} else if (constructor.getParameterCount() == 0) {
return createPojoFromDefaultConstructor(constructor, fields, object);
} else {
throw new IllegalStateException("no suitable constructor for type " + clazz.getName());
}
} else {
throw new IllegalStateException("cannot access to constructor: " + constructor);
}
} catch (NoSuchMethodException e) {
throw new IllegalStateException("no suitable constructor found for type: " + clazz.getName(), e);
}
return createPojo(clazz, fields, object);
}
throw new IllegalArgumentException(json.toString());
};
}

static <T> T createPojo(Class<T> clazz, List<Tuple2<Field, JsonDecoder<Object>>> fields, JsonNode.JsonObject object) {
try {
var constructor = findConstructor(clazz);
if (constructor.trySetAccessible()) {
if (constructor.getParameterCount() > 0 && constructor.isAnnotationPresent(JsonCreator.class)) {
return createPojoFromAnnotatedConstructor(constructor, fields, object);
} else if (constructor.getParameterCount() == 0) {
return createPojoFromDefaultConstructor(constructor, fields, object);
} else {
throw new IllegalStateException("no suitable constructor for type " + clazz.getName());
}
} else {
throw new IllegalStateException("cannot access to constructor: " + constructor);
}
} catch (NoSuchMethodException e) {
throw new IllegalStateException("no suitable constructor found for type: " + clazz.getName(), e);
}
}

static <T> T createPojoFromDefaultConstructor(Constructor<T> constructor, List<Tuple2<Field, JsonDecoder<Object>>> fields,
JsonNode.JsonObject object) {
try {
Expand Down

0 comments on commit c14fb4e

Please sign in to comment.