Search code examples
c#serializationjson.netdeserializationjson-deserialization

Json.NET deserialization of Tuple<...> inside another type doesn't work?


Using Json.net, deserializing a type that contains a Tuple<...> doesn't work (serialization works, but deserialization doesn't):

[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); }
}

Funny thing is that direct deserialization of Tuple<...> does work:

[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.
}

Is it a Json.NET bug or am I missing here something?


Solution

  • The solution - or mine, anyhow - is to define a custom converter for the Tuple.

    This example provides a concrete solution for a specific Tuple, but you could genericize it to make the TupleConverter class to handle any combination of value types. Could also make it abstract and have derived types implement instantiation methods for each item, to handle tuples with reference types.

        public class TupleConverter : Newtonsoft.Json.JsonConverter
        {
            public override bool CanConvert(Type objectType)
            {
                return typeof(Tuple<string, bool>) == objectType;
            }
    
            public override object ReadJson(
                Newtonsoft.Json.JsonReader reader,
                Type objectType,
                object existingValue,
                Newtonsoft.Json.JsonSerializer serializer)
            {
                if (reader.TokenType == Newtonsoft.Json.JsonToken.Null)
                    return null;
    
                var jObject = Newtonsoft.Json.Linq.JObject.Load(reader);
    
                var target = new Tuple<string, bool>(
                    (string)jObject["Item1"], (bool)jObject["Item2"]);
    
                return target;
            }
    
            public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
            {
                serializer.Serialize(writer, value);
            }
        }
    
        public class TupleHolder
        {
            [Newtonsoft.Json.JsonConverter(typeof(TupleConverter))]
            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); }
        }
    
        [Test]
        public void Test()
        {
            var orig = new TupleHolder("what????", true);
            var json = Newtonsoft.Json.JsonConvert.SerializeObject(orig);
    
            Assert.AreEqual("{\"Tup\":{\"Item1\":\"what????\",\"Item2\":true}}", json);
    
            var dupl = Newtonsoft.Json.JsonConvert.DeserializeObject<TupleHolder>(json);
    
            // These succeed, now
            Assert.AreEqual(orig.Tup.Item1, dupl.Tup.Item1);
            Assert.AreEqual(orig.Tup.Item2, dupl.Tup.Item2);
        }