1
1
package io .github .stavshamir .springwolf .schemas ;
2
2
3
3
import com .fasterxml .jackson .annotation .JsonInclude ;
4
+ import com .fasterxml .jackson .core .JsonProcessingException ;
4
5
import com .fasterxml .jackson .databind .ObjectMapper ;
5
6
import com .fasterxml .jackson .databind .module .SimpleModule ;
6
7
import io .swagger .oas .inflector .examples .ExampleBuilder ;
7
8
import io .swagger .oas .inflector .examples .models .Example ;
8
9
import io .swagger .oas .inflector .processors .JsonNodeExampleSerializer ;
9
- import io .swagger .util .Json ;
10
10
import io .swagger .v3 .core .converter .ModelConverters ;
11
11
import io .swagger .v3 .oas .models .media .Schema ;
12
12
import lombok .extern .slf4j .Slf4j ;
@@ -27,14 +27,18 @@ public class DefaultSchemasService implements SchemasService {
27
27
28
28
public DefaultSchemasService () {
29
29
objectMapper .setSerializationInclusion (JsonInclude .Include .NON_NULL );
30
-
31
30
SimpleModule simpleModule = new SimpleModule ().addSerializer (new JsonNodeExampleSerializer ());
32
- Json . mapper () .registerModule (simpleModule );
31
+ objectMapper .registerModule (simpleModule );
33
32
}
34
33
35
34
@ Override
36
35
public Map <String , Schema > getDefinitions () {
37
- definitions .forEach ((k , schema ) -> setExample (schema ));
36
+ // The examples must first be set as JSON strings (the inflector does not work otherwise)
37
+ definitions .forEach (this ::buildExampleAsString );
38
+
39
+ // Then they must be deserialized to map, or they will be serialized as reguler string and not json by the
40
+ // object mapper
41
+ definitions .forEach (this ::deserializeExampleToMap );
38
42
return definitions ;
39
43
}
40
44
@@ -48,14 +52,21 @@ public String register(Class<?> type) {
48
52
return type .getSimpleName ();
49
53
}
50
54
51
- private void setExample ( Schema schema ) {
55
+ private void buildExampleAsString ( String k , Schema schema ) {
52
56
log .debug ("Setting example for {}" , schema .getName ());
53
57
54
58
Example example = ExampleBuilder .fromSchema (schema , definitions );
55
- String exampleAsJson = Json .pretty (example );
59
+ try {
60
+ String exampleAsJson = objectMapper .writeValueAsString (example );
61
+ schema .setExample (exampleAsJson );
62
+ } catch (JsonProcessingException e ) {
63
+ log .error ("Failed to write example value as a string" );
64
+ }
65
+ }
56
66
67
+ private void deserializeExampleToMap (String k , Schema schema ) {
57
68
try {
58
- schema .setExample (objectMapper .readValue (exampleAsJson , Map .class ));
69
+ schema .setExample (objectMapper .readValue (( String ) schema . getExample () , Map .class ));
59
70
} catch (IOException e ) {
60
71
log .error ("Failed to convert example object of {} to map" , schema .getName ());
61
72
}
0 commit comments