1

Say, we have that code:

var tuple = new Tuple<double, int>(10.6, 2);
var tupleString = tuple.ToString(); //returns "(10.6, 2)";

Can we get a new Tuple instance from tupleString without implementing any custom parsers and JsonConverters and extending TypeConverter?

UPDATE 1
In my production code I have SortedList<Tuple<DayOfWeek, double>, double>. That list is serialized by Json.NET,that converts Dictionary keys by .ToString(). Then JSON is sent to frontend application. Then frontend application send request with that serialized key to server. I have to convert that key to .NET Tuple, but I don't know how to do that.

  • Are you assuming that only tuples of `double, int` need to be reconstructed from the string? In *general*, there's no guarantee that the strings created by calling `ToString()` on the individual tuple components contain enough information to recreate the original data type. If you want *serialization*, you ought to be looking for serialization mechanisms, not `ToString`. – Damien_The_Unbeliever Oct 20 '17 at 08:33
  • @Damien_The_Unbeliever, I updated my question. – Vladislav Shirshakov Oct 20 '17 at 08:49

2 Answers2

4

Of course you can. You can 'simply' parse the output string, but I hope you like writing parsing algorithms then which might get hard, especially when it involves strings and objects...

See for example this one, which is impossible to parse:

var tuple = new Tuple<string, int>("10, 6", 2);
var tupleString = tuple.ToString(); //returns "(10, 6, 2)";

I would suggest to use the items in the tuple itself instead of making a string out of it first:

Tuple<int> tuple2 = tuple.Item2;

If you are serializing it using JSON.NET, you should write or use a custom serializer, like the one mentioned here.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
0

I solved my problem by another way using this answer of Nate Barbettini. I changed his code to that:

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        Type type = value.GetType();
        IEnumerable keys = (IEnumerable)type.GetProperty("Keys").GetValue(value, null);
        IEnumerable values = (IEnumerable)type.GetProperty("Values").GetValue(value, null);
        IEnumerator valueEnumerator = values.GetEnumerator();

        writer.WriteStartObject();
        foreach (object key in keys)
        {
            valueEnumerator.MoveNext();
            writer.WritePropertyName(JsonConvert.SerializeObject(key));
            serializer.Serialize(writer, valueEnumerator.Current);
        }
        writer.WriteEndObject();
    }

Then just set custom JsonConverterAttribute to required IDictionary<,> and Json.NET will serialize its keys by JsonConvert.SerializeObject() instead of .ToString(). So that Tuple can be deserialized by Json.NET correctly.