反序列化JSON子文档

时间:2015-09-08 09:46:49

标签: c# json api rest serialization

我正在调用JIRA Rest API来接收Worklog对象列表。

我收到的JSON看起来像。

{
"startAt": 0,
"maxResults": 1,
"total": 1,
"worklogs": [
    {
        "self": "http://www.example.com/jira/rest/api/2/issue/10010/worklog/10000",
        "author": {
            "self": "http://www.example.com/jira/rest/api/2/user?username=fred",
            "name": "fred",
            "displayName": "Fred F. User",
            "active": false
        },
        "updateAuthor": {
            "self": "http://www.example.com/jira/rest/api/2/user?username=fred",
            "name": "fred",
            "displayName": "Fred F. User",
            "active": false
        },
        "comment": "I did some work here.",
        "visibility": {
            "type": "group",
            "value": "jira-developers"
        },
        "started": "2015-08-25T07:43:10.086+0000",
        "timeSpent": "3h 20m",
        "timeSpentSeconds": 12000,
        "id": "100028"
    }
]
}

正如我所说,我想把它放在一个清单中。

var json = client.MakeRequest("", password, user);
List<Worklog> myList = JsonConvert.DeserializeObject<List<Worklog>>(json);

由于

,它无法正常工作
"startAt": 0,
"maxResults": 1,
"total": 1,

如何让反序列化器忽略这些属性? 谢谢你的帮助!

1 个答案:

答案 0 :(得分:1)

创建一个包含属性的“RootObject”类:

public class RootObject 
{
    public int startAt { get; set; }
    public int maxResults { get; set; }
    public int total { get; set; }
    public List<Worklog> worklogs { get; set; }
}

反序列化:

var rootObject = JsonConvert.DeserializeObject<RootObject>(json);
// access rootObject.worklogs

或者进入已解析的JSON并从那里反序列化:

JObject o = JObject.Parse(json);
JToken worklogsJson = o.SelectToken("worklogs");
var worklogs = worklogsJson.ToObject<List<Worklog>>();