Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing JSON object throws a Newtonsoft.Json.JsonSerializationException

Tags:

json

c#

I have this Json object:

{
   "Sheet1": [
      {
         "one": 1,
         "two": 18
      },
      {
         "one": 16,
         "two": 33
      },
      {
         "one": 17,
         "two": 34
      }
   ]
}

And I am trying to deserialize it using the following model:

public class Sheets
{
    [JsonProperty("Sheet1")]
    public Sheet Sheet { get; set; }
}

public class Sheet
{
    public List<Row> Rows { get; set; }
}

public class Row
{
    [JsonProperty("one")]
    public string Col1 { get; set; }

    [JsonProperty("two")]
    public string Col2 { get; set; }
}

var res = JsonConvert.DeserializeObject<Sheets>(result);

but I'm getting this exception:

An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll

Additional information: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'ExcelConsoleApp.Sheet' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.

What am I doing wrong? Any thoughts?

EDIT

One possible solution is to use

dynamic dynamicObject = JsonConvert.DeserializeObject(result);

but I want to deserialize it directly into my model.

like image 368
Yar Avatar asked Jun 18 '16 06:06

Yar


2 Answers

Sheet1 is not a Sheet type but a List of Rows. This can be identify by brackets.
i.e "Sheet1": [ which is a clear sign for Collection and not an Object which is identified by {.

Change Sheets to the following:

public class Sheets
{
    [JsonProperty("Sheet1")]
    public List<Row> Sheet { get; set; }
}
like image 56
Orel Eraki Avatar answered Nov 10 '22 00:11

Orel Eraki


this is the model you need, I tested it and it was working exactly as you want. and there is NO need to change the JSON structure.

public class SheetRoot
{
    [JsonProperty("Sheet1")]
    public List<Row> Sheet { get; set; }
}

public class Row
{
    [JsonProperty("one")]
    public int Col1 { get; set; }

    [JsonProperty("two")]
    public int Col2 { get; set; }
}

var res = JsonConvert.DeserializeObject<SheetRoot>(s);
like image 23
Hakan Fıstık Avatar answered Nov 10 '22 00:11

Hakan Fıstık