Home >Backend Development >C++ >How to Deserialize Nested JSON with Dynamic Keys into C# Classes?

How to Deserialize Nested JSON with Dynamic Keys into C# Classes?

Barbara Streisand
Barbara StreisandOriginal
2025-01-19 21:51:11389browse

How to Deserialize Nested JSON with Dynamic Keys into C# Classes?

Deserialize nested JSON to C# class

Deserialize the JSON response into a C# class. The key is to match the class structure with the entire JSON data. Here is the solution on how to deserialize the given JSON:

JSON structure:

<code>{
    "results": {
        "jobcodes": {
            "1": { ... },
            "2": { ... },
            ...
        }
    }
}</code>

Question:

You are not taking into account the dynamic keys ("1" and "2") in the nested "jobcodes" object.

Solution:

To handle objects with dynamic keys, use Dictionary<string, JobCode>:

<code class="language-csharp">class Results
{
    [JsonProperty("jobcodes")]
    public Dictionary<string, JobCode> JobCodes { get; set; }
}</code>

Complete class structure:

<code class="language-csharp">class RootObject
{
    [JsonProperty("results")]
    public Results Results { get; set; }
}

class JobCode
{
    [JsonProperty("_status_code")]
    public string StatusCode { get; set; }
    [JsonProperty("_status_message")]
    public string StatusMessage { get; set; }
    [JsonProperty("id")]
    public string Id { get; set; }
    [JsonProperty("name")]
    public string Name { get; set; }
}</code>

Deserialization:

Deserialize JSON to RootObject class:

<code class="language-csharp">RootObject obj = JsonConvert.DeserializeObject<RootObject>(jsonResponse);</code>

Result:

You can get obj.Results.JobCodes.Values by visiting List<JobCode>. Each JobCode will have corresponding attribute value from JSON.

The above is the detailed content of How to Deserialize Nested JSON with Dynamic Keys into C# Classes?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn