首页 > 解决方案 > 如何使用 Kotlin、MongoDB 和 Jsonschema “oneof”获取正确的类类型

问题描述

我们正在使用消息队列来获取一些事件。这些事件被描述为这样的 json 模式。

{
  "title": "Partner",
  "type": "object",
  "properties": {
    "partnerID": {
      "type": "string",
      "examples": [
        "0001038645"
      ]
    },
    "partnerTyp": {
      "type": "string",
      "enum": [
        "NATPERS",
        "PAAR",
        "SONST-JURIST"
      ],
      "examples": [
        "SONST-JURIST"
      ]
    },
    "name": {
      "oneOf": [
          "vorname": {
            "type": "string",
            "examples": [
              "Bernd"
            ]
          },
          "nachname": {
            "type": "string",
            "examples": [
              "Wernersen"
            ]
          },
        },
        {
          "vorname1": {
            "type": "string",
            "examples": [
              "Bernd"
            ]
          },
        },
        {
          "nameExtern": {
            "type": "string",
            "examples": [
              "Internationale Pinsel Manufaktur Gesellschaft mbH"
            ]
          },
        }
      ]
    }
}

描述

这意味着我们可以拥有三种不同类型的合作伙伴,这也会导致在 kotlin 中产生不同的类。我们想将它们保存在我们的数据库(mongodb)中。

稍后我们希望通过 REST 将它们发送到另一个应用程序。

问题

我们现在遇到的问题是,当我们从事件中获取消息时,我们不知道如何确定需要将哪种类型保存在数据库中。

在其他项目中,我们有类似的东西

message.getBody(messageClass)

但是如何在此事件中使用 Information 获得正确的消息类?

以及稍后我们如何从数据库中获取正确的类型。

interface ContractRepository : MongoRepository<Partner, String> {
    override fun deleteAll()
} 

Partner 可以是一个抽象类吗?spring data 什么时候知道正确的实现是什么?

标签: mongodbkotlinjsonschema

解决方案


The everit-org/json-schema library has a feature called ValidationListener that reports events during validation, including "oneOf" subschema matches, so it probably provides enough information for you to determine the message class.

More precisely, if you run the validation with a ValidationListener configured, you will receive a #combinedSchemaMatch(CombinedSchemaMatchEvent) event, and the event's #getSchema() will return the wrapping "oneOf", and the #getSubSchema() will return the actually matched subschema (which will tell you the message class).

The library is written in java, so you can use it from kotlin.

Disclaimer: I'm the maintainer of the library.


推荐阅读