获取对象中不同值的数量

时间:2018-12-13 16:14:08

标签: c# json visual-studio winforms

当我通过API进行网络调用时,它会显示一个JSON文件。我选择所需的某些数据没有问题。对于这个项目,我们不想这样做。我们希望获得状态为1的任何结果并显示该计数。

        List<stats> ls = new List<stats>();
        ls = rClient.makeRequest(txtURL1.Text);

        listBox1.DataSource = ls;
        listBox1.DisplayMember = "fullResult";

        var url = ls[1].ID;
        string access = ls[1].FirstAccessed;
        string endAccess = ls[1].LastAccessed;
        string count = ls.Count.ToString();
        string status = ls[int.Parse(count)- 1].Status;
        string intCon = url.ToString();
        dataOutput.Text = intCon + " " + access + " " + endAccess + "  " + count + " " + status;

如您所见,我选择了JSON文件的不同部分。我确实尝试尝试获取一些信息,但是结果并不理想。为此,我需要一些指导。刚刚开始使用C#。

ListBox显示来自API的所有内容,所以我有点想读取所有数据并以这种方式提取单独的状态代码。

JSON输出

[
    {
    "ID": 502,
    "WorkflowID": "5b7ac3e66eb51a0dcc287f84",
    "WorkflowName": "I9 Approval",
    "EngineID": null,
    "FilePages": null,
    "PortalID": 0,
    "Permissions": 0,
    "ProcessActions": null,
    "SSDocument": {
        "SSDBID": 1002,
        "SSArchiveID": 1,
        "SSDocumentID": 164
    },
    "LastAccessed": "2018-11-28T17:34:38.843Z",
    "FirstAccessed": "2018-11-28T17:34:38.843Z",
    "Status": 3, **<--- Want to read this here.**
    "CurrentNode": "-7",
    "Wait": 0,
    "WaitStart": "0001-01-01T00:00:00Z",
    "Queue": null,
    "Properties": [

在此处解析JSON:

    public List<stats> makeRequest(string endPoint)
    {

        string strResponseVlaue = string.Empty;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(endPoint);
        request.Method = httpMethod.ToString();
        request.Method = "GET";
        request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("SSAdministrator:Password!"));
        HttpWebResponse response = request.GetResponse() as HttpWebResponse;



        {
            if (response.StatusCode != HttpStatusCode.OK)
            {
                throw new ApplicationException("Error Code: "+ response.StatusCode.ToString());
            }
            //Process the response stream

        using (Stream responseStream = response.GetResponseStream())
            {
                if(responseStream != null)
                {
                    using(StreamReader reader = new StreamReader(responseStream))
                    {
                        strResponseVlaue = reader.ReadToEnd();
                    }
                }
            } //End of Response Stream
        }// End Of Using Reponse

        var obj = JsonConvert.DeserializeObject<List<stats>>(strResponseVlaue);
        return obj;

API还提供了47个其他结果。

1 个答案:

答案 0 :(得分:1)

如果statusstats对象的属性,并且在反序列化JSON后得到List<stats>,则计数如下:

using System.Linq;

var statusOneCount = ls.Count(i=>i.status == 1);