Convert complex JSON response to DTO in C# Asp.Net
Original question:
When using RestSharp to receive complex JSON responses, extract a list of DTOs without manual parsing.
Solution:
Leverage Visual Studio’s “Paste Special” feature to automatically generate C# classes from JSON:
<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>
This allows you to access data in the JSON response via generated DTO properties, for example:
<code class="language-csharp">// 假设 response 是 RestSharp 响应对象 var json = response.Content; // 将 JSON 反序列化到 Rootobject 类 Rootobject rootObject = JsonConvert.DeserializeObject<Rootobject>(json); // 访问 Leads 属性 var leads = rootObject.response.result.Leads; // 访问各个 Lead 记录 foreach (var leadRow in leads.row) { var leadId = leadRow.FL[0].content; var company = leadRow.FL[1].content; // 从检索到的数据创建 LeadDto 对象 var leadDto = new LeadDto { LeadId = leadId, Company = company }; }</code>
The above is the detailed content of How to Easily Convert Complex JSON Responses into C# DTOs?. For more information, please follow other related articles on the PHP Chinese website!