Home >Backend Development >C++ >How Can I Deserialize Nested JSON Objects to Extract a List of Job Codes?

How Can I Deserialize Nested JSON Objects to Extract a List of Job Codes?

DDD
DDDOriginal
2025-01-19 22:11:17562browse

How Can I Deserialize Nested JSON Objects to Extract a List of Job Codes?

Handling deserialization of nested JSON objects

In your code, you are having trouble deserializing JSON data that contains nested objects. This guide will address this issue and provide a solution for getting a list of job codes from the provided JSON.

Inconsistent class structure

Initially, you try to deserialize the entire JSON response into a single JobCode class, ignoring that there are multiple job codes under the "jobcodes" key. To solve this problem, we need to create classes that match the JSON structure.

Use a dictionary to handle variable keys

The keys for the "jobcodes" attribute in JSON are string values ​​("1" and "2" in your example). To accommodate this variability, we use Dictionary<string, JobCode> instead of simply List<JobCode>. This dictionary allows us to retrieve job codes using their respective keys.

Updated class structure

The following is the modified class structure aligned with JSON:

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

public class Results
{
    [JsonProperty("jobcodes")]
    public Dictionary<string, JobCode> JobCodes { get; set; }
}

public 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>

Updated Deserialization

With these classes, you can deserialize JSON using the following code:

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

This will populate the obj variable with the deserialized JSON data, allowing you to access the list of job codes via obj.Results.JobCodes.

The above is the detailed content of How Can I Deserialize Nested JSON Objects to Extract a List of Job Codes?. 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