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

时间:2014-09-26 13:58:07

标签: c# json api ontime

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

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

custom_170

custom_171

custom_172

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

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

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

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

我可以从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:

1 个答案:

答案 0 :(得分:2)

分配了{p> defectWAS两次,而defectWJ未分配新值

你可能意味着:

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