DEV Community

LS
LS

Posted on

merge jsonschema

@SuppressWarnings("unchecked")
private static Document innerJsonSchema(Document full) {
  // full is { "$jsonSchema": { ... } }
  return (Document) full.get("$jsonSchema");
}

private static Document mergeSchemasAsOneOf(Document... fullSchemas) {
  List<Document> versions = new ArrayList<>();
  for (Document full : fullSchemas) {
    versions.add(innerJsonSchema(full));
  }
  return new Document("$jsonSchema", new Document("oneOf", versions));
}

// If you prefer "anyOf":
private static Document mergeSchemasAsAnyOf(Document... fullSchemas) {
  List<Document> versions = new ArrayList<>();
  for (Document full : fullSchemas) {
    versions.add(innerJsonSchema(full));
  }
  return new Document("$jsonSchema", new Document("anyOf", versions));
}

Enter fullscreen mode Exit fullscreen mode
import org.bson.Document;
import org.bson.json.JsonMode;
import org.bson.json.JsonWriterSettings;

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public final class SchemaDumper {
  private SchemaDumper() {}

  /** Dump the WHOLE validator doc: { "$jsonSchema": { ... } } */
  public static Path dumpValidator(String filenameWithoutExt, Document validator, Path outDir) throws Exception {
    Files.createDirectories(outDir);
    JsonWriterSettings pretty = JsonWriterSettings.builder()
        .indent(true)
        .outputMode(JsonMode.RELAXED)
        .build();
    String json = validator.toJson(pretty);
    Path file = outDir.resolve(filenameWithoutExt + ".json");
    Files.writeString(file, json, StandardCharsets.UTF_8);
    return file;
  }

  /** Dump only the INNER $jsonSchema object (no wrapper). */
  public static Path dumpInnerSchema(String filenameWithoutExt, Document validator, Path outDir) throws Exception {
    Document inner = validator.get("$jsonSchema", Document.class);
    if (inner == null) throw new IllegalArgumentException("Validator missing $jsonSchema");
    return dumpValidator(filenameWithoutExt, new Document("$jsonSchema", inner), outDir);
  }
}


Document cd18  = loadJsonSchema(CreditDecisioning.class, "{}");
Document cd20  = loadJsonSchema(CreditDecisioningV2.class, "{}");
Document merged = mergeSchemasAsAnyOf(cd18, cd20); // or oneOf

Path out = Path.of("target", "schemas");
SchemaDumper.dumpValidator("creditDecisioning-merged", merged, out);
// or, if someone wants only the inside object:
SchemaDumper.dumpInnerSchema("creditDecisioning-merged-inner", merged, out);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)