title: How to create json, sorted on keys, using gson?
body: <p>I need to create constant json string or a json sorted on keys. What do I mean by constant json string? Please look into following code sample, which I created.</p>
  
  <p><strong>My Code 1:</strong></p>
  
  <pre><code>public class GsonTest
  {
      class DataObject {
  
          private int data1 = 100;
          private String data2 = "hello";
  
      }   
  
  
      public static void main(String[] args)
      {
          GsonTest obj=new GsonTest();
          DataObject obj2 = obj.new DataObject();
          Gson gson = new Gson();
  
          String json = gson.toJson(obj2);
          System.out.println(json);
      }
  }
  </code></pre>
  
  <p><strong>Output 1:</strong></p>
  
  <pre><code>{"data1":100,"data2":"hello"}
  </code></pre>
  
  <p><strong>My Code 2:</strong></p>
  
  <pre><code>public class GsonTest
  {
      class DataObject {
          private String data2 = "hello";
          private int data1 = 100;
  
  
      }   
  
  
      public static void main(String[] args)
      {
          GsonTest obj=new GsonTest();
          DataObject obj2 = obj.new DataObject();
          Gson gson = new Gson();
  
          String json = gson.toJson(obj2);
          System.out.println(json);
      }
  }
  </code></pre>
  
  <p><strong>Output 2:</strong></p>
  
  <pre><code>{"data2":"hello","data1":100}
  </code></pre>
  
  <p>If you see, if I switch variables (<code>data1</code> &amp; <code>data2</code> in <code>DataObject</code> class), I get different json. My objective to get same json, even if somebody changes position of the class variables. I get it when somebody adds new variables, json would change. But json shouldn't change when variables are moved around. So, my objective is to get standard json, possibly in sorted keys order for same class. If there is nested json, then it should be sorted in the nested structure.</p>
  
  <p><strong>Expected output on run of both the codes</strong>:</p>
  
  <pre><code>{"data1":100,"data2":"hello"}  //sorted on keys!! Here keys are data1 &amp; data2
  </code></pre>
  
  <p>I understand, I need to change something in <code>String json = gson.toJson(obj2);</code> line, but what do I have to do?</p>
  
  <p><strong>Why I need them to be order?</strong></p>
  
  <p>I need to encode the json string and then pass it to another function. If I change the order of keys, even though value remain intact, the encoded value will change. I want to avoid that.</p>