Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

c# - How does a Tuple serialize to and deserialize from 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Test codes

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() + "
");
        }
        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);
    }
}

Summary

  • Tuple.Create("own","hehe",true) serializes to {"Item1":"one","Item2":"hehe","Item3":true}

  • {"Item1":"one","Item2":"hehe","Item3":true} can be deserialized back to Tuple<string,string, bool>

  • Class Foo with Tuple data, can be serialized to json string, and the string can be deserialized back to Class Foo.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...