Home >Backend Development >C++ >How to Efficiently Create C# DTOs from Complex JSON Responses in ASP.NET?
In ASP.NET applications, it is often necessary to extract complex JSON response data into DTO (Data Transfer Object). With tools like RestSharp, getting JSON data from APIs is relatively easy, but creating DTOs from complex responses is still a challenge.
Assume the following JSON response:
<code class="language-json">{ "response": { "result": { "Leads": { "row": [ { "no": "1", "FL": [ { "val": "LEADID", "content": "101" }, { "val": "Company", "content": "Test 1" } ] }, { "no": "2", "FL": [ { "val": "LEADID", "content": "102" }, { "val": "Company", "content": "Test 2" } ] } ] } }, "uri": "/crm/private/json/Leads/getRecords" } }</code>
The goal is to extract the list of Leads from this JSON response as DTO, each DTO contains "LEADID" and "Company" attributes.
Visual Studio provides a convenient function: "Paste JSON as class", which can automatically generate C# classes based on the JSON structure.
Steps:
For the provided JSON response, the following classes will be generated:
<code class="language-csharp">public class Rootobject { public Response response { get; set; } } public class Response { public Result result { get; set; } public string uri { get; set; } } public class Result { public Leads Leads { get; set; } } public class Leads { public Row[] row { get; set; } } public class Row { public string no { get; set; } public FL[] FL { get; set; } } public class FL { public string val { get; set; } public string content { get; set; } }</code>
Now that we have a C# class, we can define our LeadDto class:
<code class="language-csharp">public class LeadDto { public string LeadId { get; set; } public string Company { get; set; } }</code>
In order to populate the LeadDto list based on the JSON response, you can use LINQ:
<code class="language-csharp">var leads = from response in Rootobject.response.result.Leads.row select new LeadDto { LeadId = response.FL.First(fl => fl.val == "LEADID").content, Company = response.FL.First(fl => fl.val == "Company").content };</code>
This query will create a list of LeadDto objects, each containing the "LEADID" and "Company" properties extracted from the JSON response.
The above is the detailed content of How to Efficiently Create C# DTOs from Complex JSON Responses in ASP.NET?. For more information, please follow other related articles on the PHP Chinese website!