|
|
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?
|
|