I would have my JSON string as below which needs to be deserialized to the below class
{
"Id":"1",
"Names":{
"string":"Surya"
},
"ClassTypes":{
"Types":[
{
"TypeId":"1",
"TypeName":"First Name"
},
{
"TypeId":"2",
"TypeName":"Last Name"
}
]
},
"Status":"1",
"DOB":"23/12/2014"
}
Class Definition
public class MyClass
{
public int Id { get; set; }
public IList<string> Names { get; protected set; }
public IList<Types> ClassTypes { get; protected set; }
public StatusType Status { get; set; }
public DateTime DOB { get; set; }
public MyClass()
{
Names = new List<string>();
ClassTypes = new List<Types>();
Status = StatusType.Active;
}
}
public class Types
{
public int TypeId { get; set; }
public string TypeName { get; set; }
}
public enum StatusType
{
Active = 0,
InActive = 1
}
I have used the following code for deserialization, but getting error
var serializerSettings = new JsonSerializerSettings();
serializerSettings.ContractResolver = new IncludeNonPublicMembersContractResolver();
JsonConvert.DeserializeObject<MyClass>(jsonString, serializerSettings);
public class IncludeNonPublicMembersContractResolver : DefaultContractResolver
{
public IncludeNonPublicMembersContractResolver()
{
DefaultMembersSearchFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
}
protected override List<MemberInfo> GetSerializableMembers(Type objectType)
{
var members = base.GetSerializableMembers(objectType);
return members.Where(m => !m.Name.EndsWith("k__BackingField")).ToList();
}
}
Error Details
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.IList`1[System.String]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'Names.string', line 1, position 28.
Note - I can't change by JSON string and solution to be more generic has this would be required for other classes as well :(