繼DataTable中的數據(「|」就是各自的COL3匹配COL4/COL5分隔符):如何正確創建的Web API一個JSON文件
Col1 Col2 Col3 Col4 Col5
John Doe 12 156-345 792-098
Mike Keller 12|15 145-394|909-203 156-323|121-444,134-232
Hanes Wara 34|12|18 180-655,202-175|123-654|118-000 121-343|654-222|109-220
我現在有這只是顯示一個自定義列表在API調用這樣的數據:
[HttpGet]
public System.Web.Mvc.JsonResult RTData()
{
//...call SQL to retrieve the data and populate the {custom List}
//return...
return new System.Web.Mvc.JsonResult { Data = {custom List} };
}
這是我得到的(在瀏覽器控制檯)當我打電話從JQuery的API的是什麼:
Object
ContentEncoding:null
ContentType:null
Data:Array(12)
[0 … 11]
length:12
__proto__:Array(0)
JsonRequestBehavior:1
MaxJsonLength:null
RecursionLimit:null
__proto__:Object
每個結果的數據是這樣的:
Data:Array(12)
[0 … 11]
0:
Col1: "John"
Col2: "Doe"
Col3: "12"
Col4: "156-345"
Col5: "792-098"
1:
Col1: "Mike"
Col2: "Keller"
Col3: "12|15"
Col4: "145-394|909-203 "
Col5: "156-323|121-444,134-232"
在JSON所需的輸出:
{
"Col1": "John",
"Col2": "Doe",
"Col3Combined": [
{
"Col3": "12",
"Col4Combined": [
{
"Col4": "156-345"
}
],
"Col5Combined": [
{
"Col5": "792-098"
}
]
}
]
},
{
"Col1": "Mike",
"Col2": "Keller",
"Col3Combined": [
{
"Col3": "12",
"Col4Combined": [
{
"Col4": "145-394"
}
],
"Col5Combined": [
{
"Col5": "156-323"
}
]
},
{
"Col3": "15",
"Col4Combined": [
{
"Col4": "909-203"
}
],
"Col5Combined": [
{
"Col5": "121-444",
"Col5": "134-232"
}
]
}
]
}...//more data
如何能夠做到在API調用JSON格式?
類我想出了哪些應該足夠?
public class RootObject
{
public string col1 { get; set; }
public string col2 { get; set; }
public List<col3data> col3 { get; set; }
}
public class col3data
{
public string col3d { get; set; }
public List<col4data> col4d { get; set; }
public List<col5data> col5d { get; set; }
}
public class col4data
{
public string col4 { get; set; } //since col4 can also have comma separated values within each entry, as seen for Hanes, should this be a list too?
}
public class col5data
{
public string col5 { get; set; } //since col5 can also have comma separated values within each entry, as seen for Mike, should this be a list too?
}
像這樣的東西也:
public class RootObject
{
public string col1 { get; set; }
public string col2 { get; set; }
public List<col3data> col3 { get; set; }
}
public class col3data
{
public string col3d { get; set; }
public List<col4data> col4d { get; set; }
public List<col5data> col5d { get; set; }
}
public class col4data
{
public List<col4subdata> col4sub { get; set; }
}
public class col4subdata
{
public string col4_1 { get; set; }
public string col4_2 { get; set; }
}
public class col5data
{
public List<col5subdata> col5sub { get; set; }
}
public class col5subdata
{
public string col5_1 { get; set; }
public string col5_2 { get; set; }
}
我想現在我會通過每一行進行迭代,並添加到RootObject
類,並從它創建一個JSON。我可以得到一些幫助嗎?
請說明你是如何在瀏覽器控制檯中獲得輸出的。 'console.log(JSON.stringify(data));'(或類似取決於你的變量名)應該顯示爲JSON。您還可以在瀏覽器的網絡選項卡中確切地查看服務器的原始響應。如果你直接將JS對象直接登錄到控制檯而不進行字符串化處理(請記住,你的代碼可能會自動將JSON字符串轉換爲JS對象) – ADyson
您使用的是什麼版本的Web API? Web API 2或Core? –
Web API 2 ...只是爲了澄清,我只是想請求幫助從主鍵創建子鍵並迭代它。 – Si8