chugh97
chugh97

Reputation: 9984

Parse JSON to C# object

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

I am trying to convert this JSON string to a C# object, but I am finding it hard because the error message is not very intuitive. Any JSON punters please help!

ERROR Type 'ConsoleApplication1.Program+Row' is not supported for deserialization of an array.

Upvotes: 0

Views: 973

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062820

First we get:

Type 'Row' is not supported for deserialization of an array.

The JSON with [ [ shows a nested array. So either change the JSON, or make rows a Row[][]:

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

Now we get:

ContentPanel1 is not a valid value for Int32.

well...

public int id { get; set; }

vs

""id"": ""ContentPanel1""

Now: "ContentPanel1" is not an int. Make id a string:

public string id { get; set; }

Upvotes: 4

Related Questions