title: Converted ArrayList of custom objects to JSON using gson library, ClassCastException when retrieving back those custom objects
body: <p>I have used the Google's GSON library to convert an <code>ArrayList</code> of my custom objects to JSON in order to store it into <code>SharedPreferences</code>. The class of the objects stored in the ArrayList is like this:</p>
  
  <pre><code>class CustomObject {
    String name;
    Map&lt;String, Long&gt;  topGrades;
    Map&lt;String, Long&gt; lowestGrades;
  
    CustomObject(String name, Map&lt;String, Long&gt;  topGrades, Map&lt;String, Long&gt;  lowestGrades) {
      this.name = name;
      this.lowestGrades = lowestGrades;
      this.topGrades = topGrades;
    }
  }
  </code></pre>
  
  <p>I saved an <code>ArrayList</code> of objects of <code>CustomObject</code> to <code>SharedPreferences</code> like:</p>
  
  <pre><code>List&lt;CustomObject&gt; dataList = new ArrayList&lt;&gt;();
  //Populate the list with objects of type CustomObject
  ...
  SharedPreferences sharedPreferences = getActivity().getSharedPreferences(
                      "tests.dataSharedPreferences", Context.MODE_PRIVATE);
  SharedPreferences.Editor editor = sharedPreferences.edit();
  Gson gson = new Gson();
  String dataListJson = gson.toJson(dataList);
  editor.putString("tests.dataListJsonKey", dataListJson);
  editor.commit();
  </code></pre>
  
  <p>The I retrieved the <code>List</code> from the JSON like:</p>
  
  <pre><code>SharedPreferences sharedPreferences = getActivity().getSharedPreferences("tests.dataSharedPreferences", Context.MODE_PRIVATE);
              String dataJson = sharedPreferences.getString("tests.dataListJsonKey", "");
  
              Gson gson = new Gson();
              final List&lt;CustomObject&gt; dataList = gson.fromJson(dataJson, ArrayList.class);
  </code></pre>
  
  <p><strong>SO far so good. But now in order to get the <code>name</code>s of all <code>CustomObject</code>s in <code>dataList</code> above into a String array, in the following loop, I tried to retrieve a <code>CustomObject</code> from the <code>dataList</code>, <em>But I got <code>ClassCastException</code></em></strong>:</p>
  
  <pre><code>        String[] namesArray = new String[dataList.size()];
  
          for (int x=0; x&lt;namesArray.length; x++) {
              CustomObject customObject = dataList.get(x);//********ClassCastException********************************
              namesArray[x] = customObject.name;
          }
  </code></pre>
  
  <p><strong>I got</strong></p>
  
  <pre><code>06-18 12:28:11.689: E/AndroidRuntime(1536): Caused by: java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to tests.CustomObject
  </code></pre>
  
  <p>The question is why and what is the solution?</p>