【问题标题】:How can I turn a JSON into a C# Dictionary?如何将 JSON 转换为 C# 字典?
【发布时间】:2011-12-18 22:06:15
【问题描述】:

我有以下 JSON:

validate = {
    '(\\.org|\\.info|\\.biz|\\.name)$': [
        { 'type': 'size', 'pattern': /^.{3,64}$/, 'error': 'Your domain can have at max 26 characters and at least 3.' }
    ],
    '.*': [
        { 'type': 'general', 'pattern': /^[^\.-].*[^\.-]$/, 'message': 'Your domain name shouldn\'t contain . or - at the beginning or the end.' },
        { 'type': 'characters', 'pattern': /^[abcdefghijklmnopqrstwuvxyz0123456789]+$/, 'error': 'Your domain can have at max 26 characters and at least 3.' }
    ]
};

并尝试像这样使用:

var validate = new Dictionary<string, dynamic> {
    {
        @"(\.org|\.info|\.biz|\.name)$",
        new {
            Type = "size",
            Pattern = @"^.{3,64}$",
            Message = "Your domain can have at max 26 characters and at least 3."
        }
    }
};

动态对象的键是域扩展的正则表达式模式,Pattern 键中的正则表达式应该与域名匹配。

但我不知道如何将 2 个验证类型放入 Dictionarydynamic 部分。

以前有没有人做过类似的事情,或者这很愚蠢,我应该以另一种方式做?

这样做的目的是我可以将字典序列化为 Json。

【问题讨论】:

  • 你想要完成什么?
  • 我正在尝试用它创建一个自定义数据注释,然后我想使用 asp-net-mvc3 将字典中的内容作为 Json 发送到视图,这样我就可以使用验证规则C# 代码和每次我们更改 C# 验证时,客户端都会跟随。

标签: c# javascript json asp.net-mvc-3 dictionary


【解决方案1】:

如果您尝试为 MVC 站点执行此操作,我认为您应该查看 custom validation,并让运行时为您处理管道。这个question 讨论了如何实现自定义的RegularExpressionAttribute,似乎在这里。

【讨论】:

  • 我非常擅长自定义验证,特别是如果它是 mvc3,无论您的链接来自 mvc2,我认为它们没有太大区别。 This 在将正则表达式验证作为序列化 Json 发送到视图时,问题无法解决我的问题。
  • 看起来您正在尝试验证正则表达式,不是吗?
  • 我正在尝试使用正则表达式进行验证,但我需要在字典中,因为我想在之后对其进行迭代。
【解决方案2】:

我尝试在字典的动态部分使用List&lt;dynamic&gt;

var validate = new Dictionary<string, List<dynamic>> {
    {
        "(\\.org|\\.info|\\.biz|\\.name)$",
        new List<dynamic>
        {
            new {
                Type = "size",
                Pattern = @"^.{3,64}$",
                Message = "Your domain can have at max 26 characters and at least 3."
            }
        }
    },
    {
        ".*",
        new List<dynamic>
        {
            new {
                Type = "general",
                Pattern = @"^[^\.-].*[^\.-]$",
                Message = "Your domain name shouldn\'t contain . or - at the beginning or the end."
            },
            new {
                Type = "characters",
                Pattern = @"^[abcdefghijklmnopqrstwuvxyz0123456789]+$",
                Message = "Your domain name should contain only alphanumeric characters."
            }
        }
    }
};

并使用来自JsonResult mvc3 视图的Json 它返回了我需要的json。

【讨论】:

  • 你也可以做 Dictionary>
  • 这也是一个很好的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-01
  • 2018-07-04
  • 2014-12-31
  • 1970-01-01
  • 1970-01-01
  • 2013-02-14
相关资源
最近更新 更多