Example #1
0
        /// <inheritdoc />
        public override void WriteJson(JsonWriter writer, IMetadataSchemaProvider?value, JsonSerializer serializer)
        {
            // Serializer copy without this converter to prevent infinite loop.
            var serializerCopy = serializer.CopyWithoutConverter(this);

            if (!Options.UseSchemasRoot)
            {
                // Serialize standard way
                serializerCopy.Serialize(writer, value);
                return;
            }

            // Get ISchemaRepository from current writer ot create new.
            ISchemaRepository schemaRepository = /*value?.Schemas ?? */ writer.AsMetadataProvider().GetMetadata <ISchemaRepository>() ?? new SchemaRepository();

            // Temp writer
            JTokenWriter jTokenWriter = new JTokenWriter();

            // Attaches ISchemaRepository to reader
            jTokenWriter.AsMetadataProvider().SetMetadata((ISchemaRepository)schemaRepository);

            // Stage:1 Write to jTokenWriter
            serializerCopy.Serialize(jTokenWriter, value);

            JToken?jToken = jTokenWriter.Token;

            if (jToken != null)
            {
                JObject defsContent  = new JObject();
                JToken  defsProperty = new JProperty(Options.SchemasRootName, defsContent);

                foreach (KeyValuePair <string, ISchema> valuePair in schemaRepository.GetSchemas())
                {
                    object    schema         = new CompactSchemaGenerator(serializer, Options).GenerateSchema(valuePair.Value);
                    JProperty schemaProperty = new JProperty(valuePair.Key, new JObject(new JProperty("$metadata.schema.compact", JArray.FromObject(schema))));
                    defsContent.Add(schemaProperty);
                }

                // Stage2: Add "$defs" section to json.
                jToken.Last?.AddAfterSelf(defsProperty);

                // Stage2: Write final json
                jToken.WriteTo(writer);
            }
        }