-
For example: I setup a custom converter for ObjectId type using MongoDB.Bson;
using System.Text.Json;
using System.Text.Json.Schema;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
JsonSerializerOptions serializerOptions = new(JsonSerializerOptions.Web)
{
TypeInfoResolver = new DefaultJsonTypeInfoResolver(),
Converters = { new JsonObjectIdConverter() },
};
JsonSchemaExporterOptions exporterOptions = new() { TreatNullObliviousAsNonNullable = true };
var schema = serializerOptions.GetJsonSchemaAsNode(typeof(Test), exporterOptions);
Console.WriteLine(schema);
file class Test
{
public required ObjectId Id { get; set; }
public required string Name { get; set; }
public required bool Flag { get; set; }
}
file class JsonObjectIdConverter : JsonConverter<ObjectId>
{
public override ObjectId Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
=> ObjectId.Parse(reader.GetString());
public override void Write(Utf8JsonWriter writer, ObjectId value, JsonSerializerOptions options)
=> writer.WriteStringValue(value.ToString());
} this just returns {
"type": "object",
"properties": {
"id": true,
"name": {
"type": "string"
},
"flag": {
"type": "boolean"
}
},
"required": [
"id",
"name",
"flag"
]
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Right now there isn't a public API for this. However, there is an API proposal to support scenarios like this: #105769. Basically, you either wait for this API to be realized in some form -- whenever this might be i don't know (it's currently a milestone for 10.0.0, but i am not involved with the .NET team and don't know how good the chances are for such a feature really becoming part of for the .NET 10 release), or you have to do this quasi "manually" using a TransformSchemaNode delegate, in which you somehow detect whether the property or the type of a property is being associated with one of your JsonConverters and then modify the Json schema for that property accordingly... |
Beta Was this translation helpful? Give feedback.
Right now there isn't a public API for this. However, there is an API proposal to support scenarios like this: #105769. Basically, you either wait for this API to be realized in some form -- whenever this might be i don't know (it's currently a milestone for 10.0.0, but i am not involved with the .NET team and don't know how good the chances are for such a feature really becoming part of for the .NET 10 release), or you have to do this quasi "manually" using a TransformSchemaNode delegate, in which you somehow detect whether the property or the type of a property is being associated with one of your JsonConverters and then modify the Json schema for that property accordingly...