Deserialize JSON into nested C# classes
The JSON response retrieved from the REST API contains multiple job code entries nested in a complex structure. Deserializing this data requires a class structure that matches the JSON layout and an appropriate data type to handle the different keys.
First, create a root-level class RootObject
that contains the properties Results
of another class Results
. Results
will contain a JobCodes
named Dictionary<string, JobCode>
, where the string keys are job code identifiers ("1", "2", etc.) and the values are JobCode
objects.
Next, define the JobCode
class whose properties map to JSON values: StatusCode
, StatusMessage
, Id
, and Name
.
To deserialize JSON, use:
<code class="language-csharp">RootObject obj = JsonConvert.DeserializeObject<RootObject>(json);</code>
This will create an instance of RootObject
which you can then access to retrieve a list of job codes like this:
<code class="language-csharp">List<JobCode> jobCodes = obj.Results.JobCodes.Values.ToList();</code>
The above is the detailed content of How to Deserialize Nested JSON into C# Classes?. For more information, please follow other related articles on the PHP Chinese website!