问题描述
您好,
我想创建像这样的json字符串我的C#代码如下:
[
[Joe,42,185,M],
[Ann,40,125,F]
]
目前我正在创建这样的
[
{姓名:乔,年龄:42,体重:185,性别:M},
{姓名:安,年龄:40,体重:125,性别:F}
]
我正在读C#数据表并创建JSON列表。
我不想重复字段名称,以便JSON数据的大小更小,以获得更好的带宽。 />
任何人都可以帮助我。
我的尝试:
公共静态字符串getJSONString(DataTable dt)
{
System.Web.Script.Serialization.JavaScriptSerializer JSSerializ er = new System.Web.Script.Serialization.JavaScriptSerializer();
List< dictionary>< string,>> dic = new List< dictionary>< string,>>();
Dictionary< string,> newrow = null;
JSSerializer.MaxJsonLength = 2147483647;
//循环数据表中每一行并将其添加到字典对象的代码
dt.AcceptChanges();
string reqLink =;
foreach(DataRow drow in dt.Rows)
{
newrow = new Dictionary< string,>();
foreach(dt.Columns中的DataColumn col)
{
newrow.Add(col.ColumnName.Trim(),drow [col]);
}
dic.Add(newrow);
}
//序列化字典对象以生成json输出
返回JSSerializer.Serialize(dic );
}
Hello,
I want to create json string like this form my C# code like this :
[
["Joe", 42,185,"M"],
["Ann",40, 125, "F"]
]
Currently i am creating like this
[
{"Name":"Joe", "Age":"42","Weight":185,"Gender":"M"},
{"Name":"Ann", "Age":"40","Weight":125,"Gender":"F"}
]
I am reading the C# Data Table and creating the JSON list.
I don't want to repeat the field names so that the JSON data is of less size for better bandwidth.
Can any one help me.
What I have tried:
public static string getJSONString(DataTable dt)
{
System.Web.Script.Serialization.JavaScriptSerializer JSSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<dictionary><string,>> dic = new List<dictionary><string,>>();
Dictionary<string,> newrow = null;
JSSerializer.MaxJsonLength = 2147483647;
//Code to loop each row in the datatable and add it to the dictionary object
dt.AcceptChanges();
string reqLink = "";
foreach (DataRow drow in dt.Rows)
{
newrow = new Dictionary<string,>();
foreach (DataColumn col in dt.Columns)
{
newrow.Add(col.ColumnName.Trim(), drow[col]);
}
dic.Add(newrow);
}
//Serialising the dictionary object to produce json output
return JSSerializer.Serialize(dic);
}
这篇关于如何创建优化json字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!