Can't deserialize object with default parameter-less constructor

Jul 18, 2012 at 11:15 AM

I have found strange thing:

 

 

// Two simple classes

public class Data
{
  public string Name {get; set;}
  public int Value {get; set;}
  
  public Data(string name, int value)
  {
     Name = name;
     Value = value;
  }
  
}

public class Values
{
  private Dictionary<string, Data> dict;
  public List<Data> Entries
    {
        get
        {
            return dict.Values.ToList();
        }
        set
        {
            dict = value.ToDictionary(x => x.Name, x => x);
        }
    }
    
    public Values()
    {
      dict = new Dictionary<string, Data>();
    }
 
    public void Add(string name, int value)
    {
      dict.Add(name, new Data(name, value));
    }
}

 

Code for testing serialize/deserialze:

 

void Main()
{
  Values v = new Values(); 
  v.Add("red", 1);
  v.Add("green", 2);
   string json = JsonConvert.SerializeObject(v, 
                Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings
            {            });
            
  Console.WriteLine(json);

  Values another = JsonConvert.DeserializeObject<Values>(json);

  Console.WriteLine("Deserialized entries count: " + another.Entries.Count);
}
 

will return:

{
  "Entries": [
    {
      "Name": "red",
      "Value": 1
    },
    {
      "Name": "green",
      "Value": 2
    }
  ]
}
Deserialized entries count: 0

However if I change constructor for Values from

Values() to Values(string s="")

object will be properly deserialized

 

  Console.WriteLine(json);

  Values another = JsonConvert.DeserializeObject<Values>(json);
  Console.WriteLine("Deserialized enteries count: " + another.Entries.Count);
  
  Console.WriteLine("Another: " + JsonConvert.SerializeObject(another, 
                Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings
            {}));



{
  "Entries": [
    {
      "Name": "red",
      "Value": 1
    },
    {
      "Name": "green",
      "Value": 2
    }
  ]
}
Deserialized enteries count: 2
Another: {
  "Entries": [
    {
      "Name": "red",
      "Value": 1
    },
    {
      "Name": "green",
      "Value": 2
    }
  ]
}

Is it bug, or I missing some point?