从类中获取JSON数据成员

时间:2015-07-17 06:40:13

标签: c# .net json rest

我有从JSON生成的类,如下所示:

[DataContract]
public class Issue
{
    [DataMember(Order = 0)]
    public string expand { get; set; }
    [DataMember(Order = 1)]
    public string id { get; set; }
    [DataMember(Order = 2)]
    public string self { get; set; }
    [DataMember(Order = 3)]
    public string key { get; set; }
}

[DataContract]
public class search
{
    [DataMember(Order = 0)]
    public string expand { get; set; }
    [DataMember(Order = 1)]
    public int startAt { get; set; }
    [DataMember(Order = 2)]
    public int maxResults { get; set; }
    [DataMember(Order = 3)]
    public int total { get; set; }
    [DataMember(Order = 4)]
    public IList<Issue> issues { get; set; }
}

我想访问&#34; id&#34;而且我试图像这样检索:

jiraIssues.IssueKey = item.issues.key ?? string.Empty; 

收到错误&#34;不包含&#34;键&#34;的定义。请检查程序集参考

&#34;项目&#34;我好像在下面:

foreach (search item in issuesearched)
{
    JiraIssues jiraissues = new JiraIssues();
    SetIssueDetails(item, jiraissues, priorities, statuses, resolution, issuetypes);
}

有没有其他方法可以访问&#34; key&#34; ?我有什么问题,我出错了?

1 个答案:

答案 0 :(得分:1)

问题是一个列表 所以你必须这样做:

s.issues [0]的.key;

(如果要设置第一个元素的键。 不为其他元素设置键;)

其他样本:

public class Issue
{                          
    public string key { get; set; }
}


public class search
{
    public IList<Issue> issues { get; set; }
}

private static void Main(string[] args) {

    search s = new search();

    s.issues.Add(new Issue()); // YOU HAVE THREE ISSUES
    s.issues.Add(new Issue());
    s.issues.Add(new Issue());


    var x=s.issues[0].key; // YOU ACCESS 1st one
    x = s.issues[2].key; // YOU ACCESS 3rd one (zero based)


}