【发布时间】:2021-02-04 18:21:56
【问题描述】:
使用原始 JSON.NET 包很容易做到这一点,您只需将 Formatting.None 传递给 ToString() 方法,您就会得到一个很好的压缩输出。 JSchema 没有类似的选项吗?
【问题讨论】:
标签: json.net formatting jsonschema
使用原始 JSON.NET 包很容易做到这一点,您只需将 Formatting.None 传递给 ToString() 方法,您就会得到一个很好的压缩输出。 JSchema 没有类似的选项吗?
【问题讨论】:
标签: json.net formatting jsonschema
给定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.
【讨论】: