JToken不包含'length的定义

时间:2018-06-26 20:28:10

标签: c# asp.net json.net

我在扩展名为.json的文件中包含JSON数据。我抓取并从文件中读取JSON。我的问题是如何检查payment数组是否有任何子代。

我尝试过o2["payment"].length(),但给我一个错误

  

'JToken'不包含'length'的定义,也没有扩展名   接受类型为“ JToken”的第一个参数的方法“长度”可以是   找到(您是否缺少using指令或程序集引用?)

我正在使用Json.NET

{
    "bank_name": "MyBank",
    "payment": [
        {
            "ssn": "123456789",
            "description": "Payment for income tax for 2015",
            "amount": "55.00"
        },
        {
            "ssn": "123456789",
            "description": "Payment for income tax for 2016",
            "amount": "95.10"
        },
        {
            "ssn": "123456789",
            "description": "Payment for income tax for 2017",
            "amount": "35.03"
        }
    ]
}




public ActionResult ReadFile()
{

    var Path = "C:\\Payment";
    var PendingPath = Path + "\\Pending";

    string[] FilePaths = Directory.GetFiles(@PendingPath, "*.json");
    foreach ( var CurrentFile in FilePaths )
    {
        using (StreamReader file = System.IO.File.OpenText(CurrentFile))
        using (JsonTextReader reader = new JsonTextReader(file))
        {
            JObject o2 = (JObject)JToken.ReadFrom(reader);
            var bank_name = o2["bank_name"];
            if ( o2["payment"].length() ) //Check here if payment has any children
            {

            }
        }
    }

    return new EmptyResult();
}

1 个答案:

答案 0 :(得分:3)

如果要使用数组的方法,则应强制转换对象:

if (((JArray)o2["payment"]).Count > 0)
{
    // Logic...
}