Example usage for com.google.gson JsonSerializer JsonSerializer

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

Introduction

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

Prototype

JsonSerializer

Source Link

Usage

From source file:org.mitre.oauth2.view.TokenIntrospectionView.java

License:Apache License

@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) {/*from  w w  w. j ava2s .c  o  m*/

    Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {

        @Override
        public boolean shouldSkipField(FieldAttributes f) {
            /*
            if (f.getDeclaringClass().isAssignableFrom(OAuth2AccessTokenEntity.class)) {
               // we don't want to serialize the whole object, just the scope and timeout
               if (f.getName().equals("scope")) {
                  return false;
               } else if (f.getName().equals("expiration")) {
                  return false;
               } else {
                  // skip everything else on this class
                  return true;
               }
            } else {
               // serialize other classes without filter (lists and sets and things)
               return false;
            }
             */
            return false;
        }

        @Override
        public boolean shouldSkipClass(Class<?> clazz) {
            // skip the JPA binding wrapper
            if (clazz.equals(BeanPropertyBindingResult.class)) {
                return true;
            } else {
                return false;
            }
        }

    }).registerTypeAdapter(OAuth2AccessTokenEntity.class, new JsonSerializer<OAuth2AccessTokenEntity>() {
        @Override
        public JsonElement serialize(OAuth2AccessTokenEntity src, Type typeOfSrc,
                JsonSerializationContext context) {
            JsonObject token = new JsonObject();

            token.addProperty("active", true);

            token.addProperty("scope", Joiner.on(" ").join(src.getScope()));

            token.add("exp", context.serialize(src.getExpiration()));

            //token.addProperty("audience", src.getAuthenticationHolder().getAuthentication().getAuthorizationRequest().getClientId());

            token.addProperty("sub", src.getAuthenticationHolder().getAuthentication().getName());

            token.addProperty("client_id",
                    src.getAuthenticationHolder().getAuthentication().getOAuth2Request().getClientId());

            token.addProperty("token_type", src.getTokenType());

            return token;
        }

    }).registerTypeAdapter(OAuth2RefreshTokenEntity.class, new JsonSerializer<OAuth2RefreshTokenEntity>() {
        @Override
        public JsonElement serialize(OAuth2RefreshTokenEntity src, Type typeOfSrc,
                JsonSerializationContext context) {
            JsonObject token = new JsonObject();

            token.addProperty("active", true);

            token.addProperty("scope", Joiner.on(" ")
                    .join(src.getAuthenticationHolder().getAuthentication().getOAuth2Request().getScope()));

            token.add("exp", context.serialize(src.getExpiration()));

            //token.addProperty("audience", src.getAuthenticationHolder().getAuthentication().getAuthorizationRequest().getClientId());

            token.addProperty("sub", src.getAuthenticationHolder().getAuthentication().getName());

            token.addProperty("client_id",
                    src.getAuthenticationHolder().getAuthentication().getOAuth2Request().getClientId());

            return token;
        }

    }).setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create();

    response.setContentType("application/json");

    Writer out;

    try {

        out = response.getWriter();
        Object obj = model.get("entity");
        if (obj == null) {
            obj = model;
        }

        gson.toJson(obj, out);

    } catch (IOException e) {

        logger.error("IOException occurred in TokenIntrospectionView.java: ", e);

    }

}

From source file:org.mitre.openid.connect.view.JSONIdTokenView.java

License:Apache License

protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {

        public boolean shouldSkipField(FieldAttributes f) {

            return false;
        }/*from  w w  w .j  av a2s  .c om*/

        public boolean shouldSkipClass(Class<?> clazz) {
            // skip the JPA binding wrapper
            if (clazz.equals(BeanPropertyBindingResult.class)) {
                return true;
            }
            return false;
        }

    }).registerTypeHierarchyAdapter(ClaimSet.class, new JsonSerializer<ClaimSet>() {
        @Override
        public JsonElement serialize(ClaimSet src, Type typeOfSrc, JsonSerializationContext context) {
            if (src != null) {
                return src.getAsJsonObject();
            } else {
                return JsonNull.INSTANCE;
            }
        }
    }).create();

    response.setContentType("application/json");

    Writer out = response.getWriter();

    Object obj = model.get("entity");
    if (obj == null) {
        obj = model;
    }

    gson.toJson(obj, out);
}

From source file:org.netbeans.rest.application.config.GsonMessageBodyHandler.java

private Gson getGson() {
    if (gson == null) {
        JsonSerializer<Date> ser = new JsonSerializer<Date>() {

            @Override//from  ww  w .  ja  va 2s.  co  m
            public JsonElement serialize(Date src, Type type, JsonSerializationContext jsc) {
                return src == null ? null : new JsonPrimitive(src.getTime());
            }

        };

        JsonDeserializer<Date> deser = new JsonDeserializer<Date>() {

            @Override
            public Date deserialize(JsonElement json, Type type, JsonDeserializationContext jdc)
                    throws JsonParseException {
                return json == null ? null : new Date(json.getAsLong());
            }
        };

        final GsonBuilder gsonBuilder = new GsonBuilder();
        gson = gsonBuilder.registerTypeAdapter(Date.class, ser).registerTypeAdapter(Date.class, deser).create();
    }
    return gson;
}

From source file:org.ohmage.dagger.OhmageModule.java

License:Apache License

@Provides
@Singleton//from  w w w . j  a v a  2  s  .  c o m
Gson provideGson() {
    GsonBuilder gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .registerTypeAdapterFactory(new LowercaseEnumTypeAdapterFactory())
            .registerTypeAdapter(Prompt.class, new BasePrompt.PromptDeserializer())
            .registerTypeAdapter(Double.class, new JsonSerializer<Double>() {
                @Override
                public JsonElement serialize(Double src, Type typeOfSrc, JsonSerializationContext context) {
                    if ((src == Math.floor(src)) && !Double.isInfinite(src)) {
                        return context.serialize(src.intValue());
                    }

                    return context.serialize(src);
                }
            });
    TriggerInit.injectDeserializers(gson);
    return gson.create();
}

From source file:org.opendolphin.core.comm.JsonCodec.java

License:Apache License

public JsonCodec() {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Date.class, new JsonSerializer<Date>() {
        @Override/*from w w  w. j  a v  a  2 s .com*/
        public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
            JsonObject element = new JsonObject();
            element.addProperty(Date.class.toString(), new SimpleDateFormat(ISO8601_FORMAT).format(src));
            return element;
        }
    });
    gsonBuilder.registerTypeAdapter(Float.class, new JsonSerializer<Float>() {
        @Override
        public JsonElement serialize(Float src, Type typeOfSrc, JsonSerializationContext context) {
            JsonObject element = new JsonObject();
            element.addProperty(Float.class.toString(), Float.toString(src));
            return element;
        }
    });
    gsonBuilder.registerTypeAdapter(Double.class, new JsonSerializer<Double>() {
        @Override
        public JsonElement serialize(Double src, Type typeOfSrc, JsonSerializationContext context) {
            JsonObject element = new JsonObject();
            element.addProperty(Double.class.toString(), Double.toString(src));
            return element;
        }
    });
    gsonBuilder.registerTypeAdapter(BigDecimal.class, new JsonSerializer<BigDecimal>() {
        @Override
        public JsonElement serialize(BigDecimal src, Type typeOfSrc, JsonSerializationContext context) {
            JsonObject element = new JsonObject();
            element.addProperty(BigDecimal.class.toString(), src.toString());
            return element;
        }
    });
    GSON = gsonBuilder.serializeNulls().create();
}

From source file:org.rapla.rest.gwtjsonrpc.server.JsonServlet.java

License:Apache License

private String formatResult(final ActiveCall call) throws UnsupportedEncodingException, IOException {
    final GsonBuilder gb = createGsonBuilder();

    gb.registerTypeAdapter(call.getClass(), new JsonSerializer<ActiveCall>() {
        @Override/*  ww  w.  j a  va  2 s . c  o m*/
        public JsonElement serialize(final ActiveCall src, final Type typeOfSrc,
                final JsonSerializationContext context) {
            if (call.externalFailure != null) {
                final String msg;
                if (call.method != null) {
                    msg = "Error  in " + call.method.getName();
                } else {
                    msg = "Error";
                }
                logger.error(msg, call.externalFailure);
            }

            Throwable failure = src.externalFailure != null ? src.externalFailure : src.internalFailure;
            Object result = src.result;
            if (result instanceof FutureResult) {
                try {
                    result = ((FutureResult) result).get();
                } catch (Exception e) {
                    failure = e;
                }
            }

            final JsonObject r = new JsonObject();
            if (src.versionName == null || src.versionValue == null) {
                r.add("jsonrpc", new JsonPrimitive("2.0"));
            } else {
                r.add(src.versionName, src.versionValue);
            }
            if (src.id != null) {
                r.add("id", src.id);
            }
            if (failure != null) {
                final int code = to2_0ErrorCode(src);
                final JsonObject error = getError(src.versionName, code, failure, gb);
                r.add("error", error);
            } else {
                r.add("result", context.serialize(result));
            }
            return r;
        }

    });
    Gson create = gb.create();
    final StringWriter o = new StringWriter();

    create.toJson(call, o);
    o.close();
    String string = o.toString();
    return string;
}

From source file:org.rapla.server.jsonrpc.JsonServlet.java

License:Apache License

private String formatResult(final ActiveCall call) throws UnsupportedEncodingException, IOException {
    final GsonBuilder gb = createGsonBuilder();
    gb.registerTypeAdapter(call.getClass(), new JsonSerializer<ActiveCall>() {
        @Override//from  w w  w . j a v  a  2s .c  o  m
        public JsonElement serialize(final ActiveCall src, final Type typeOfSrc,
                final JsonSerializationContext context) {
            if (call.callback != null) {
                if (src.externalFailure != null) {
                    return new JsonNull();
                }
                return context.serialize(src.result);
            }

            final JsonObject r = new JsonObject();
            r.add(src.versionName, src.versionValue);
            if (src.id != null) {
                r.add("id", src.id);
            }
            if (src.xsrfKeyOut != null) {
                r.addProperty("xsrfKey", src.xsrfKeyOut);
            }
            if (src.externalFailure != null) {
                final JsonObject error = new JsonObject();
                if ("jsonrpc".equals(src.versionName)) {
                    final int code = to2_0ErrorCode(src);

                    error.addProperty("code", code);
                    error.addProperty("message", src.externalFailure.getMessage());
                } else {
                    error.addProperty("name", "JSONRPCError");
                    error.addProperty("code", 999);
                    error.addProperty("message", src.externalFailure.getMessage());
                }
                r.add("error", error);
            } else {
                r.add("result", context.serialize(src.result));
            }
            return r;
        }
    });

    final StringWriter o = new StringWriter();
    if (call.callback != null) {
        o.write(call.callback);
        o.write("(");
    }
    gb.create().toJson(call, o);
    if (call.callback != null) {
        o.write(");");
    }
    o.close();
    return o.toString();
}

From source file:org.talend.esb.sam.server.ui.JsonRowMapper.java

License:Apache License

/**
 * Instantiates a new json row mapper.//w  ww. j  a  v  a 2  s.  c o m
 */
public JsonRowMapper() {
    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(Timestamp.class, new JsonSerializer<Timestamp>() {

        @Override
        public JsonElement serialize(Timestamp src, Type typeOfSrc, JsonSerializationContext context) {
            return new JsonPrimitive(src.getTime());
        }
    });
    gson = builder.create();
}

From source file:org.unitime.timetable.api.JsonApiHelper.java

License:Apache License

protected Gson createGson() {
    return new GsonBuilder()
            .registerTypeAdapter(java.sql.Timestamp.class, new JsonSerializer<java.sql.Timestamp>() {
                @Override//from  ww  w  . j  a  v  a2 s. co m
                public JsonElement serialize(java.sql.Timestamp src, Type typeOfSrc,
                        JsonSerializationContext context) {
                    return new JsonPrimitive(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(src));
                }
            }).registerTypeAdapter(java.sql.Date.class, new JsonSerializer<java.sql.Date>() {
                @Override
                public JsonElement serialize(java.sql.Date src, Type typeOfSrc,
                        JsonSerializationContext context) {
                    return new JsonPrimitive(new SimpleDateFormat("yyyy-MM-dd").format(src));
                }
            }).registerTypeAdapter(Date.class, new JsonSerializer<Date>() {
                @Override
                public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
                    return new JsonPrimitive(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(src));
                }
            }).setFieldNamingStrategy(new FieldNamingStrategy() {
                Pattern iPattern = Pattern.compile("i([A-Z])(.*)");

                @Override
                public String translateName(Field f) {
                    Matcher matcher = iPattern.matcher(f.getName());
                    if (matcher.matches())
                        return matcher.group(1).toLowerCase() + matcher.group(2);
                    else
                        return f.getName();
                }
            }).setPrettyPrinting().create();
}

From source file:org.unitime.timetable.export.events.EventsExportEventsToJSON.java

License:Apache License

@Override
protected void print(ExportHelper helper, EventLookupRpcRequest request, List<EventInterface> events,
        int eventCookieFlags, EventMeetingSortBy sort, boolean asc) throws IOException {
    helper.setup("application/json", reference(), false);

    Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new JsonSerializer<Date>() {
        @Override/*from  w ww .j  a v  a2s  . c o  m*/
        public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
            return new JsonPrimitive(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(src));
        }
    }).setFieldNamingStrategy(new FieldNamingStrategy() {
        Pattern iPattern = Pattern.compile("i([A-Z])(.*)");

        @Override
        public String translateName(Field f) {
            Matcher matcher = iPattern.matcher(f.getName());
            if (matcher.matches())
                return matcher.group(1).toLowerCase() + matcher.group(2);
            else
                return f.getName();
        }
    }).setPrettyPrinting().create();

    helper.getWriter().write(gson.toJson(events));
}