你在正確的軌道上。要獲得您問題中列出的結構,您需要使用代表商店編號與每個SKU數量映射的字典詞典。該類將如下所示:
class RootObject
{
[JsonProperty("skus")]
public Dictionary<string, Dictionary<string, int>> Skus { get; set; }
}
您將需要少量代碼將數據錶行分組到嵌套字典中,如下所示。注意:此代碼假定每個商店編號僅在每個SKU中遇到一次。如果情況並非如此,則需要相應調整。
DataTable table = new DataTable();
table.Columns.Add("sku", typeof(int));
table.Columns.Add("store", typeof(int));
table.Columns.Add("qty", typeof(int));
table.Rows.Add(20000, 100, 3);
table.Rows.Add(20000, 132, 1);
table.Rows.Add(20000, 320, 0);
table.Rows.Add(30000, 243, 2);
table.Rows.Add(30000, 210, 1);
table.Rows.Add(10000, 410, 5);
var skus = new Dictionary<string, Dictionary<string, int>>();
foreach (DataRow row in table.Rows)
{
string sku = row["sku"].ToString();
Dictionary<string, int> stores;
if (!skus.TryGetValue(sku, out stores))
{
stores = new Dictionary<string, int>();
skus.Add(sku, stores);
}
stores.Add(row["store"].ToString(), (int)row["qty"]);
}
RootObject root = new RootObject { Skus = skus };
一旦收集到你的RootObject數據,實在是小巫見大巫使用Json.Net將其序列化到JSON:
string json = JsonConvert.SerializeObject(root, Formatting.Indented);
反序列化JSON的回你RootObject也很簡單:
RootObject root = JsonConvert.DeserializeObject<RootObject>(json);
這是一個完整的往返演示:https://dotnetfiddle.net/qR3wbE
你嘗試過什麼讓d esired輸出? – 2014-11-05 10:12:11