package th.co.muangthai.endrprint.util; import com.google.gson.*; import java.lang.reflect.Type; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by IntelliJ IDEA. * User: ZIZU * Date: 5/16/13 * Time: 9:21 AM * To change this template use File | Settings | File Templates. */ public class JsonUtil { private static Gson gson; public static Gson getGsonInstance() { if (gson == null) { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(BigDecimal.class, new JsonDeserializer() { @Override public BigDecimal deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException { try { String value = json.getAsString(); if (value != null){ value = value.replace("\\r",""); } return new BigDecimal(value); } catch (Exception e) { return null; } } }); gsonBuilder.registerTypeAdapter(Integer.class, new JsonDeserializer() { @Override public Integer deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException { try { String value = json.getAsString(); if (value != null){ value = value.replace("\\r",""); } return new Integer(value); } catch (Exception e) { return null; } } }); gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer() { SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy"); @Override public Date deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException { // public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (VSMUtil.isEmpty(json.getAsString())) return null; // return new Date(Long.parseLong(json.getAsString())); try { return df.parse(json.getAsString()); } catch (ParseException e) { throw new RuntimeException(e); } } }); gsonBuilder.setDateFormat("dd/MM/yyyy"); gson = gsonBuilder.create(); } return gson; } }