title: Unity Serializing Nested Dictionary to JSON
body: <p>The REST service I am using, RSA Archer, is expecting an integer key which means I simply can't nest <code>[Serializable]</code> objects and then <code>JsonUtility.ToJson()</code> to create the serialized JSON string. I thought I found a solution to create a <code>Dictionary</code> object and then use <code>ISerializationCallbackReceiver</code> to handle just the dictionary piece of the nested structure, but the code below simply ignores that part of the nested object and doesn't serialize the <code>Dictionary</code>. Does anyone have any thoughts on the best approach to this?</p>
  
  <p>Expected Output:</p>
  
  <pre><code>{"Content": {"LevelId": 10,"FieldContents": {"47": {"Type": 1, "Value": "me", "FieldId": 47}}}}
  </code></pre>
  
  <p>Object Structure:    </p>
  
  <pre><code>[Serializable]
  public class Record
  {
      public Content Content;
  }
  
  [Serializable]
  public class Content
  {
      public int LevelId;
      public FieldContents FieldContents;
  }
  
  public class FieldContents : ISerializationCallbackReceiver
  {
      public Dictionary&lt;string, FieldValue&gt; FieldValues;
  
      public List&lt;string&gt; dicKeys;
      public List&lt;FieldValue&gt; dicVals;
  
      public void OnBeforeSerialize ()
      {
          dicKeys.Clear ();
          dicVals.Clear ();
          foreach (var kvp in FieldValues) {
              dicKeys.Add (kvp.Key);
              dicVals.Add (kvp.Value);
          }
      }
  
      public void OnAfterDeserialize ()
      {
          FieldValues = new Dictionary&lt;string, FieldValue&gt; ();
          for (int i = 0; i &lt; Math.Min (dicKeys.Count, dicVals.Count); i++) {
              FieldValues.Add (dicKeys [i], dicVals [i]);
          }
      }
  }
  
  [Serializable]
  public class FieldValue
  {
      public int Type;
      public string Value;
      public int FieldId;
  }
  </code></pre>
  
  <p>JSONUtility and Instantiation:</p>
  
  <pre><code>Record newRecord = new Record () { Content = new Content () {
                  LevelId = 10,
                  FieldContents = new FieldContents () { FieldValues = new Dictionary&lt;string, FieldValue&gt; () { {
                              "47",
                              new FieldValue () {
                                  Type = 1,
                                  Value = "me",
                                  FieldId = 47
                              }
                          }
                      }
                  }
              }
          };
  Debug.Log (JsonUtility.ToJson (newRecord));
  </code></pre>