JSON.NET序列化为数组

时间:2014-04-17 18:22:02

标签: c# json json.net

我有一些数据需要序列化为json。下面是我在后端使用的代码的简化版本,用于生成json:

public class RawBarData
{
    public string Month { get; set; }
    public decimal Total { get; set; }
}

List<RawBarData> lstData == getData();

string jdata = JsonConvert.SerializedObject(lstData);   

运行之后,jdata看起来像这样:

[ 
  { Month: "January", Total: 10}, 
  { Month: "February", Total: 8}, 
  { Month: "March", Total:  4}, 
  { Month: "April", Total: 13}, 
  { Month: "May", Total: 17}, 
  { Month: "June", Total:  9} 
]

但是我需要输出看起来像这样:

[ 
  ["January", 10], 
  ["February", 8], 
  ["March", 4], 
  ["April", 13], 
  ["May", 17], 
  ["June", 9] 
]

如何指导json.net以此格式序列化数据?

1 个答案:

答案 0 :(得分:3)

你可以这样做:

List<object[]> converted = getData()
    .Select(r => new object[] { r.Month, r.Total })
    .ToList();
string jdata = JsonConvert.SerializedObject(converted);

这会将RawBarData个实例替换为object个数组,这些数组会序列化为......你猜对了,JSON数组。