ENDRPrint/.svn/pristine/55/5534d016a95491d7e482d49c515be07bc8efd6fc.svn-base
2024-08-14 10:33:27 +07:00

98 lines
3.0 KiB
Plaintext

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<BigDecimal>() {
@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<Integer>() {
@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<Date>() {
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;
}
}