2014-04-20 318 views
0

我想使用json到我的android项目。我有一些问题如何使用json与.net。我的代码:Json反序列化

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"}] 

    } 

我怎么能做到这一点?谢谢...

回答

0

给这一个镜头:

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

您序列化的每一行。你想要做的是把每一行变成一个集合,然后作为一个整体序列化集合。

+0

感谢您的回复:))我改变了这段代码并且工作:) – sorunluadam