All Downloads are FREE. Search and download functionalities are using the official Maven repository.

android.jsonUtil.mustache Maven / Gradle / Ivy

package {{invokerPackage}};

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.List;
{{#hasModel}}
import {{modelPackage}}.*;
{{/hasModel}}

public class JsonUtil {
  public static GsonBuilder gsonBuilder;

  static {
    gsonBuilder = new GsonBuilder();
    gsonBuilder.serializeNulls();
    gsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
  }

  public static Gson getGson() {
    return gsonBuilder.create();
  }

  public static String serialize(Object obj){
    return getGson().toJson(obj);
  }

  public static  T deserializeToList(String jsonString, Class cls){
    return getGson().fromJson(jsonString, getListTypeForDeserialization(cls));
  }

  public static  T deserializeToObject(String jsonString, Class cls){
    return getGson().fromJson(jsonString, getTypeForDeserialization(cls));
  }

  public static Type getListTypeForDeserialization(Class cls) {
    String className = cls.getSimpleName();
    {{#models}}{{#model}}
    if ("{{classname}}".equalsIgnoreCase(className)) {
      return new TypeToken>(){}.getType();
    }
    {{/model}}{{/models}}
    return new TypeToken>(){}.getType();
  }

  public static Type getTypeForDeserialization(Class cls) {
    String className = cls.getSimpleName();
    {{#models}}{{#model}}
    if ("{{classname}}".equalsIgnoreCase(className)) {
      return new TypeToken<{{classname}}>(){}.getType();
    }
    {{/model}}{{/models}}
    return new TypeToken(){}.getType();
  }

};