Search code examples
c#reflectionfastjson

Problems to deserialize JSON data to IDbSet<T>


I have the following json data:

{
    "Persons": [
        { "Person": { "FirstName":"A", "Surname": "B" } },
        { "Person": { "FirstName":"C", "Surname": "D" } },
        { "Person": { "FirstName":"E", "Surname": "F" } }
    ]
}

My class definitions are:

public class PersonContext
{
    public IDbSet<Person> Persons { get; set; }
}

public class Person
{
    public string FirstName { get; set; }
    public string Surname { get; set; }
}

When I use fastJSON to deserialize it to an object, I receive a NullReferenceException.

PersonContext context = fastJSON.JSON.ToObject<PersonContext>(jsonText);

Debugging source code of fastJSON, the exception is thrown on CreateGenericList, because the col variable of the method after calling (IList)Reflection.Instance.FastCreateInstance(pt); is null. So after, when it tries to add the parsed dictionary, it raises the exception.

Can I configure serialization process to ensure that IDbSet<T> objects are correctly processed?

Thanks in advance.

PS: You can also clone my repo in github in order to reproduce this issue.


Solution

  • This is the answer for my question by mr. Mehdi Gholam (fastJSON owner) on this thread:

    fastJSON needs concrete types and not interfaces to be defined so it knows what type to create.

    So change your code to :

    public class PersonContext
    {
       public List<Person> Persons { get; set; }
    }