Deserialize JSON subdocument

2019-02-27 18:53发布

I'm calling the JIRA Rest API to recieve a list of Worklog Objects.

The JSON I recieve looks like.

{
"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"
    }
]
}

As I said, I want to put it in a list.

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

It doesn't work, because of

"startAt": 0,
"maxResults": 1,
"total": 1,

How can I make the deserializer ignore those properties? Thanks for your help!

1条回答
乱世女痞
2楼-- · 2019-02-27 19:20

Either create a "RootObject" class that does contain the properties:

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

And deserialize into that:

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

Or step into the parsed JSON and deserialize from there:

JObject o = JObject.Parse(json);
JToken worklogsJson = o.SelectToken("worklogs");
var worklogs = worklogsJson.ToObject<List<Worklog>>();
查看更多
登录 后发表回答