【问题标题】:How do I output JSchema without the formatting?如何在没有格式化的情况下输出 JSchema?
【发布时间】:2021-02-04 18:21:56
【问题描述】:

使用原始 JSON.NET 包很容易做到这一点,您只需将 Formatting.None 传递给 ToString() 方法,您就会得到一个很好的压缩输出。 JSchema 没有类似的选项吗?

【问题讨论】:

    标签: json.net formatting jsonschema


    【解决方案1】:

    给定JSchema schema,要获得紧凑的格式,您可以:

    var json = JsonConvert.SerializeObject(schema, Formatting.None);
    

    或者

    using var sw = new StringWriter(CultureInfo.InvariantCulture);
    using (var jsonWriter = new JsonTextWriter(sw) { Formatting = Formatting.None })
        schema.WriteTo(jsonWriter);
    var json = sw.ToString();
    

    后者可以做成一个扩展方法,可选用JSchemaWriterSettings:

    public static partial class JsonExtensions
    {
        public static string ToString(this JSchema schema, Formatting formatting, JSchemaWriterSettings settings = default)
        {
            using var sw = new StringWriter(CultureInfo.InvariantCulture);
            using (var jsonWriter = new JsonTextWriter(sw) { Formatting = formatting })
                if (settings == null)
                    schema.WriteTo(jsonWriter);
                else
                    schema.WriteTo(jsonWriter, settings); // This overload throws if settings is null
            return sw.ToString();
        }
    }
    

    然后你可以这样做:

    var unversionedSchema = schema.ToString(Formatting.None);
    var versionedSchema = schema.ToString(Formatting.None, new JSchemaWriterSettings { Version = SchemaVersion.Draft7 } );
    

    演示小提琴here.

    【讨论】:

      猜你喜欢
      • 2020-01-05
      • 2010-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-29
      • 1970-01-01
      • 1970-01-01
      • 2011-02-23
      相关资源
      最近更新 更多