[英]JSON.NET serializing as array
I have a some data that I need serialized to json. 我有一些需要序列化为json的数据。 Below is a simplified version of the code I'm using on the backend to generate the json:
以下是我在后端用于生成json的代码的简化版本:
public class RawBarData
{
public string Month { get; set; }
public decimal Total { get; set; }
}
List<RawBarData> lstData == getData();
string jdata = JsonConvert.SerializedObject(lstData);
After this runs, jdata looks something like this: 运行之后,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}
]
However I need the output to look like this: 但是我需要输出看起来像这样:
[
["January", 10],
["February", 8],
["March", 4],
["April", 13],
["May", 17],
["June", 9]
]
How can I guide json.net to serialize the data in this format? 如何引导json.net以这种格式序列化数据?
You can do it like this: 您可以这样做:
List<object[]> converted = getData()
.Select(r => new object[] { r.Month, r.Total })
.ToList();
string jdata = JsonConvert.SerializedObject(converted);
This replaces the RawBarData
instances with object
arrays, which will serialize into... you guessed it, JSON arrays. 这将
RawBarData
实例替换为object
数组,该object
数组将序列化为JSON数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.