简体   繁体   中英

C# JSON.Net Iterate through Given JSON

I am in a struggle, I am new at C#, I have read already many ways to retrieve a JSON string, but the one I have been given is not in any example, so please help.

This is the JSON I get:

{
"projects": {
    "0": {
        "projectId": "3",
        "title": "Project Title",
        "excerpt": "Far Far Away from somewhere it was a place where blah blah blah",
        "date": "11/04/2018"
    },
    "2": {
        "projectId": "17",
        "title": "New Project Title",
        "excerpt": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula....",
        "date": "25/06/2018"
    },
    "3": {
        "projectId": "18",
        "title": "Another Project Title",
        "excerpt": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo\n ligula eget...",
        "date": "06/07/2018"
    }
}

I have this class (not sure if it is ok)

public class PeopleProjects
{
    public List<string> Projects { get; set; }
    public string Id { get; set; }
    public string Title { get; set; }
    public string Excerpt { get; set; }
    public string PublishedDate { get; set; }

}

Should I use a loop like foreach? if so, how? also, please notice that each project is inside a dynamic number, which can be any number, it is really driving me crazy, please help

Thanks!

It looks to me like you should have:

public class ProjectCollection
{
    [JsonProperty("projects")]
    public Dictionary<string, Project> Projects { get; set; }
}

public class Project
{
    [JsonProperty("projectId")]
    public string Id { get; set; }

    [JsonProperty("title")]
    public string Title { get; set; }

    [JsonProperty("excerpt")]
    public string Excerpt { get; set; }

    [JsonProperty("date")]
    public DateTime PublishedDate { get; set; }
}

You can then use:

var collection = JsonConvert.DeserializeObject<ProjectCollection>(json);
foreach (var project in collection.Projects.Values)
{
    // Use project.Id etc
}

The ProjectCollection class corresponds to your "root" object - it expects a projects property in the JSON, and then treats each property within projects as an entry in the dictionary. In the foreach loop above I've ignored the key, but you could always use:

foreach (var pair in collection.Projects)
{
    Console.WriteLine($"{pair.Key}: {pair.Value.Id}");
}

That would print:

0: 3
1: 17
2: 18

with your sample data, for example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM