Search code examples
c#asp.netjsonasp.net-coredeserialization

Error occurs while deserialize json object


I have following JSON data:

{
"Id": 1,
"Name1": "Test1",
"Name2": null,
"PName": "PT",
"Address1": "First",
"Address2": "Second",
"NamePreferences": {
     "Dntst": "Test1",
     "Hygntst": "Test2"
   }
}

Now I am trying to de-serialize it using this code:

DataTable data = (DataTable)JsonConvert.DeserializeObject(data, (typeof(DataTable)), settings);

But I'm getting this error near PracticePreferences node:

Unexpected JSON token when reading DataTable: StartObject. Path '[0].NamePreferences', line 22, position 28.'


Solution

  • The provided json does not look like a data table nor a list of objects. It could be de-serialized to a object of a class like this:

    public class MyBaseClass{ public int Id {get;set;} public string? Name1 {get;set;} public string? Name2 {get;set;} public string? Address1 {get;set;} public string? Address2 {get;set;} public MyChildClass? NamePreferences {get;set;} } public class MyChildClass{ public string? Dntst {get;set;} public string? {get;set;} }