【问题标题】:Creating layered DTO class for Ajax为 Ajax 创建分层 DTO 类
【发布时间】:2015-05-05 19:20:39
【问题描述】:

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

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

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

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

【问题讨论】:

  • 您是在尝试维护您在此处描述的 JSON 中的命名空间,还是仅仅为了说明关系?
  • @DavidL 我已经编辑了它,假设它只是为了说明目的。阿隆索,如果那是一个错误,无论如何都要恢复我的编辑。
  • 我正在尝试维护从 c# 到 JSON 的命名空间
  • @AlonsoQuesada 在这种情况下它们会被维护为一个字符串键吗?
  • 正确,它们将是一个字符串键。我正在考虑在主 DocInfo 类中上课,但我不确定这是否可行

标签: c# dto


【解决方案1】:

您也可以使用 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;}

}

【讨论】:

    【解决方案2】:

    这是一个 LinqPad 示例:

    void Main()
    {
        var docInfo = new DocInfo{CustomerInfo = new CustomerInfo{ Name = "Todor", Address = "101 Local Drive", XXXXXX = "YYYYYY" }};
        var docInfoJson = new JavaScriptSerializer().Serialize(docInfo);
        docInfoJson.Dump();
    }
    
    // Define other methods and classes here
    public class DocInfo
    {
        public CustomerInfo CustomerInfo {get;set;}
    }
    
    public class CustomerInfo
    {
        public string Name {get;set;}
        public string Address {get;set;}
        public string XXXXXX {get;set;}
    }
    

    结果:

    {"CustomerInfo":{"Name":"Todor","Address":"101 Local Drive","XXXXXX":"YYYYYY"}}
    

    您可以根据需要对此进行扩展。

    如果这不是您需要的,请告诉我。

    【讨论】:

    • 这就是我所需要的!!非常感谢...(Y)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多