2012-10-23 134 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