【问题标题】:Invalid Operation Exception , No elements in the sequence无效操作异常,序列中没有元素
【发布时间】:2012-01-02 19:05:36
【问题描述】:
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 而不是(数组,整数,布尔等)

我能做些什么来摆脱这种情况?

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

【问题讨论】:

    标签: c# json json.net jsonschema


    【解决方案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": {}
    }
    

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

    【讨论】:

    • 首先你的回答正确地解决了我的第二个问题。谢谢你。我将更新我的问题,为您提供 jsonschema 的快照。我很想将此标记为答案,我很快就会这样做。但我也想更多地关注前面的部分,因为这真的让我很困惑。
    • 有没有办法告诉序列化器不要打印特定的属性。例如我有 AllowAddtionalProperties = true ,在我的架构中打印了无数次。我怎样才能关闭它??
    • @immy_keen 对拒绝接受答案表示诚挚的歉意。一旦我们也处理了异常消息,我稍后会接受它。
    • @ashutoshrina: Properties 计数为 0 的模式对我来说正确序列化。您能否提供有关您使用的架构/生成架构的类型的更多详细信息?
    猜你喜欢
    • 1970-01-01
    • 2010-10-02
    • 1970-01-01
    • 1970-01-01
    • 2015-05-06
    • 1970-01-01
    • 2017-03-07
    • 2017-05-26
    相关资源
    最近更新 更多