[英]Json Deserialization
我想在我的android项目中使用json。 我在使用.net时遇到了一些问题。 我的代码:
string stroutput = "";
try
{
string conStr = @"data source=.;database=Kelepir;Integrated Security=True;";
SqlConnection connection = new SqlConnection(conStr);
connection.Open();
string myquery = "select ProductID,ProductName,CategoryName,UnitPrice from Products";
SqlCommand cmd = new SqlCommand(myquery, connection);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
var nes = new
{
ProductID = reader["ProductID"].ToString(),
ProductName = reader["ProductName"].ToString(),
CategoryName = reader["CategoryName"].ToString(),
UnitPrice = reader["UnitPrice"].ToString()
};
stroutput = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(nes);
Response.Write(stroutput);
}
}
catch (Exception ex)
{
stroutput = "ERROR : " + ex.Message;
}
但是我的json没有这个标记:“,”和“ []”。
我的输出:
{"ProductID":"1","ProductName":"Şeker","CategoryName":"Tatlı","UnitPrice":"20"}
{"ProductID":"2","ProductName":"Kuruyemiş","CategoryName":"Tuzl","UnitPrice":"200"}
{"ProductID":"3","ProductName":"Baklagil","CategoryName":"Sebze","UnitPrice":"100"}
{"ProductID":"4","ProductName":"Bulgur","CategoryName":"Sebze","UnitPrice":"10"}
我想要这种格式到我的代码:
{ "table_name":
[
{"ProductID":"1","ProductName":"Şeker","CategoryName":"Tatlı","UnitPrice":"20"}, {"ProductID":"2","ProductName":"Kuruyemiş","CategoryName":"Tuzl","UnitPrice":"200"},
{"ProductID":"3","ProductName":"Baklagil","CategoryName":"Sebze","UnitPrice":"100"},
{"ProductID":"4","ProductName":"Bulgur","CategoryName":"Sebze","UnitPrice":"10"}]
}
我该怎么做? 谢谢...
试一下:
var rowList = new List<object>();
while (reader.Read())
{
var nes = new
{
ProductID = reader["ProductID"].ToString(),
ProductName = reader["ProductName"].ToString(),
CategoryName = reader["CategoryName"].ToString(),
UnitPrice = reader["UnitPrice"].ToString()
};
rowList.Add(nes);
}
var serializeMe = new {table_name = rowList }
stroutput = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(serializeMe );
Response.Write(stroutput);
您正在序列化每一行。 您想要做的就是将每一行打包成一个大学,然后将集合整体序列化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.