Skip to content

Commit fc302d0

Browse files
committed
Extended API response JSON deserialization to be able to handle missing 'favorites' nodes. In case the user has no favorites the API does not return an empty 'favorites' node but no 'favorites' node at all.
1 parent 410132c commit fc302d0

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

src/main/java/com/github/m0nk3y2k4/thetvdb/internal/util/JsonDeserializer.java

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,11 @@
33
import static com.github.m0nk3y2k4.thetvdb.api.exception.APIException.API_JSON_PARSE_ERROR;
44

55
import java.io.IOException;
6+
import java.util.Collections;
67
import java.util.List;
78
import java.util.Map;
89
import java.util.function.Function;
10+
import java.util.function.Supplier;
911
import java.util.stream.Collectors;
1012
import java.util.stream.StreamSupport;
1113

@@ -86,10 +88,15 @@ public static APIResponse<List<String>> mapQueryParameters(@Nonnull JsonNode jso
8688
}
8789

8890
public static APIResponse<List<String>> mapFavorites(@Nonnull JsonNode json) throws APIException {
89-
Function<JsonNode, List<String>> dataFunction =
90-
node -> StreamSupport.stream(getData(node).get("favorites").spliterator(), false)
91-
.map(JsonNode::asText).collect(Collectors.toList());
92-
return mapObject(json, new TypeReference<>(){}, createFunctionalModule(dataFunction));
91+
if (getData(json).has("favorites")) {
92+
// If the user has no favorites just an empty data-node might be returned
93+
Function<JsonNode, List<String>> dataFunction =
94+
node -> StreamSupport.stream(getData(node).get("favorites").spliterator(), false)
95+
.map(JsonNode::asText).collect(Collectors.toList());
96+
return mapObject(json, new TypeReference<>() {}, createFunctionalModule(dataFunction));
97+
}
98+
99+
return mapObject(json, new TypeReference<>(){}, createFunctionalModule(Collections::emptyList));
93100
}
94101

95102
public static Map<String, String> mapSeriesHeader(@Nonnull JsonNode json) throws APIException {
@@ -163,6 +170,11 @@ private static <T> Module createFunctionalModule(@Nonnull Function<JsonNode, T>
163170
return new SimpleModule().addDeserializer(APIResponse.class, new FunctionalDeserializer<>(dataFunction));
164171
}
165172

173+
private static <T> Module createFunctionalModule(@Nonnull Supplier<T> supplier) {
174+
Function<JsonNode, T> dataFunction = node -> supplier.get();
175+
return new SimpleModule().addDeserializer(APIResponse.class, new FunctionalDeserializer<>(dataFunction));
176+
}
177+
166178
private static <T> T mapObject(@Nonnull JsonNode json, @Nonnull TypeReference<T> typeReference) throws APIException {
167179
return mapObject(json, typeReference, DFAULT_MODULE);
168180
}

0 commit comments

Comments
 (0)