Skip to content

Commit 3770a2b

Browse files
committed
Ensure consistent model structure keying with sorted properties in Jackson JSON writer
1 parent eb85d80 commit 3770a2b

File tree

1 file changed

+30
-4
lines changed

1 file changed

+30
-4
lines changed

modules/openapi-generator/src/main/java/org/openapitools/codegen/InlineModelResolver.java

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,10 @@
1717

1818
package org.openapitools.codegen;
1919

20+
import com.fasterxml.jackson.core.JsonProcessingException;
21+
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
22+
import com.fasterxml.jackson.databind.MapperFeature;
23+
import com.fasterxml.jackson.databind.ObjectMapper;
2024
import io.swagger.v3.core.util.Json;
2125
import io.swagger.v3.oas.models.*;
2226
import io.swagger.v3.oas.models.callbacks.Callback;
@@ -25,6 +29,7 @@
2529
import io.swagger.v3.oas.models.parameters.RequestBody;
2630
import io.swagger.v3.oas.models.responses.ApiResponse;
2731
import io.swagger.v3.oas.models.responses.ApiResponses;
32+
import org.apache.commons.lang3.StringUtils;
2833
import org.openapitools.codegen.utils.ModelUtils;
2934
import org.slf4j.Logger;
3035
import org.slf4j.LoggerFactory;
@@ -36,6 +41,17 @@ public class InlineModelResolver {
3641
private OpenAPI openapi;
3742
private Map<String, Schema> addedModels = new HashMap<String, Schema>();
3843
private Map<String, String> generatedSignature = new HashMap<String, String>();
44+
45+
// structure mapper sorts properties alphabetically on write to ensure models are
46+
// serialized consistently for lookup of existing models
47+
private static ObjectMapper structureMapper;
48+
49+
static {
50+
structureMapper = Json.mapper().copy();
51+
structureMapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
52+
structureMapper.writer(new DefaultPrettyPrinter());
53+
}
54+
3955
static Logger LOGGER = LoggerFactory.getLogger(InlineModelResolver.class);
4056

4157
void flatten(OpenAPI openapi) {
@@ -488,15 +504,25 @@ private String resolveModelName(String title, String key) {
488504
}
489505

490506
private String matchGenerated(Schema model) {
491-
String json = Json.pretty(model);
492-
if (generatedSignature.containsKey(json)) {
493-
return generatedSignature.get(json);
507+
try {
508+
String json = structureMapper.writeValueAsString(model);
509+
if (generatedSignature.containsKey(json)) {
510+
return generatedSignature.get(json);
511+
}
512+
} catch (JsonProcessingException e) {
513+
e.printStackTrace();
494514
}
515+
495516
return null;
496517
}
497518

498519
private void addGenerated(String name, Schema model) {
499-
generatedSignature.put(Json.pretty(model), name);
520+
try {
521+
String json = structureMapper.writeValueAsString(model);
522+
generatedSignature.put(json, name);
523+
} catch (JsonProcessingException e) {
524+
e.printStackTrace();
525+
}
500526
}
501527

502528
/**

0 commit comments

Comments
 (0)