Home > Backend Development > C++ > How to Easily Convert Complex JSON Responses into C# DTOs?

How to Easily Convert Complex JSON Responses into C# DTOs?

Patricia Arquette
Release: 2025-01-12 12:41:44
Original
584 people have browsed it

How to Easily Convert Complex JSON Responses into C# DTOs?

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:

  1. Copy the JSON response.
  2. In Visual Studio, navigate to Edit >Paste Special >Paste JSON As Class.
  3. Visual Studio will generate a series of classes that represent the JSON structure, including:
<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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template