[英]Custom Json response from web api
I am working on ASP .Net web api project where we are giving response of a custom object. 我正在研究ASP .Net Web api项目,我们在其中提供自定义对象的响应。 JsonFormatter formats the data to a json object when api is exposed in fiddler. 当api在小提琴手中公开时,JsonFormatter将数据格式化为json对象。 Here is the skeleton of our application. 这是我们应用程序的框架。
Data Objects 数据对象
public class CustomData
{
public Records MRecord {get;set;}
public string ResponseCode {get;set;}
public string Status {get;set;}
}
public class Records
{
Public class FirstName {get;set;}
Public class LastName {get;set;}
}
Response 响应
CustomData : {
MRecord : [
{
FirstName : "1stName",
LastName : "",
},
{
FirstName : "2Name",
LastName : "",
},
],
ResponseCode : "0",
Status: "Success"
}
And the expected format is like 预期的格式像
CustomData : {
MRRecordList : {
MRecord :
{
FirstName : "1stName",
LastName : "",
},
MRecord :
{
FirstName : "2Name",
LastName : "",
}
},
ResponseCode : "0",
Status: "Success"
}
Considering the array objects aren't split and shown as a single entity by the JsonFormatter. 考虑到数组对象没有被JsonFormatter拆分并显示为单个实体。 Please help me if there is any solution to achieve this. 如果有解决方案,请帮助我。
Following is the code / model you need: 以下是您需要的代码/模型:
void Main()
{
var c = new CustomData()
{
MRecordList = new List<UserQuery.Record>
{
new Record{FirstName="A",LastName="B"},
new Record{FirstName="C",LastName="D"}
},
ResponseCode = "0",
Status = ""
};
JsonConvert.SerializeObject(c).Dump();
}
public class CustomData
{
public List<Record> MRecordList { get; set; }
public string ResponseCode { get; set; }
public string Status { get; set; }
}
public class Record
{
public string FirstName { get;set;}
public string LastName { get;set;}
}
This will yield the following Json: 这将产生以下Json:
{
"MRecordList": [{
"FirstName": "A",
"LastName": "B"
}, {
"FirstName": "C",
"LastName": "D"
}],
"ResponseCode": "0",
"Status": ""
}
In case your requirement is the following Json: 如果您的要求是以下Json:
{
"customData": {
"MRecordList": [{
"FirstName": "A",
"LastName": "B"
}, {
"FirstName": "C",
"LastName": "D"
}],
"ResponseCode": "0",
"Status": ""
}
}
then make following changes to the code: 然后对代码进行以下更改:
public class Test
{
public CustomData customData {get;set;}
}
Test t = new Test{customData = c};
Now serialize t
Remember no root tag in Json as clear from the above examples 从上面的示例可以清楚地记住,Json中没有根标签
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.