How does a Tuple serialize to and deserialize from JSON?
If you are looking for a short answer. I am using JsonConvert.
var testTuple = Tuple.Create(1234, "foo", true);
var serialized = JsonConvert.SerializeObject(testTuple);
Console.WriteLine(serialized);
// prints: {"Item1":1234,"Item2":"foo","Item3":true}
I made a minimal fiddle.
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() + "\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);
}
}
Summary
Tuple.Create("own","hehe",true)
serializes to{"Item1":"one","Item2":"hehe","Item3":true}
{"Item1":"one","Item2":"hehe","Item3":true}
can be deserialized back toTuple<string,string, bool>
Class Foo
withTuple
data, can be serialized to json string, and the string can be deserialized back toClass Foo
.