2012-04-22 130 views
1

我試過以下代碼將一個.NET對象序列化爲JSON,但我不斷得到空白文本。我究竟做錯了什麼?將.NET對象序列化爲JSON

[DataContract] 
     public class JsonObject2 
     { 
      [DataMember(Name = "field1")] 
      string field1 { get; set; } 
      [DataMember(Name = "field2")] 
      string field2 { get; set; } 
      [DataMember(Name = "field3")] 
      string[] test = { "heshan", "perera" }; 
     } 

的對象,我試圖序列,並顯示在消息框中所產生的JSON字符串,但我得到的是空白。

MemoryStream s = new MemoryStream(); 

      DataContractJsonSerializer dcjs2 = new DataContractJsonSerializer((typeof(JsonObject2))); 
      JsonObject2 obj2 = new JsonObject2(); 
      dcjs2.WriteObject(s, obj2); 

      StreamReader r = new StreamReader(s); 
      String x = r.ReadToEnd(); 
      MessageBox.Show(x); 

回答

4

嘗試增加:

s.Position = 0; 

創建StreamReader.

+0

輝煌之前!非常感謝! – 2012-04-23 03:12:15