Example usage for com.google.gson JsonDeserializer JsonDeserializer

List of usage examples for com.google.gson JsonDeserializer JsonDeserializer

Introduction

In this page you can find the example usage for com.google.gson JsonDeserializer JsonDeserializer.

Prototype

JsonDeserializer

Source Link

Usage

From source file:it.delli.mwebc.utils.DefaultCastHelper.java

License:Open Source License

private Map toMap(String value, Class<?> type) throws Exception {
    Map map = (Map) type.newInstance();
    JsonObject data = new GsonBuilder()
            .registerTypeAdapter(JsonObject.class, new JsonDeserializer<JsonObject>() {
                public JsonObject deserialize(JsonElement json, Type arg1, JsonDeserializationContext arg2)
                        throws JsonParseException {
                    return json.getAsJsonObject();
                }/*from   w w w.  j av a 2  s. c  om*/
            }).create().fromJson(value, JsonObject.class);
    for (Map.Entry<String, JsonElement> entry : data.entrySet()) {
        map.put(entry.getKey(), entry.getValue().getAsString());
    }
    return map;
}

From source file:it.smartcommunitylab.JSON.java

License:Apache License

public JSON() {
    gson = createGson().registerTypeAdapter(Date.class, dateTypeAdapter)
            .registerTypeAdapter(java.sql.Date.class, sqlDateTypeAdapter)
            .registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter)
            .registerTypeAdapter(LocalDate.class, localDateTypeAdapter)
            .registerTypeAdapter(byte[].class, byteArrayAdapter)
            .registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
                public Date deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context)
                        throws JsonParseException {
                    return new Date(jsonElement.getAsJsonPrimitive().getAsLong());
                }/*from w  w w  .  j a  v  a2 s. co  m*/
            }).create();
}

From source file:mashup.fm.github.BaseService.java

License:Apache License

/**
 * Gets the gson builder.//from www  .j  av a2 s  . c  o  m
 * 
 * @return the gson builder
 */
private static GsonBuilder getGsonBuilder() {
    // Init Builder
    GsonBuilder builder = new GsonBuilder();

    // This is the code that will try to parse dates
    builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
        @Override
        public Date deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2)
                throws JsonParseException {
            try {
                if (arg0.getAsString().indexOf(' ') == 0) {
                    // 2011-03-23T05:14:20-07:00
                    DateFormat df = new SimpleDateFormat("yyyy-MM-ddTHH:mm:ss-mm:mm");
                    return df.parse(arg0.getAsString());
                }
                DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss Z");
                return df.parse(arg0.getAsString());

            } catch (Throwable t) {
                Logger.warn(ExceptionUtil.getStackTrace(t));
                return null;
            }
        }
    });

    // We use camel case and the api returns lower case with underscore -
    // fieldId versus field_id
    builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);

    // Return Builder
    return builder;
}

From source file:me.figo.internal.GsonAdapter.java

License:Open Source License

public static Gson createGson() {
    JsonSerializer<Date> serializer = new JsonSerializer<Date>() {
        @Override//  ww w  . java2s . co  m
        public JsonElement serialize(Date src, Type type, JsonSerializationContext context) {
            if (src == null)
                return null;

            String formatted = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").format(src);
            return new JsonPrimitive(formatted.substring(0, 22) + ":" + formatted.substring(22));
        }
    };

    JsonDeserializer<Date> deserializer = new JsonDeserializer<Date>() {
        @Override
        public Date deserialize(JsonElement json, Type type, JsonDeserializationContext context)
                throws JsonParseException {
            if (json == null)
                return null;

            String s = json.getAsString().replace("Z", "+0000");
            try {
                return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ").parse(s);
            } catch (ParseException e) {
                return null;
            }
        }
    };

    return new GsonBuilder().registerTypeAdapter(Date.class, serializer)
            .registerTypeAdapter(Date.class, deserializer).excludeFieldsWithoutExposeAnnotation().create();
}

From source file:net.bhira.sample.common.JsonUtil.java

License:Open Source License

/**
 * Create a customized version of Gson that handles Date formats and timezones correctly. It
 * uses UTC date format for parsing and formating dates and expects the date string values to be
 * formatted in UTC timezone.//from   ww  w.  j a  v a  2 s  .co m
 *
 * @return an instance of {@link com.google.gson.Gson}.
 */
public static Gson createGson() {

    // create a custom serializer for dates
    JsonSerializer<Date> serializer = new JsonSerializer<Date>() {
        @Override
        public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
            if (src == null) {
                return null;
            }
            SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
            formatter.setTimeZone(TimeZone.getTimeZone(TIMEZONE));
            return new JsonPrimitive(formatter.format(src));
        }
    };

    // create a custom de-serializer for dates
    JsonDeserializer<Date> deserializer = new JsonDeserializer<Date>() {
        @Override
        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            if (json == null) {
                return null;
            }
            String date = json.getAsString();
            SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
            formatter.setTimeZone(TimeZone.getTimeZone(TIMEZONE));
            try {
                return formatter.parse(date);
            } catch (ParseException e) {
                throw new JsonParseException("Error parsing date " + date, e);
            }

        }
    };

    // create a custom gson that uses the custom date serializer/deserializer
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Date.class, serializer);
    gsonBuilder.registerTypeAdapter(Date.class, deserializer);
    return gsonBuilder.create();
}

From source file:net.nexustools.njs.JSON.java

License:Open Source License

public JSON(final Global global) {
    super(global);
    setHidden("stringify", new AbstractFunction(global) {

        public java.lang.String stringify(BaseObject object) {
            StringBuilder builder = new StringBuilder();
            stringify(object, builder);//from w  ww  .j  a  v a 2s  .c om
            return builder.toString();
        }

        public void stringify(BaseObject object, StringBuilder builder) {
            if (Utilities.isUndefined(object)) {
                builder.append("null");
                return;
            }

            BaseObject toJSON = object.get("toJSON", OR_NULL);
            if (toJSON != null)
                stringify0(((BaseFunction) toJSON).call(object), builder);
            else
                stringify0(object, builder);
        }

        public void stringify0(BaseObject object, StringBuilder builder) {
            if (object instanceof GenericArray) {
                builder.append('[');
                if (((GenericArray) object).length() > 0) {
                    stringify(object.get(0), builder);
                    for (int i = 1; i < ((GenericArray) object).length(); i++) {
                        builder.append(',');
                        stringify(object.get(i), builder);
                    }
                }
                builder.append(']');
            } else if (object instanceof String.Instance) {
                builder.append('"');
                builder.append(object.toString());
                builder.append('"');
            } else if (object instanceof Number.Instance) {
                double number = ((Number.Instance) object).value;
                if (Double.isNaN(number) || Double.isInfinite(number))
                    builder.append("null");

                builder.append(object.toString());
            } else if (object instanceof Boolean.Instance)
                builder.append(object.toString());
            else {
                builder.append('{');
                Iterator<java.lang.String> it = object.keys().iterator();
                if (it.hasNext()) {

                    java.lang.String key = it.next();
                    builder.append('"');
                    builder.append(key);
                    builder.append("\":");
                    stringify(object.get(key), builder);

                    if (it.hasNext()) {
                        do {
                            builder.append(',');
                            key = it.next();
                            builder.append('"');
                            builder.append(key);
                            builder.append("\":");
                            stringify(object.get(key), builder);
                        } while (it.hasNext());
                    }
                }
                builder.append('}');
            }
        }

        @Override
        public BaseObject call(BaseObject _this, BaseObject... params) {
            switch (params.length) {
            case 0:
                return Undefined.INSTANCE;

            case 1:
                if (params[0] == Undefined.INSTANCE)
                    return Undefined.INSTANCE;
                return global.wrap(stringify(params[0]));

            default:
                return global.wrap("undefined");
            }
        }

        @Override
        public java.lang.String name() {
            return "JSON_stringify";
        }
    });
    setHidden("parse", new AbstractFunction(global) {
        final Gson GSON;
        {
            GsonBuilder gsonBuilder = new GsonBuilder();
            gsonBuilder.registerTypeAdapter(BaseObject.class, new JsonDeserializer<BaseObject>() {
                @Override
                public BaseObject deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
                        throws JsonParseException {
                    if (je.isJsonNull())
                        return Null.INSTANCE;
                    if (je.isJsonPrimitive()) {
                        JsonPrimitive primitive = je.getAsJsonPrimitive();
                        if (primitive.isBoolean())
                            return primitive.getAsBoolean() ? global.Boolean.TRUE : global.Boolean.FALSE;
                        if (primitive.isNumber())
                            return global.wrap(primitive.getAsDouble());
                        if (primitive.isString())
                            return global.wrap(primitive.getAsString());
                        throw new UnsupportedOperationException(primitive.toString());
                    }
                    if (je.isJsonObject()) {
                        GenericObject go = new GenericObject(global);
                        JsonObject jo = je.getAsJsonObject();
                        for (Map.Entry<java.lang.String, JsonElement> entry : jo.entrySet()) {
                            go.set(entry.getKey(), deserialize(entry.getValue(), type, jdc));
                        }
                        return go;
                    }
                    if (je.isJsonArray()) {
                        JsonArray ja = je.getAsJsonArray();
                        BaseObject[] array = new BaseObject[ja.size()];
                        for (int i = 0; i < array.length; i++) {
                            array[i] = deserialize(ja.get(i), type, jdc);
                        }
                        return new GenericArray(global, array);
                    }
                    throw new UnsupportedOperationException(je.toString());
                }
            });
            GSON = gsonBuilder.create();
        }

        @Override
        public BaseObject call(BaseObject _this, BaseObject... params) {
            try {
                return GSON.fromJson(params[0].toString(), BaseObject.class);
            } catch (com.google.gson.JsonSyntaxException ex) {
                throw new Error.JavaException("SyntaxError", "Unexpected token", ex);
            }
        }

        @Override
        public java.lang.String name() {
            return "JSON_parse";
        }
    });
}

From source file:net.segoia.event.eventbus.config.json.EventBusJsonConfigLoader.java

License:Apache License

public static EventBusJsonConfig load(Reader reader) {
    GsonBuilder gb = new GsonBuilder();

    gb.registerTypeAdapter(Condition.class, new JsonDeserializer<Condition>() {

        @Override//  ww w .j  a va 2  s .c  o m
        public Condition deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            JsonObject jo = json.getAsJsonObject();
            JsonElement conditionType = jo.get("ctype");
            String ctype = null;
            if (conditionType != null) {
                ctype = conditionType.getAsString().trim();
                if ("".equals(ctype)) {
                    ctype = null;
                }
            }
            JsonDeserializer<?> deserializerForType = jsonDeserializers.get(ctype);
            if (deserializerForType == null) {
                throw new JsonParseException("No deserializer defined for condition type " + ctype);
            }
            return (Condition) deserializerForType.deserialize(json, typeOfT, context);
        }
    });

    gb.registerTypeAdapterFactory(new TypeAdapterFactory() {

        @Override
        public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
            final TypeAdapter<T> delegateAdapter = gson.getDelegateAdapter(this, type);

            TypeAdapter<T> typeAdapter = new TypeAdapter<T>() {

                @Override
                public void write(JsonWriter out, T value) throws IOException {
                    delegateAdapter.write(out, value);
                }

                @Override
                public T read(JsonReader in) throws IOException {
                    JsonElement value = Streams.parse(in);

                    if (value.isJsonNull()) {
                        return null;
                    }

                    if (!value.isJsonObject()) {
                        return delegateAdapter.fromJsonTree(value);
                    }
                    // System.out.println(value+" "+value.getClass());
                    JsonObject jo = value.getAsJsonObject();

                    JsonElement cnameElem = jo.remove("className");

                    if (cnameElem != null) {
                        String cname = cnameElem.getAsString();

                        try {
                            // System.out.println("using clazz " + cname);
                            return (T) gson.fromJson(value, Class.forName(cname));
                        } catch (ClassNotFoundException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            return null;
                        }
                    } else {
                        return delegateAdapter.fromJsonTree(value);
                    }
                }
            };

            return typeAdapter;

        }
    });

    final Gson gson = gb.create();

    EventBusJsonConfig ebusConfig = gson.fromJson(reader, EventBusJsonConfig.class);

    return ebusConfig;
}

From source file:net.servicestack.client.JsonSerializers.java

License:Open Source License

public static JsonDeserializer<Date> getDateDeserializer() {
    return new JsonDeserializer<Date>() {
        @Override//w ww  .j  a  v  a2 s.  c  o  m
        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            return json == null ? null : Utils.parseDate(json.getAsString());
        }
    };
}

From source file:net.servicestack.client.JsonSerializers.java

License:Open Source License

public static JsonDeserializer<TimeSpan> getTimeSpanDeserializer() {
    return new JsonDeserializer<TimeSpan>() {
        @Override//from w  ww.j a v  a  2s  .c om
        public TimeSpan deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            return json == null ? null : TimeSpan.parse(json.getAsString());
        }
    };
}

From source file:net.servicestack.client.JsonSerializers.java

License:Open Source License

public static JsonDeserializer<UUID> getGuidDeserializer() {
    return new JsonDeserializer<UUID>() {
        @Override/*  w  w w . ja  va 2 s.co  m*/
        public UUID deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            return json == null ? null : Utils.fromGuidString(json.getAsString());
        }
    };
}