C# 验证包含字典的JSON对象
我正在为.NET项目中的许多对象使用JSON签名,然后验证这些对象以确保它们包含正确数量的参数,等等 但是,我不知道如何验证这个对象,因为“myActions”可以包含不同数量的元素。这个例子只有两个元素,但可能还有几个,甚至只有一个(实际上,它总是在1到5个元素之间) 既然JSON签名可以是五种形式中的一种,那么我该如何对此进行验证?我是否可以将其称为字典并以这种方式进行验证?现在,我使用的是这样的东西(如下)w/a String.Format(因此使用了所有额外的引号和花括号),但我在5个几乎相同的对象中使用了相同的巨型签名,因为我知道myActions将包含1到5个元素。请记住,我无法控制顶部JSON块的格式;我只编写验证程序(如下面的一个)。如果“myActions”是一个数组,这将是一个快照C# 验证包含字典的JSON对象,c#,json,validation,json.net,C#,Json,Validation,Json.net,我正在为.NET项目中的许多对象使用JSON签名,然后验证这些对象以确保它们包含正确数量的参数,等等 但是,我不知道如何验证这个对象,因为“myActions”可以包含不同数量的元素。这个例子只有两个元素,但可能还有几个,甚至只有一个(实际上,它总是在1到5个元素之间) 既然JSON签名可以是五种形式中的一种,那么我该如何对此进行验证?我是否可以将其称为字典并以这种方式进行验证?现在,我使用的是这样的东西(如下)w/a String.Format(因此使用了所有额外的引号和花括号),但我在5个几
""myMetadata"":{{
""myCanvas"":{{
""type"":""object"",
""required"":true,
""properties"":{{
""width"":{{
""type"":""number"",
""required"":true
}},
""height"":{{
""type"":""number"",
""required"":true
}},
""initialScene"":{{
""type"":""string"",
""required"":true
}}
}}
}},
""myActions"":{{
""type"":""object"",
""required"":true,
""properties"":{{
{0}
}}
}},
""otherStuff"":{{
""type"":""object"",
""required"":true,
""properties"":{{
""controlBoard"":{{
""type"":""object"",
""required"":true,
""properties"":{{
""format"":{{
""type"":""array"",
""items"":{{
""type"":""object"",
""properties"":{{
""image"":{{
""type"":""string"",
}},
""x"":{{
""type"":""number"",
}},
""y"":{{
""type"":""number"",
}},
""w"":{{
""type"":""number"",
}},
""h"":{{
""type"":""number"",
}}
}}
}}
}}
}}
}}
}}
}}
}};
是的,这是可行的。一些JSON解析器/反序列化器确实支持两个不同的语法,以便反序列化为强类型字典,如您的示例(即您的第一个JSON片段) 我知道我的 将数据映射到.NET字典的最常见语法包括: 或者
"SomeDictionary": [
{ "Key": "Key1", "Value": "Value1" },
{ "Key": "Key2", "Value": "Value2" },
...
]
或者,更直截了当地说,如您的情况:
"SomeDictionary": {
"Key1": "Value1",
"Key2": "Value2",
...
}
(其中“Value1”、“Value2”等不需要是基元类型,也可以是对象或列表/数组等)
因此,您的目标对象模型(即其类)将类似于以下内容:
public class MyParams
{
public string linkUri { get; set; }
// ...
}
public class MyAction
{
public string type { get; set; }
public string text { get; set; }
public MyParams @params { get; set; }
}
public class MyOuterObject
{
// other properties omitted
public IDictionary<string, MyAction> myActions { get; set; }
// ...
}
公共类MyParams
{
公共字符串linkUri{get;set;}
// ...
}
公共集体诉讼
{
公共字符串类型{get;set;}
公共字符串文本{get;set;}
公共MyParams@params{get;set;}
}
公共类对象
{
//省略了其他属性
公共IDictionary myActions{get;set;}
// ...
}
例如,见:
(示例对象模型)
(对应单元测试)
希望有帮助,
public class MyParams
{
public string linkUri { get; set; }
// ...
}
public class MyAction
{
public string type { get; set; }
public string text { get; set; }
public MyParams @params { get; set; }
}
public class MyOuterObject
{
// other properties omitted
public IDictionary<string, MyAction> myActions { get; set; }
// ...
}