代码无法从JSON中找到特定值

本文关键字:JSON 代码 | 更新日期: 2023-09-27 18:24:43

我使用C#对axosoft的软件调用OnTime进行api调用。

我在客户端创建了三个自定义字段:

客户_170

客户_171

客户_172

每个字段都被添加到JSON调用"custom_fields"中的一个部分。OnTime提供了一个他们自己的API包装器,可以轻松使用他们的代码。

在下面的C#代码中,我使用get从"缺陷"中提取JSON,然后循环查找缺陷编号7。

如果找到数字7,它将从JSON Id、Name、custom_170、custom_171和custom_172中提取5个值。

我遇到的问题是,我的程序找到了Id、Name、custom_170,但查找custom_171的if语句从custom_172获得了值,最后一个if似乎从未被触摸过(请参阅下面的结果)。

如何从custom_171和custom_172中获取值,并将它们放在正确的位置?

JSON(片段)

{
    "data": {
        "reported_date": "2014-09-25T04:00:00Z",
        "percent_complete": 100,
        "archived": false,
        "publicly_viewable": false,
        "completion_date": null,
        "due_date": null,
        "description": "",
        "name": "Defect Created from API Explorer 3",
        "notes": "",
        "number": "7",
        "custom_fields": {
            "custom_171": "Work Around Steps",
            "custom_172": "Work Journal",
            "custom_170": "Analysis"
        }
    }
}

C#代码

        var DefectInfo = axosoftClient.Defects.Get();
        int? defectID = 0;
        string defectName = "";
        string defectAnalysis = "";
        string defectWAS = "";
        string defectWJ = "";
        foreach (var defect in DefectInfo.Data)
        {
            if(defect.Id == 7)
            {
                defectID = defect.Id;
                defectName = defect.Name;
                if(defect.CustomFields.ContainsKey("custom_170"))
                {
                    defectAnalysis = (string)defect.CustomFields["custom_170"];
                }
                if(defect.CustomFields.ContainsKey("custom_171"))
                {
                    defectWAS = (string)defect.CustomFields["custom_171"];
                }
                if (defect.CustomFields.ContainsKey("custom_172"))
                {
                    defectWAS = (string)defect.CustomFields["custom_172"];
                }
            } 
        }
        Console.WriteLine("Defect ID: {0} Defect Name: {1}'nAnalysis: {2} 'nWork Around: {3}'nWork Journal: {4}'n'n", defectID, defectName, defectAnalysis, defectWAS, defectWJ);

结果

Defect ID: 7 Defect Name: Defect Created from API Explorer 3
Analysis: Analysis
Work Around: Work Journal
Work Journal:

代码无法从JSON中找到特定值

defectWAS被分配两次,而defectWJ没有被分配新值

你的意思可能是:

if (defect.CustomFields.ContainsKey("custom_172"))
{
    defectWJ = (string)defect.CustomFields["custom_172"];
}