我有一个json文件:
{
"rowId": "39",
"refNumber": "19",
"title": "Mobile",
"date": "10/29/2015",
"status": "saved"
}{
"rowId": "10",
"refNumber": "478",
"title": "Completion",
"date": "10/30/2015",
"status": "saved"
}{
"rowId": "11",
"refNumber": "604",
"title": "Online Order",
"date": "10/30/2015",
"status": "failed"
}
我想要做的是使用winforms app在c#中查询json文件:
string qrySaved = "select count(*) as total from file where status = 'saved'";
string qryFailed = "select count(*) as total from file where status = 'failed'";
然后将结果放在两个变量中。
我做了以下事情:
logFolder = Directory.GetCurrentDirectory();
logFolder = logFolder.Replace("\\bin\\Debug", "\\metrics");
logFile = logFolder + @"\log.json";
我正在使用Newtonsoft.Json nuget资源并知道如何读取第一个对象,但无法弄清楚如何查询文件以返回基于给定元素的总计数。
答案 0 :(得分:1)
您可以尝试这样的事情:
static void Main(string[] args)
{
string json = File.ReadAllText("sample1.json");
var array = JArray.Parse(json);
int savedcount = array.Count(i => i["status"].Value<string>() == "saved");
int failedcount = array.Count(i => i["status"].Value<string>() == "failed");
}
可能是拼写错误,但发布的JSON无效,所以我将其更改为如下所示:
[
{
"rowId": "39",
"refNumber": "19",
"title": "Mobile",
"date": "10/29/2015",
"status": "saved"
},
{
"rowId": "10",
"refNumber": "478",
"title": "Completion",
"date": "10/30/2015",
"status": "saved"
},
{
"rowId": "11",
"refNumber": "604",
"title": "Online Order",
"date": "10/30/2015",
"status": "failed"
}
]