Azbesciak
Azbesciak

Reputation: 580

Jackson JsonSchema - Object as string in schema

I'm using ComparableQuantity from JSR 385 reference implementation - this is not a case, just want to mention that subtype is generic and I cannot modify it.

The case is that I am generating a Json schema with Jackson JsonSchemaModule. Currently, what I am receiving from that schema is of course something like below:

{
  "weight": {
    "type": "object",
    "id": "Mass>",
    "required": true,
    "properties": {
      "value": {
        "type": "number"
      },
      "unit": {
        "type": "object",
        "id": "Mass>",
        "properties": {
          "name": {
            "type": "string"
          },
          ...
        }
      }
    }
  }
}

Ofc, this does not give me a lot - it is too expressive. I already have a parsers which can create my values from string (with validation) and serialize it also to string (10m will be in json just "10 m"), and I would want to have the same schema, with pattern, for example:

{
  "weight": {
    "type": "string",
    "pattern": "[\\d,.]+\\s*(kg|t)",
    "required": true
  }
}

I know that Jdk8JacksonModule can make something similiar with Optional, but When I saw Jdk8OptionalBeanPropertyWriter, I have passed - even not sure if it is correct place to look for.

Also, I think it is possible to use ObjectMapper$acceptJsonFormatVisitor, maybe something with SchemaFactoryWrapper#expectObjectFormat - not sure.

What I have noticed is that when I add ComparableQuantity serialization module to Schema serializer (which is actually class serialization from schema), it will then return

{
  "weight": {
    "type": "any",
    "required": true
  }
}

so maybe this is some way...

Any example would be nice :).

Upvotes: 0

Views: 1039

Answers (1)

Azbesciak
Azbesciak

Reputation: 580

I've finished with overriding method JsonSerializer#acceptJsonFormatVisitor where I call visitor.expectStringFormat(type), and also, to add a pattern I added visitor in constructor of JsonSchemaGenerator.

This visitor bases on com.fasterxml.jackson.module.jsonSchema.customProperties.ValidationSchemaFactoryWrapper, but instead of expectObjectFormat overrides expectStringFormat of course.

Upvotes: 0

Related Questions