title: Serializing a SparseArray<T> with GSON
body: <p>I want to serialize a custom Java object, so I can use <code>SharedPreferences</code> to store it and retreive it in another Activity. I don't need persistant storage, the <code>SharedPreferences</code>, I  wipe them when my application is closed. I'm currently using GSON for this, but it doesn't seem to work well with Android's SparseArray type.</p>
  
  <p>My objects:</p>
  
  <pre><code>public class PartProfile {
  
  private int gameId;
  // Some more primitives
  private SparseArray&lt;Part&gt; installedParts = new SparseArray&lt;Part&gt;();
  
  // ...
  }
  
  public class Part {
     private String partName;
     // More primitives
  }
  </code></pre>
  
  <p>Serialization:</p>
  
  <pre><code>Type genericType = new TypeToken&lt;PartProfile&gt;() {}.getType();
  String serializedProfile = Helpers.serializeWithJSON(installedParts, genericType);
  preferences.edit().putString("Parts", serializedProfile).commit();
  </code></pre>
  
  <p>serializeWithJSON():</p>
  
  <pre><code>public static String serializeWithJSON(Object o, Type genericType) {
      Gson gson = new Gson();
      return gson.toJson(o, genericType);
  }
  </code></pre>
  
  <p>Deserialization:</p>
  
  <pre><code>Type genericType = new TypeToken&lt;PartProfile&gt;() {}.getType();
  PartProfile parts = gson.fromJson(preferences.getString("Parts", "PARTS_ERROR"), genericType);
  
  SparseArray&lt;Part&gt; retreivedParts = parts.getInstalledParts();
  int key;
  for (int i = 0; i &lt; retreivedParts.size(); i++) {
      key = retreivedParts.keyAt(i);
      // Exception here:
      Part part = retreivedParts.get(key);
      // ...
  }
  </code></pre>
  
  <p>Exception:</p>
  
  <pre><code>java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to com.mypackage.objects.Part
  </code></pre>
  
  <p>I don't understand why Gson wants to cast a <code>LinkedTreeMap</code> to my object, I never use one in my entire program. I used to have a <code>HashMap&lt;Integer,Part&gt;</code> before I switched to the <code>SparseArray&lt;Part&gt;</code>, and never had issues with that. Are SparseArrays not supported by Gson, or is there an error on my side?</p>
  
  <p>Edit: It seems that the SparseArray gets deserialized correctly, but not the objects inside. Instead of <code>LinkedTreeMaps</code>, these should be of type <code>Part</code>.<img src="https://i.stack.imgur.com/IQUAj.png" alt="enter image description here"></p>