如何做一个元组序列,并从JSON反序列化? [英] How does a Tuple serialize to and deserialize from JSON?
问题描述
我很好奇如何使用元组LT; T1,T2,T3,...>
序列化和反序列化。我搜索使用关键字JSON和元组,但我找不到我想要的东西。
I am curious about how the Tuple<T1, T2, T3, ...>
serializes and deserializes. I searched using keywords "json" and "tuple" but I could not find what I want.
推荐答案
我测试通过的UnitTest
和 Json.net 和测试代码是如下。结果表明元组LT; T1,T2,T3,...>
是序列化和deserializable。因此,我可以在我的应用程序中使用它们。
I test by UnitTest
and Json.net, and the test codes is as following. The results shows Tuple<T1,T2,T3,...>
is serializable and deserializable. So I can use them in my application.
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(自己,嘻嘻,真)
将序列化到字符串{项目1:一,项目2 嘻嘻,项目3:真正},它可以反序列化回元组LT;字符串,字符串,布尔>
键入
Comments
The Tuple.Create("own","hehe",true)
will be serialize to string {"Item1":"one","Item2":"hehe","Item3":true}, and it can be deserialized back to Tuple<string,string,bool>
type.
这篇关于如何做一个元组序列,并从JSON反序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!