Home > Net >  deserialize complex object in C#
deserialize complex object in C#

Time:09-17

I have a JSON object that fails to deserialize. It fails with the following error:

Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List1[SampleObj]' because the type requires a JSON array.

The JSON:

"{\"rows\":
     [
      {\"ID\":1,
       \"Name\":\"Puz\"
      },
       
      {\"ID\":2,
        \"Name\":\"Kez\"
      }
        
    ]
}"

I am have tried to following using Newtonsoft:

var deserializeObject = JsonConvert.DeserializeObject<List<SampleObj>>(jsonString);

And the following attempt is using the JavaScriptSerializer.

JavaScriptSerializer oJS = new JavaScriptSerializer();
List<SampleObj> deserializeObject = new List<ReportColumns>();
deserializeObject = oJS.Deserialize<List<ReportColumns>>(jsonString);

But both give an error.

CodePudding user response:

Your deserialization class doesn't seem to match the provided JSON structure. Something like this should work for you:

public class Foo
{
  public List<Bar> rows { get; set; }
}

public class Bar
{
  public int ID { get; set; }
  public string Name { get; set; }
}

Foo deserializeObject = oJS.Deserialize<Foo>(jsonString);

CodePudding user response:

Newtonsoft can be installed using the following command:

PM>Install-Package Newtonsoft.Json -Version 13.0.1

Example usage:

string json = @"{
  'Email': '[email protected]',
  'Active': true,
  'CreatedDate': '2013-01-20T00:00:00Z',
  'Roles': [
    'User',
    'Admin'
  ]
}";

Account account = JsonConvert.DeserializeObject<Account>(json);

Console.WriteLine(account.Email);
  • Related