这是一种奇怪的情况,但当我们不想将数据分解成一个单独的表时,我们经常使用这种模式来处理SQL后端。
这里的问题是,在反序列化时,MyList
中有两个项,而不是一个。问题的根源在于,当反序列化程序获取MyList
属性时,它会重用现有值,而不是重置该属性。
这是代码:
public class Jason
{
public object FromJSON(string json, Type t)
{
JsonSerializerSettings s = new JsonSerializerSettings();
s.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
s.NullValueHandling = NullValueHandling.Ignore;
return Newtonsoft.Json.JsonConvert.DeserializeObject(json, t, s);
}
public string ToJSON(object o)
{
JsonSerializerSettings s = new JsonSerializerSettings();
s.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
s.NullValueHandling = NullValueHandling.Ignore;
return Newtonsoft.Json.JsonConvert.SerializeObject(o, s);
}
public string MyListString
{
get { return ToJSON(_MyList); }
set { _MyList = (List<string>)FromJSON(value, typeof(List<string>)); }
}
private List<string> _MyList = new List<string>();
public List<string> MyList
{
get { return _MyList; }
set { _MyList = value; }
}
}
[TestFixture]
public class JasonTests : TestFixtureBase
{
[Test]
public void Jason()
{
Jason j = new Jason();
j.MyList.Add("hello");
string json = j.ToJSON(j);
Jason j2 = (Jason)j.FromJSON(json, typeof(Jason));
Assert.AreEqual(j.MyList.Count, j2.MyList.Count);
}
}
好吧,在检查了源代码并试图修复我认为的错误后,在谷歌上搜索是否有其他人有这个问题,我突然想到可能有一个设置,果然有。这是固定代码:
public class Jason
{
public object FromJSON(string json, Type t)
{
JsonSerializerSettings s = new JsonSerializerSettings();
s.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
s.NullValueHandling = NullValueHandling.Ignore;
s.ObjectCreationHandling = ObjectCreationHandling.Replace; // without this, you end up with duplicates.
return Newtonsoft.Json.JsonConvert.DeserializeObject(json, t, s);
}
public string ToJSON(object o)
{
JsonSerializerSettings s = new JsonSerializerSettings();
s.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
s.NullValueHandling = NullValueHandling.Ignore;
s.ObjectCreationHandling = ObjectCreationHandling.Replace; // without this, you end up with duplicates.
return Newtonsoft.Json.JsonConvert.SerializeObject(o, s);
}
public string MyListString
{
get { return ToJSON(_MyList); }
set { _MyList = (List<string>)FromJSON(value, typeof(List<string>)); }
}
private List<string> _MyList = new List<string>();
public List<string> MyList
{
get { return _MyList; }
set { _MyList = value; }
}
}
[TestFixture]
public class JasonTests : TestFixtureBase
{
[Test]
public void Jason()
{
Jason j = new Jason();
j.MyList.Add("hello");
string json = j.ToJSON(j);
Jason j2 = (Jason)j.FromJSON(json, typeof(Jason));
Assert.AreEqual(j.MyList.Count, j2.MyList.Count);
}
}