0
private static void WriteJson(string filepath, 
                              string filename, 
                              JsonSchema jsonschema)
        {
        using (TextWriter writer = File.CreateText(
                       @"C:\Users\ashutosh\Desktop\Output\" + filename + ".js"))
        using (var jtw = new JsonTextWriter(writer))
            {
            jtw.Formatting = Formatting.Indented;
            jsonschema.WriteTo(jtw);
            }
        //var json = JsonConvert.SerializeObject(
        //        jsonschema, Formatting.Indented, 
        //        new JsonSerializerSettings { 
        //                 NullValueHandling = NullValueHandling.Ignore });
        //    File.WriteAllText(
        //       @"C:\Users\ashutosh\Desktop\Output\" + filename + ".js", json);
        }

我正在从 JSON.net 创建一个 JSONSchema,然后将其写出来。我得到一个

Invalid Operation Exception Sequence contains no matching element

但是当我使用注释代码而不是通常的东西时。没有出现这样的异常。

1)是什么导致了这个异常?2)我会很高兴地使用第二种方法,但感觉不直观,它会打印出 JsonType 的整数值,用于 schema.Type 而不是(数组,整数,布尔等)

我该怎么做才能摆脱这种情况?

更新当has count = 0 的 " Properties" 属性 时发生异常。是。我已经对其进行了初始化,因此它不为空。最终,代码可能会也可能不会向其中添加元素。因此,计数可能保持为 0。JsonSchemaPropertiesDictionary<String,JsonSchema>

4

1 回答 1

1

默认情况下,枚举将被序列化为它们对应的整数值。StringEnumConverter您可以通过在序列化程序设置中提供轻松更改:

var json = JsonConvert.SerializeObject(jsonschema, Formatting.Indented,
    new JsonSerializerSettings
    {
        NullValueHandling = NullValueHandling.Ignore,
        Converters = new List<JsonConverter> { new StringEnumConverter() }
    });

编辑

我运行这个简单的测试代码:

var schema = new JsonSchemaGenerator().Generate(typeof(CustomType));
Debug.Assert(schema.Properties.Count == 0);
using (TextWriter textWriter = File.CreateText(@"schema.json"))
using (var jsonTextWriter = new JsonTextWriter(textWriter))
{
    jsonTextWriter.Formatting = Formatting.Indented;
    schema.WriteTo(jsonTextWriter);
}

// CustomType is a class without any fields/properties
public class CustomType { }

上面的代码将架构正确地序列化为:

{
    "type": "object",
    "properties": {}
}

您生成的架构是否正确?似乎序列化程序正在“思考”它应该处理一些实际上没有的属性。你能显示你生成模式的类型吗?类型可能存在问题,导致生成无效模式 - 但我仍然无法重现它。

于 2012-01-05T15:38:07.163 回答