Deserialize JSON subdocument

走远了吗. 提交于 2019-12-31 04:08:06

问题


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:


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>>();


来源:https://stackoverflow.com/questions/32454483/deserialize-json-subdocument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!