我想在c#中创建以下json结构:
{
"data": [
["", "Kia", "Nissan", "Toyota", "Honda", "Mazda", "Ford"],
["2012", 10, 11, 12, 13, 15, 16],
["2013", 10, 11, 12, 13, 15, 16],
["2014", 10, 11, 12, 13, 15, 16],
["2015", 10, 11, 12, 13, 15, 16],
["2016", 10, 11, 12, 13, 15, 16]
]
}
我现在有以下代码:
public class JsonModel
{
public List<string> data { get; set; }
}
var properties = test.GetType().GetProperties();
List<string> propNames = new List<string>();
foreach(var props in properties)
{
propNames.Add(props.Name);
}
JsonModel json = new JsonModel
{
data = propNames
};
var jsonObj = JsonConvert.SerializeObject(json);
这给了我以下结构:
{
"data":["ITEM_NO","ITEM_TYPE","ITEM_STATE","ITEM_NAME"]
}
如您所见,data-property包含一个包含数据的数组。相反,我希望data-property是一个包含数组字符串的数组,就像我在上面展示的结构一样。
我该如何做到这一点?
答案 0 :(得分:0)
查看您发布的JSON,您有一个相当简单的对象结构。用例看起来像表或CSV。您只需要在代码中重新创建它。
{ // <= Object
"data": [ // <= Property on Object named 'data' that is an array of arrays
// Array of strings
["", "Kia", "Nissan", "Toyota", "Honda", "Mazda", "Ford"],
// Array of string followed by numbers through the rest.
["2012", 10, 11, 12, 13, 15, 16],
["2013", 10, 11, 12, 13, 15, 16],
["2014", 10, 11, 12, 13, 15, 16],
["2015", 10, 11, 12, 13, 15, 16],
["2016", 10, 11, 12, 13, 15, 16]
]
}
出现的问题是您在第一个数组(标题行)和其他数组(数据行)中没有相同的数据类型。值得庆幸的是,您将转到JavaScript,其中字符串和数字(实际上)相同。
您已经关闭了现有的JsonModel
类,但是您需要使用另一个数组包装数组,因为这就是您所需的JSON。
public class CarModel
{
// I stick with C# UpperCamelCaseConvention and use Newtonsoft's serializer
// settings to do the conversions for me.
public IEnumerable<IEnumerable<string>> Data { get; set; }
}
然后您可以像这样填充它:
var model = new CarModel
{
Data = new[]
{
new[] {"", "Kia", "Nissan", "Toyota", "Honda", "Mazda", "Ford"},
new[] {"2012", "10", "11", "12", "13", "15", "16"},
new[] {"2013", "10", "11", "12", "13", "15", "16"},
new[] {"2014", "10", "11", "12", "13", "15", "16"},
new[] {"2015", "10", "11", "12", "13", "15", "16"},
new[] {"2016", "10", "11", "12", "13", "15", "16"}
}
};
唯一的缺点是,一旦你到达消费者,你就需要将每个制造商的数字解析回数字。如果您将其发送回服务器,则不需要进行转换,因为使用int很容易进行字符串转换。
答案 1 :(得分:0)
我已成功使用JSON.NET's JTokenWriter
类以有序的方式创建JSON。
不确定您的数据是如何存储的,但以下是构建该结构的方法:
void Main() {
var sb = new StringBuilder();
using(var tw = new StringWriter(sb))
using(var writer = new Newtonsoft.Json.JsonTextWriter(tw)) {
writer.WriteStartObject(); // {
writer.WritePropertyName("data"); // data:
writer.WriteStartArray(); // [
writer.WriteStartArray(); // [
writer.WriteValue(""); // "",
writer.WriteValue("Kia"); // "Kia",
writer.WriteValue("Nissan"); //"Nissan",
// etc.
writer.WriteEndArray(); // ],
writer.WriteStartArray(); // [
writer.WriteValue("2012");// "2012",
writer.WriteValue(10); // 10,
writer.WriteValue(11); // 11,
// etc.
writer.WriteEndArray(); // ]
writer.WriteEndArray(); // ]
writer.WriteEndObject(); // }
}
Console.WriteLine(sb.ToString());
}