title: Php Json Associative Array To Java Map
body: <p>My problem is, PHP encodes arrays differently, based on if they are consecutive &amp; begin with a zero index, or not. Example:</p>
  
  <pre><code>$arr = array(array(12), array(13));
  ===&gt; [[12], [13]]
  
  $arr = array("0" =&gt; array(12), "1" =&gt; array(13));
  ===&gt; [[12], [13]]
  
  $arr = array("0" =&gt; array(12), "2" =&gt; array(13));
  ===&gt; {"0": [12], "2": [13]}
  </code></pre>
  
  <p>Why is the third one so radically different?</p>
  
  <p>The first example produces a list of lists, the third example produces an object with lists. I need to convert all of these to Java 's <code>Map&lt;Integer, List&lt;Double&gt;&gt;</code>. That is the most generic datatype I could find in Java for these PHP objects. I am using Gson from Google. However, since the examples produces different types of objects, I cannot just read this into a map. I have to first check if it has indices and then adding one by one to a custom map. Please look at the line that says "THERE HAS TO BE A BETTER WAY TO DO THIS PART". This is my code:</p>
  
  <pre><code>import java.lang.StringBuilder;
  import com.google.gson.*;
  import com.google.gson.reflect.*;
  import java.util.Map;
  import java.util.HashMap;
  import java.util.List;
  
  public class Saving {
  
      public static void main(String[] args) {
  
          String json = "[[12], [13]]";
          json = json.trim();
          Map&lt;Integer, List&lt;Double&gt;&gt; fuelSavings = null;
  
          // such a cluster****
          if(json.startsWith("[[")) { // THERE HAS TO BE A BETTER WAY TO DO THIS PART
          // ANY WAY I CAN AVOID THIS ENTIRE IF CONDITION
  
              //implicit keys
              fuelSavings = new HashMap&lt;Integer, List&lt;Double&gt;&gt;();
              List&lt;List&lt;Double&gt;&gt; temporaryList = new Gson().fromJson(json, new TypeToken&lt;List&lt;List&lt;Double&gt;&gt;&gt;(){}.getType());
              int index = 0;
              for(List&lt;Double&gt; temporaryListMember: temporaryList) {
                  fuelSavings.put(index, temporaryListMember);
                  index++;
              }
  
          } else {
  
              // explicit keys
              // THIS PART IS PERFECT
              fuelSavings = new Gson().fromJson(json, new TypeToken&lt;Map&lt;Integer, List&lt;Double&gt;&gt;&gt;(){}.getType());
  
          }
  
          System.out.println(fuelSavings);
  
      }
  
  }
  </code></pre>
  
  <p>Any help is appreciated, thanks!</p>