title: JSON serialization of generics
body: <p>I have a class that looked like this:</p>
  
  <pre><code>public class MyData : IList&lt;Tuple&lt;double,double&gt;&gt;
  </code></pre>
  
  <p>The idea being that you have a list of pairs of values. Simple enough. But I wanted this to be serialized such that it looks like an array of an array of doubles (i.e. <code>double[][]</code>) rather than a list of tuples. It should look like this when serialized:</p>
  
  <pre><code>[[1,1],[2,2],[3,3]]
  </code></pre>
  
  <p>So I created a simple <code>JsonConverter</code> that will do it. It has a very simple <code>WriteJson</code> method that looks like this:</p>
  
  <pre><code>public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  {
      var obj = value as MyData;
      double[][] dataArray = (from dp in obj._data
                              select new[] { dp.Item1, dp.Item2 }).ToArray();
      var ser = new JsonSerializer();
      ser.Serialize(writer, dataArray);
  }
  </code></pre>
  
  <p>And I decorate <code>MyData</code> with the appropriate attribute:</p>
  
  <pre><code>    [JsonConverter(typeof(MyDataJsonConverter))]
      public class MyData: IList&lt;Tuple&lt;double,double&gt;&gt;
  </code></pre>
  
  <p>And everything works fine. Now however, I want to extend this and make <code>MyData</code> generic:</p>
  
  <pre><code>    public class MyData&lt;S,T&gt;: IList&lt;Tuple&lt;S,T&gt;&gt;
  </code></pre>
  
  <p>And this is were I run into problems. Initially, I tried making <code>MyDataJsonConverter</code> also generic:</p>
  
  <pre><code>   [JsonConverter(typeof(MyDataJsonConverter&lt;S,T&gt;))]
     public class MyData&lt;S,T&gt;: IList&lt;Tuple&lt;S,T&gt;&gt;
  </code></pre>
  
  <p>But that isn't allowed because you can't use generics with attributes. </p>
  
  <p>So I have to keep <code>MyDataJsonConverter</code> non-generic, but I need to figure out how to flatten my collection of tuples into an array (presumably of <code>object[][]</code> now) such that when I serialize my data would look like:</p>
  
  <pre><code>[[1,2],[2,3]]
  </code></pre>
  
  <p>or:</p>
  
  <pre><code>[["foo":1],["bar":2]]
  </code></pre>
  
  <p>or even:</p>
  
  <pre><code>[["foo":"bar"],["what":"ever"]]
  </code></pre>
  
  <p>Any ideas on how to handle it? In <code>WriteJson</code>, I can no longer cast <code>value</code> to <code>MyData</code> because I won't know the type parameters, so everything just pretty much falls apart at that point.</p>
  
  <p>I could just create separate classes for each type combination (so one for <code>Tuple&lt;double,double&gt;</code> and one for <code>Tuple&lt;string,double&gt;</code> and so on...), but I was wondering  if there was a better way before I go brute force on it.</p>