我很好奇Tuple<T1, T2, T3, ...>序列化和反序列化的方式。我使用关键字“ json”和“ tuple”进行搜索,但找不到所需的内容。
Tuple<T1, T2, T3, ...>
我通过UnitTest和Json.net进行测试,测试代码如下。结果显示Tuple<T1,T2,T3,...>可序列化和可反序列化。因此,我可以在应用程序中使用它们。
UnitTest
Tuple<T1,T2,T3,...>
public class Foo { public List<Tuple<string, string, bool>> Items { get; set; } public Foo() { Items = new List<Tuple<string, string, bool>>(); } public override string ToString() { StringBuilder sb = new StringBuilder(); foreach (var a in Items) { sb.Append(a.Item1 + ", " + a.Item2 + ", " + a.Item3.ToString() + "\r\n"); } return sb.ToString(); } } [TestClass] public class NormalTests { [TestMethod] public void TupleSerialization() { Foo tests = new Foo(); tests.Items.Add(Tuple.Create("one", "hehe", true)); tests.Items.Add(Tuple.Create("two", "hoho", false)); tests.Items.Add(Tuple.Create("three", "ohoh", true)); string json = JsonConvert.SerializeObject(tests); Console.WriteLine(json); var obj = JsonConvert.DeserializeObject<Foo>(json); string objStr = obj.ToString(); Console.WriteLine(objStr); } }
在Tuple.Create("own","hehe",true)将序列化到字符串{“项目1”:“一”,“项目2”:“嘻嘻”,“项目3”:真正},并且它可以被反序列化回Tuple<string,string,bool>类型。
Tuple.Create("own","hehe",true)
Tuple<string,string,bool>