C# 验证JSON中键值对中的值
我需要根据可用的格式验证JSON。示例JSON如下所示:C# 验证JSON中键值对中的值,c#,.net,json,C#,.net,Json,我需要根据可用的格式验证JSON。示例JSON如下所示: { "sno": "1", "project_name": "Abcd", "contributors": [ { "contributor_id": "1", "contributor_name": "Ron" }, { "contributor_id": "2", "contributor_name": "Dan" } ],
{
"sno": "1",
"project_name": "Abcd",
"contributors": [
{
"contributor_id": "1",
"contributor_name": "Ron"
},
{
"contributor_id": "2",
"contributor_name": "Dan"
}
],
"office": [ "Vegas", "New York" ]
}
在上面的示例中,我需要验证JSON,如下所示:
{
"sno": "1",
"project_name": "Abcd",
"contributors": [
{
"contributor_id": "1",
"contributor_name": "Ron"
},
{
"contributor_id": "2",
"contributor_name": "Dan"
}
],
"office": [ "Vegas", "New York" ]
}
- sno的值必须是字符串
- office的值必须是有效数组
- contrbutors的值必须是一个有效数组,其中包含有效的JSON作为成员
如何解析JSON并根据上述标准检查所有键是否具有有效值 您需要这样的对象:
public class MyObject
{
public string sno { get; set; }
public string project_name { get; set; }
public List<Contrbutor> contrbutors { get; set; }
public List<string> office { get; set; }
}
public class Contrbutor
{
public string contributor_id { get; set; }
public string contributor_name { get; set; }
}
公共类MyObject
{
公共字符串sno{get;set;}
公共字符串项目名称{get;set;}
公共列表控制器{get;set;}
公共列表办公室{get;set;}
}
公共类控制器
{
公共字符串贡献者_id{get;set;}
公共字符串参与者名称{get;set;}
}
通过JsonConvert进行Pars it
try
{
MyObject desObject = JsonConvert.DeserializeObject<MyObject>(yourJsonStringHere);
}
catch(Exception ex)
{
//IF PARSE IS NOT SUCCESSFUL CATCH THE PARSE EX HERE
}
试试看
{
MyObject desObject=JsonConvert.DeserializeObject(YourJSonString);
}
捕获(例外情况除外)
{
//如果解析不成功,请在此处捕获解析表达式
}
如果解析成功,则验证“desObject”值。您可以构建自定义函数来检查json中各个键的值的数据类型 1) 将json解析为 2) 将此
JObject
映射到您的SampleClass
3) 然后,通过使用,您可以验证各个键的特定值是否属于字符串
或数组
或对象
类型
public string ValidateJson(string json)
{
JObject jObject = JObject.Parse(json);
SampleClass model = jObject.ToObject<SampleClass>();
string response = string.Empty;
foreach (var i in model.data)
{
switch (i.Key)
{
case "sno":
if (i.Value.Type != JTokenType.String)
response = "SNo is not a string";
break;
case "project_name":
if (i.Value.Type != JTokenType.String)
response = "Project name is not a string";
break;
case "contributors":
if (i.Value.Type != JTokenType.Array)
response = "Contributors is not an array";
break;
case "office":
if (i.Value.Type != JTokenType.Array)
response = "Office is not an array";
break;
}
}
return response;
}
这听起来像是一个XY问题,为什么有人要编写一个api来更改json的类型?如果您只想验证数据类型,那么您可以简单地将其反序列化到类中,并检查它是否失败。@TheGeneral我不需要更改json的类型。我需要验证JSON的格式是否正确,这不是我真正想要的。但是,您可以根据一个好的JSON验证JSON。我试图用JsonTextReader来实现这一点,但您的解决方案要简单一点。如果“sno”:1表示整数1而不是字符串1,那么您的代码不转到catch表示没有对string的数据类型进行验证是否可以获取catch块中存在数据类型不匹配的键的名称?