首頁 > 後端開發 > C++ > 如何在 ASP.NET 中從複雜的 JSON 回應高效能建立 C# DTO?

如何在 ASP.NET 中從複雜的 JSON 回應高效能建立 C# DTO?

Barbara Streisand
發布: 2025-01-12 12:27:43
原創
247 人瀏覽過

How to Efficiently Create C# DTOs from Complex JSON Responses in ASP.NET?

在ASP.NET應用程式中,經常需要將複雜JSON回應資料擷取為DTO(資料傳輸物件)。透過RestSharp等工具,從API取得JSON資料已相對簡易,但從複雜回應中建立DTO仍然是一項挑戰。

從JSON回應中提取Leads作為DTOs

假設以下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"
  }
}
登入後複製

目標是從該JSON回應中提取Leads清單作為DTO,每個DTO包含"LEADID"和"Company"屬性。

解決方案:利用JSON產生C#類別

Visual Studio提供了一個方便的功能:“貼上JSON作為類別”,可以根據JSON結構自動產生C#類別。

步驟:

  1. 複製JSON回應。
  2. 在Visual Studio中,依序選擇「編輯」>「特殊貼上」>「貼上JSON作為類別」。
  3. 這將產生代表JSON結構的C#類別。

對於提供的JSON回應,將產生以下類別:

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; }
}
登入後複製

建立LeadDto類別

現在我們有了C#類,可以定義我們的LeadDto類:

public class LeadDto
{
    public string LeadId { get; set; }
    public string Company { get; set; }
}
登入後複製

填入LeadDto列表

為了根據JSON回應填入LeadDto列表,可以使用LINQ:

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
            };
登入後複製

此查詢將建立一個LeadDto物件的列表,每個物件都包含從JSON回應中提取的"LEADID"和"Company"屬性。

以上是如何在 ASP.NET 中從複雜的 JSON 回應高效能建立 C# DTO?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板