验证JSON

时间:2018-11-05 10:53:09

标签: c# .net 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" ]
}

在上面的示例中,我需要如下验证J​​SON:

  • sno 的值必须是字符串。
  • office 的值必须是有效的数组。
  • contrbutors 的值必须是带有有效JSON作为成员的有效数组。

如何根据上述条件解析JSON并检查所有键是否都具有有效值?

2 个答案:

答案 0 :(得分:1)

您需要这样的对象:

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”值。

答案 1 :(得分:1)

您可以构建自定义函数来检查json中各个键的值的数据类型。

1)将您的json解析为JObject

2)将此JObject映射到您的SampleClass

3)然后,使用JTokenType可以验证各个键的特定值是否为stringarrayobject类型。

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; }
}