2012-10-23 135 views
0
static void Main(string[] args) 
{ 
    var json = @"{ ""rows"": [ 
       [ 
        { 
         ""colspan"": 4, 
         ""id"": ""ContentPanel1"" 
        }, 
        { 
         ""colspan"": 8, 
         ""id"": ""ContentPanel2"" 
        } 
       ], 
       [ 
        { 
         ""colspan"": 12, 
         ""id"": ""ContentPanel3"" 
        } 
       ] 
      ]}"; 

    var json_serializer = new JavaScriptSerializer(); 
    var jsonData = json_serializer.Deserialize<Grid>(json); 

    Console.ReadKey(); 
} 

[Serializable] 
public class Grid 
{ 
    public List<Row> rows { get; set; } 
} 

[Serializable] 
public class Row 
{ 
    public int colspan { get; set; } 
    public int id { get; set; } 
    public List<Row> rows { get; set; } 
} 

我想將此JSON字符串轉換爲C#對象,但我發現它很難,因爲錯誤消息不是很直觀。任何JSON玩家請幫忙!解析JSON到C#對象

錯誤類型'ConsoleApplication1.Program + Row'不支持數組的反序列化。

+0

錯誤消息是什麼... – Lloyd

+5

由於作爲錯誤信息並不直觀,它甚至不太有用的,如果你不告訴我們它是什麼。 – Rawling

+0

你有視覺工作室的網絡必需品嗎? http://madskristensen.net/post/Web-Essentials-2012-released.aspx它有一個功能粘貼JSON作爲類,這使得它很好解析 –

回答

4

首先,我們得到:

類型 '行' 不支持數組的反序列化。

的JSON與[ [示出了嵌套數組。因此,要麼改變JSON,或使rows一個Row[][]

public Row[][] rows { get; set; } 

現在,我們得到:

ContentPanel1不是的Int32的有效值。

好...

public int id { get; set; } 

VS

""id"": ""ContentPanel1"" 

現在:"ContentPanel1"不是int。讓id一個string

public string id { get; set; } 
+0

改變它仍然沒有運氣! – chugh97

+0

@ chugh97查看更新 –

+0

非常感謝! – chugh97