使用Json.net,反序列化包含Tuple<...>
不工作類型(串行化的作品,但反序列化不):JSON.NET反序列化Tuple <...>另一種類型不起作用?
[TestMethod]
public void Test()
{
var orig = new TupleHolder("what????", true);
var json = JsonConvert.SerializeObject(orig);
Assert.AreEqual("{\"Tup\":{\"Item1\":\"what????\",\"Item2\":true}}", json);
// great! serialization works like a charm! now let's test deserialization:
var dupl = JsonConvert.DeserializeObject<TupleHolder>(json);
Assert.AreEqual("ZZZ", dupl.Tup.Item1); // pass! but it should be "what????"... what????
Assert.AreEqual(false, dupl.Tup.Item2); // pass! but it should be "true", right???
Assert.AreEqual(orig.Tup.Item1, dupl.Tup.Item1); // fail!
Assert.AreEqual(orig.Tup.Item2, dupl.Tup.Item2); // fail!
}
public class TupleHolder
{
public Tuple<string, bool> Tup { get; set; }
public TupleHolder() { Tup = new Tuple<string, bool>("ZZZ", false); }
public TupleHolder(string s, bool b) { Tup = new Tuple<string, bool>(s, b); }
}
有趣的是,Tuple<...>
直接反序列化沒有問題:
[TestMethod]
public void Test2()
{
var orig = new Tuple<string, bool>("ABC", true);
var json = JsonConvert.SerializeObject(orig);
var dupl = JsonConvert.DeserializeObject<Tuple<string, bool>>(json);
Assert.AreEqual(orig, dupl); // direct deserialization of Tuple<...> works.
}
是Json.NET錯誤還是我在這裏丟失的東西?
我覺得這是類似於你的問題... http://stackoverflow.com/questions/23017716/json-net-how-to-deserialize-without-using -default-constructor。這是由於使用了無參數的構造函數 –
@JoelGregory,有些......事情是,如果我有一個'List'它將被正確地反序列化,只是'Tuple <...>'有問題。我想'Json.NET'檢查屬性/字段是否實現'IEnumerable' /'ICollection' /'IList'/...和'Tuple <...>'不...... –
Tar
@JoelGregory,解決方法可以使用'[JsonObject(MemberSerialization.Fields)]''但它會在'JSON'字符串中創建一個醜陋的' k__BackingField'字符串...我希望有這樣一個簡單的解決方案,沒有這個額外的字符串... –
Tar