【问题标题】:Json DeserializationJson 反序列化
【发布时间】:2014-04-20 13:14:48
【问题描述】:

我想在我的 android 项目中使用 json。我在如何将 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"}]

    }

我该怎么做?谢谢...

【问题讨论】:

    标签: c# android .net json


    【解决方案1】:

    试一试:

    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);
    

    您正在序列化每一行。您要做的是将每一行打包成一个集合,然后将集合作为一个整体序列化。

    【讨论】:

    • 感谢您的回复 :)) 我更改了此代码并开始工作 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多