我目前正在学习Knockout,我有这样的要求:对API的Ajax调用返回一个具有这种结构的JSON编码对象
DocInfo {
CustomerInfo {
Name,
Adress,
XXXXXX
},
ProductInfo, {
Name,
Price
},
ThirdParty {
Property1,
Property2
},
Whatever {
Property1,
Property2,
Property2
}
}
我正在创建可序列化的C#类作为DTO,但我不确定如何在C#类上进行此操作以返回到所需对象结构的客户端。
任何帮助将不胜感激!谢谢!
答案 0 :(得分:3)
您还可以使用Newtonsoft.JSON获得正确的结果:
<强>结果强>
{"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;}
}
答案 1 :(得分:1)
这是一个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"}}
您可以根据需要进行扩展。
如果这不是你需要的,请告诉我。