Ramachandran
Ramachandran

Reputation: 103

Unable Deserialize the JSON List into List of Objects in C#

I am currently working on a solution that Deserializes the list of email from json array, Once I get the list of email objects, I am validating using another class then set into another list.

Below is the code for Deserialize:

static void Main(string[] args)
{
    string jsonTest = "{\"Emails\":[\"[email protected]\",\"[email protected]\"]}";

    Class1 contact = JsonConvert.DeserializeObject<Class1>(jsonTest);

    Console.WriteLine(contact.Emails[0]);
    Console.WriteLine(contact.Emails[1]);
}

And, below is the class definition for Class1 for deserialize:

public class Class1
{
    private readonly List<ValidateEmail> emailsobj;
    public List<string> Emails
    {
        get
        {
            return emailsobj.Select(o => o.EmailAdd).ToList();
        }
        set
        {
            foreach (string email in value)
            {
                emailsobj.Add(new ValidateEmail(email));
            }
        }
    }
}

And, below is the validate class:

public class ValidateEmail
{
    public string EmailAdd { get; set; }
    private bool Valid;

    public ValidateEmail(string value)
    {           
        try
        {
            MailAddress mail = new MailAddress(EmailAdd);
            EmailAdd = value;
            Valid = true;
        }
        catch (FormatException)
        {
            Valid = false;
        }
    }
}

Whenever I deserialize I am getting exception on line :

Console.WriteLine(contact.Emails[0]);

Newtonsoft.Json.JsonSerializationException: Error getting value from 'Emails' on 'JsonGenerator.Class1'. ---> System.ArgumentNullException: Value cannot be null. (Parameter 'source')

It looks like the List<Email> never set. Any help on this, it would be much appreciated.

Upvotes: 0

Views: 178

Answers (1)

MBB
MBB

Reputation: 1695

You have to set the below setting(Replace) if you are using Lists - ObjectCreationHandling.

Replace Always create new objects and enables the setter property for the Lists!

So after you initialize the new list in Class1 like below:

private readonly List<ValidateEmail> emailsobj = new List<ValidateEmail>();

Change the code to have setting:

 var settings = new JsonSerializerSettings
      {                
         ObjectCreationHandling = ObjectCreationHandling.Replace           
      };

 Class1 contact = JsonConvert.DeserializeObject<Class1>(jsonTest, settings);

See the detailed explanation here !

Upvotes: 1

Related Questions