识别属性的值是一个数组

Sta*_*nza 4 c# json json.net

我有一个JSON文件:

{  
   "abn":"63119059513",
   "acn":"119059513",
   "business_structure":"Private Company",
   "ngr_number":"1231231",
   "cbh_number":"1231231",
   "main_name":"Brickworks Building Products Pty Ltd",
   "trading_name":"Brickworks",
   "other_trading_names":"Austral Bricks",
   "directors":[  
      {  
         "ID":"12114",
         "ae_forms_filled_in_ID":"22739",
         "name":"John Smith",
         "dob":"1983-10-29",
         "address_line_1":"123 Fake Street",
         "address_line_2":"",
         "address_line_city":"Fakeland",
         "address_line_postcode":"2000",
         "address_line_state":"New South Wales",
         "address_line_country":"Australia",
         "order_extract_id":null,
         "director_found":null,
         "drivers_lic":"",
         "home_mortgage":"",
         "phone":"",
         "mobile":"",
         "director_email":"",
         "director_title":"Mr",
         "director_position":"Director",
         "dir_pdf_url":null
      }
   ],

}
Run Code Online (Sandbox Code Playgroud)

我想确定任何属性的值是否具有数组结构.到目前为止我能想出的最好的是:

StreamReader streamrr = new StreamReader("C:\\temp\\agfarm_example_udate.json", Encoding.UTF8);

string JSON = streamrr.ReadToEnd();

JObject CWFile = JObject.Parse(JSON);
foreach (JProperty property in CWFile.Properties())
{
    // Do something

    if (property.Value.ToString().Contains("["))
    {
        // Do something with the array
        JArray items = (JArray)CWFile[property.Name];

        foreach (JObject o in items.Children<JObject>())
        {
            foreach (JProperty p in o.Properties())
            {
               // Do something
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

要确定属性值是否有数组,我使用了以下条件:

if (property.Value.ToString().Contains("["))
Run Code Online (Sandbox Code Playgroud)

我只是想知道是否有更好的方法来做这个检查?

dbc*_*dbc 10

一种方法是检查JToken.Type财产.数组类型JTokenType.Array:

if (property.Value.Type == JTokenType.Array)
{
    var items = (JArray)property.Value;

    // Proceed as before.
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以尝试强制转换为JArray:

if (property.Value is JArray)
{
    var items = (JArray)property.Value;

    // Proceed as before.
}
Run Code Online (Sandbox Code Playgroud)

两者都比检查更可取,property.Value.ToString().Contains("[")因为嵌套属性可能具有数组值,从而导致括号出现在ToString()返回的某处.

如果要递归查找具有数组值的每个属性,可以引入扩展方法:

public static class JsonExtensions
{
    public static IEnumerable<JToken> WalkTokens(this JToken node)
    {
        if (node == null)
            yield break;
        yield return node;
        foreach (var child in node.Children())
            foreach (var childNode in child.WalkTokens())
                yield return childNode;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后做:

var CWFile = JToken.Parse(JSON)
var arrayProperties = CWFile.WalkTokens().OfType<JProperty>().Where(prop => prop.Value.Type == JTokenType.Array);
Run Code Online (Sandbox Code Playgroud)