title: Return Selected Fields in Json for API calls in Java
body: <p>Is there a way to return only <strong>specific</strong> fields, in Json, when the <strong>specific</strong> API is called.  I have used "transient":  but that would be at the Object level and thus make it true for all API calls.</p>
  
  <p>Example:  The complete Json is</p>
  
  <pre><code>[{"field1":"a","field2":"b","field3":"c"},{"field1":"d","field2":"e","field3":"f"},{"field1":"g","field2":"h","field3":"i"}]
  </code></pre>
  
  <p>Depending on the API calls for a <strong>specific</strong> user, the "json output" is specific for the API call. It could be any one of the following depending on the API call.</p>
  
  <pre><code>[{"field1":"a"},{"field1":"d"},{"field1":"g"}]
  </code></pre>
  
  <p>OR</p>
  
  <pre><code>[{"field2":"b"},{"field2":"e"},{"field2":"h"}]
  </code></pre>
  
  <p>OR</p>
  
  <pre><code>[{"field3":"c"},{"field3":"f"},{"field3":"i"}]
  </code></pre>
  
  <p>OR  a combination of the above.</p>
  
  <p>E.g.  The code for the above example is shown below.</p>
  
  <pre><code>public class childObj {
  
      public String field1;
      public String field2;
      public String field3;
  
  
      public childObj(String field1, String field2, String field3) {
          super();
          this.field1 = field1;
          this.field2 = field2;
          this.field3 = field3;
      }
  
  }
  </code></pre>
  
  <p>The Main Class is defined Below:</p>
  
  <pre><code>import java.util.ArrayList;
  
  import com.google.gson.Gson;
  import com.google.gson.GsonBuilder;
  
  public class ParentAndChildObjects {
  
      public static void main(String[] args) {
  
          ArrayList&lt;childObj&gt; childObjList    = new ArrayList&lt;childObj&gt;();
  
          childObjList.add(new childObj("a","b","c"));
          childObjList.add(new childObj("d","e","f"));
          childObjList.add(new childObj("g","h","i"));
  
          Gson gson = new GsonBuilder().create();
  
          String myString = gson.toJson(childObjList);
  
          System.out.println(myString);
  
      }
  
  }
  </code></pre>