title: How to create Generic method for Gson marshal and unmarshal?
body: <p>I am new to Generics.</p>
  
  <p>I tried to create generic Gson marshal (i.e., gson.toJson()) and unmarshal (i.e., gson.fromJson())methods.</p>
  
  <pre><code>public class Message {
      private MessageBody messageBody;
      ....
  }
  public class MessageBody {
      private List&lt;BodyParam&gt; bodyParams;
  }
  public class MessageBodyParam {
      private String name;        
      private Object value;
  }
  
  public class JsonUtil {
  
      //This is not working
      public static &lt;T&gt; String marshal(Object object, Class&lt;T&gt; jtype) {
          Gson gson = new Gson();
  
          Type type = new TypeToken&lt;T&gt;() {}.getType();
          return gson.toJson(object, type);
      }
  
      //this is working as expected
      public static &lt;T&gt; T unmarshal(String jsonStr, Class&lt;T&gt; jtype) {
          Gson gson = new Gson();
          Type type = new TypeToken&lt;T&gt;() {}.getType();
          return gson.fromJson(jsonStr, type);
      }
  }
  </code></pre>
  
  <p>I am calling these methods as following:</p>
  
  <pre><code>//Message is my class
  String jsonMessage = JsonUtil.marshal(message, Message.class);
  Message message = JsonUtil.unmarshal(message, Message.class);
  </code></pre>
  
  <p>how to receive the class type in JsonUtil.marshal() and return the String object ?</p>
  
  <p>Please help me to resolve this. 
  Thanks.</p>