Skip to main content
 首页 » 编程设计

c#之为 Ajax 创建分层 DTO 类

2024年02月06日30落叶无声

我目前正在学习 Knockout,我有这样的要求,即对 API 的 Ajax 调用返回具有此结构的 JSON 编码对象

DocInfo { 
   CustomerInfo { 
      Name, 
      Adress, 
      XXXXXX 
   }, 
   ProductInfo, { 
       Name, 
       Price 
   }, 
   ThirdParty { 
       Property1, 
       Property2 
   }, 
   Whatever { 
       Property1, 
       Property2, 
       Property2 
   } 
} 

我正在创建可序列化的 C# 类作为 DTO,但我不确定如何在 C# 类上处理此问题以便返回到客户端所需的对象结构。

任何帮助将不胜感激!谢谢!

请您参考如下方法:

您也可以使用 Newtonsoft.JSON 获得正确的结果:

工作 .Net Fiddle

结果

{"CustomerInfo":{"Name":"A","Adress":"B"},"ProductInfo":{"Name":"A","Price":"1"},"Whatever":{"Property1":"1","Property2":"2"}} 

C#

using System; 
using System.Collections.Generic; 
using System.Linq; 
using Newtonsoft.Json;  
 
public class Program 
{ 
 
    public static void Main() 
    { 
        var info = new DocInfo(){ 
            CustomerInfo = new CustomerInfo(){Name = "A", Adress = "B"}, 
            ProductInfo = new ProductInfo(){Name = "A", Price = "1"}, 
            Whatever = new Whatever(){Property1 = "1", Property2 = "2"}  
        }; 
        var output =  JsonConvert.SerializeObject(info); 
        Console.WriteLine(output); 
    } 
} 
 
public class DocInfo{ 
    public CustomerInfo CustomerInfo{get;set;} 
    public ProductInfo ProductInfo{get;set;} 
    public Whatever Whatever{get;set;} 
} 
 
public class CustomerInfo{ 
    public string Name{get;set;} 
    public string Adress{get;set;} 
 
} 
 
 
public class ProductInfo{ 
    public string Name{get;set;} 
    public string Price{get;set;} 
 
} 
 
 
public class Whatever{ 
    public string Property1{get;set;} 
    public string Property2{get;set;} 
 
}