[英]Validate values in key value pair in a JSON
我需要針對可用格式驗證JSON。 JSON示例如下:
{
"sno": "1",
"project_name": "Abcd",
"contributors": [
{
"contributor_id": "1",
"contributor_name": "Ron"
},
{
"contributor_id": "2",
"contributor_name": "Dan"
}
],
"office": [ "Vegas", "New York" ]
}
在上面的示例中,我需要如下驗證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; }
}
通過JsonConvert解析
try
{
MyObject desObject = JsonConvert.DeserializeObject<MyObject>(yourJsonStringHere);
}
catch(Exception ex)
{
//IF PARSE IS NOT SUCCESSFUL CATCH THE PARSE EX HERE
}
如果解析成功,則驗證“ desObject”值。
您可以構建自定義函數來檢查json中各個鍵的值的數據類型。
1)將json解析為JObject
2)將此JObject
到您的SampleClass
。
3)然后,通過使用JTokenType
您可以驗證各個鍵的特定值是否為string
或array
或object
類型。
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;
}
您的SampleClass
將是
class SampleClass
{
[JsonExtensionData]
public Dictionary<string, JToken> data { get; set; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.