Java Examples for com.google.gson.JsonDeserializer

The following java examples will help you to understand the usage of com.google.gson.JsonDeserializer. These source code samples are taken from different open source projects.

Example 1
Project: java-cloudant-master  File: GsonHelper.java View source code
/**
     * Builds {@link Gson} and registers any required serializer/deserializer.
     *
     * @return {@link Gson} instance
     */
public static GsonBuilder initGson(GsonBuilder gsonBuilder) {
    gsonBuilder.registerTypeAdapter(JsonObject.class, new JsonDeserializer<JsonObject>() {

        public JsonObject deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            return json.getAsJsonObject();
        }
    });
    gsonBuilder.registerTypeAdapter(JsonObject.class, new JsonSerializer<JsonObject>() {

        public JsonElement serialize(JsonObject src, Type typeOfSrc, JsonSerializationContext context) {
            return src.getAsJsonObject();
        }
    });
    return gsonBuilder;
}
Example 2
Project: 2015-SMSGateway-master  File: ApiRequest.java View source code
/**
	 * Generates model using GSON
	 * 
	 * @param jsonString
	 * @return
	 */
private T createGsonModel(String jsonString) throws JsonSyntaxException, IllegalArgumentException {
    // if no json return null
    if (TextUtils.isEmpty(jsonString)) {
        throw new IllegalArgumentException();
    }
    GsonBuilder builder = new GsonBuilder().setFieldNamingPolicy(mNamingPolicy);
    JsonDeserializer<T> deserializer = getCustomDeserializer();
    if (deserializer != null) {
        builder.registerTypeAdapter(getGsonTypeToken().getType(), deserializer);
    }
    Gson gson = builder.create();
    // parse the result
    T model = gson.fromJson(jsonString, getGsonTypeToken().getType());
    return model;
}
Example 3
Project: EveryXDay-master  File: InterfaceResultParser.java View source code
public static Gson generateDateFormatGson() {
    return new GsonBuilder().registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {

        @Override
        public Date deserialize(JsonElement element, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            String date = element.getAsString();
            TimeZone.setDefault(TimeZone.getTimeZone("GMT+8:00"));
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz");
            try {
                return formatter.parse(date);
            } catch (ParseException e) {
                System.out.println("Failed to parse Date due to:" + e);
                return null;
            }
        }
    }).create();
}
Example 4
Project: LazyWaimai-Android-master  File: GsonHelper.java View source code
public static Gson builderGson() {
    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(Integer.class, new JsonDeserializer() {

        @Override
        public Integer deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            try {
                return json.getAsInt();
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            return null;
        }
    });
    builder.registerTypeAdapter(Date.class, new JsonDeserializer() {

        @Override
        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            try {
                long outer = json.getAsLong();
                Calendar calendar = Calendar.getInstance(TIME_ZONE);
                calendar.setTimeInMillis(outer * SECOND_IN_MILLISECONDS);
                return calendar.getTime();
            } catch (NumberFormatException e) {
                try {
                    return JSON_STRING_DATE.parse(json.getAsString());
                } catch (ParseException e1) {
                    throw new JsonParseException(e1);
                }
            }
        }
    });
    builder.registerTypeAdapter(OrderStatus.class, new JsonDeserializer<OrderStatus>() {

        @Override
        public OrderStatus deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            return OrderStatus.valueOf(json.getAsInt());
        }
    });
    builder.registerTypeAdapter(PayMethod.class, new JsonDeserializer<PayMethod>() {

        @Override
        public PayMethod deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            return PayMethod.valueOf(json.getAsInt());
        }
    });
    builder.registerTypeAdapter(Gender.class, new JsonDeserializer<Gender>() {

        @Override
        public Gender deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            return Gender.valueOf(json.getAsInt());
        }
    });
    builder.registerTypeAdapter(Gender.class, new JsonSerializer<Gender>() {

        @Override
        public JsonElement serialize(Gender gender, Type typeOfSrc, JsonSerializationContext context) {
            return new JsonPrimitive(gender.getValue());
        }
    });
    return builder.create();
}
Example 5
Project: kickmaterial-master  File: GlobalModule.java View source code
@Provides
Gson providesGson() {
    GsonBuilder builder = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
    JsonDeserializer<DateTime> deserializer = ( json,  typeOfT,  context) -> new DateTime(json.getAsJsonPrimitive().getAsLong() * 1000);
    builder.registerTypeAdapter(DateTime.class, deserializer);
    return builder.create();
}
Example 6
Project: org.geppetto.core-master  File: FindLocalProjectsVisitor.java View source code
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attr) throws IOException {
    if (file.toString().endsWith(".json")) {
        GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {

            @Override
            public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
                return new Date(json.getAsJsonPrimitive().getAsLong());
            }
        });
        Gson gson = builder.create();
        BufferedReader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8);
        T project = gson.fromJson(reader, type);
        for (IExperiment e : project.getExperiments()) {
            e.setParentProject(project);
        }
        projects.put(project.getId(), project);
    }
    return FileVisitResult.CONTINUE;
}
Example 7
Project: StockSimulator-master  File: GameSaver.java View source code
public void loadFromJson(String json) {
    gameState.stopThread();
    synchronized (gameState.getEntityEngine()) {
        try {
            //Custom Deserialized to Convert Component to it's expected Component subclass
            Gson gson = new GsonBuilder().registerTypeAdapter(ComponentContainer.class, new JsonDeserializer<ComponentContainer>() {

                @Override
                public ComponentContainer deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
                    String clazz = json.getAsJsonObject().get("clazz").getAsString();
                    try {
                        Class c = Class.forName(clazz);
                        System.out.println("Loading class: " + clazz);
                        JsonElement e = json.getAsJsonObject().get("value");
                        System.out.println("JSON? " + e);
                        Component component = context.deserialize(e, c);
                        System.out.println("Component? " + e);
                        return new ComponentContainer(component);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    return null;
                }
            }).create();
            SavedGame sg = gson.fromJson(json, SavedGame.class);
            gameState.getEntityEngine().removeAllEntities();
            for (EntityContainer ec : sg.entitiesContainers) {
                Class c = Class.forName(ec.clazz);
                //System.out.println("Adding entity: "+c.getName());
                Entity e = (Entity) c.newInstance();
                for (ComponentContainer component : ec.components) {
                    e.add(component.value);
                //   System.out.println("Adding Component: "+component.value.getClass().getName());
                }
                gameState.getEntityEngine().addEntity(e);
            }
            System.out.println(sg.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        gameState.startThread();
    }
}
Example 8
Project: thermospy-master  File: StartLogSessionReq.java View source code
private JSONObject getJsonObject() {
    List<LogSession> logSessionsList = new ArrayList<LogSession>();
    // Creates the json object which will manage the information received
    GsonBuilder builder = new GsonBuilder();
    // Register an adapter to manage the date types as long values
    builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {

        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            return new Date(json.getAsJsonPrimitive().getAsLong());
        }
    });
    Gson gson = builder.create();
    try {
        return new JSONObject(gson.toJson(mLogSession, LogSession.class));
    } catch (JSONExceptionJsonIOException |  e) {
        return null;
    }
}
Example 9
Project: vraptor4-master  File: GsonJSONSerializationTest.java View source code
@Before
public void setup() throws Exception {
    TimeZone.setDefault(TimeZone.getTimeZone("GMT-0300"));
    stream = new ByteArrayOutputStream();
    response = mock(HttpServletResponse.class);
    when(response.getWriter()).thenReturn(new AlwaysFlushWriter(stream));
    extractor = new DefaultTypeNameExtractor();
    environment = mock(Environment.class);
    List<JsonSerializer<?>> jsonSerializers = new ArrayList<>();
    List<JsonDeserializer<?>> jsonDeserializers = new ArrayList<>();
    jsonSerializers.add(new CalendarGsonConverter());
    jsonSerializers.add(new DateGsonConverter());
    jsonSerializers.add(new CollectionSerializer());
    jsonSerializers.add(new EnumSerializer());
    builder = new GsonBuilderWrapper(new MockInstanceImpl<>(jsonSerializers), new MockInstanceImpl<>(jsonDeserializers), new Serializee(new DefaultReflectionProvider()), new DefaultReflectionProvider());
    serialization = new GsonJSONSerialization(response, extractor, builder, environment, new DefaultReflectionProvider());
}
Example 10
Project: dashboard-master  File: GitHubService.java View source code
@Override
public void onConfigure(DashboardRepository repository) {
    for (Key key : getSettings().getKeysWithConfigurationFor(GitHubService.class)) {
        commits.put(key, Collections.<Commit>emptyList());
        repository.addDataSource(key, Commits.class, new CommitsImpl(key, this));
    }
    try {
        Field deserializersField = Gson.class.getDeclaredField("deserializers");
        deserializersField.setAccessible(true);
        Object deserializers = deserializersField.get(GsonUtils.getGson());
        Field deserializersMapField = deserializers.getClass().getDeclaredField("map");
        deserializersMapField.setAccessible(true);
        Map<Type, JsonDeserializer<?>> deserializersMap = (Map<Type, JsonDeserializer<?>>) deserializersMapField.get(deserializers);
        deserializersMap.put(Date.class, new GitHubDateFormatter());
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
}
Example 11
Project: ForgeEssentials-master  File: DataManager.java View source code
public Gson getGson() {
    if (gson == null || formatsChanged) {
        GsonBuilder builder = new GsonBuilder();
        builder.setPrettyPrinting();
        builder.setExclusionStrategies(this);
        for (Entry<Class<?>, JsonSerializer<?>> format : serializers.entrySet()) builder.registerTypeAdapter(format.getKey(), format.getValue());
        for (Entry<Class<?>, JsonDeserializer<?>> format : deserializers.entrySet()) builder.registerTypeAdapter(format.getKey(), format.getValue());
        gson = builder.create();
    }
    return gson;
}
Example 12
Project: incubator-atlas-master  File: AbstractMessageDeserializer.java View source code
// ----- helper methods --------------------------------------------------
private static Gson getDeserializer(Map<Type, JsonDeserializer> deserializerMap) {
    GsonBuilder builder = new GsonBuilder();
    for (Map.Entry<Type, JsonDeserializer> entry : DESERIALIZER_MAP.entrySet()) {
        builder.registerTypeAdapter(entry.getKey(), entry.getValue());
    }
    for (Map.Entry<Type, JsonDeserializer> entry : deserializerMap.entrySet()) {
        builder.registerTypeAdapter(entry.getKey(), entry.getValue());
    }
    return builder.create();
}
Example 13
Project: jade4ninja-master  File: ApiControllerTest.java View source code
private Gson getGsonWithLongToDateParsing() {
    // Creates the json object which will manage the information received
    GsonBuilder builder = new GsonBuilder();
    // Register an adapter to manage the date types as long values
    builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {

        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            return new Date(json.getAsJsonPrimitive().getAsLong());
        }
    });
    Gson gson = builder.create();
    return gson;
}
Example 14
Project: Nin-master  File: ApiControllerTest.java View source code
private Gson getGsonWithLongToDateParsing() {
    // Creates the json object which will manage the information received
    GsonBuilder builder = new GsonBuilder();
    // Register an adapter to manage the date types as long values
    builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {

        @Override
        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            return new Date(json.getAsJsonPrimitive().getAsLong());
        }
    });
    Gson gson = builder.create();
    return gson;
}
Example 15
Project: ninja-appengine-master  File: ApiControllerTest.java View source code
private Gson getGsonWithLongToDateParsing() {
    // Creates the json object which will manage the information received
    GsonBuilder builder = new GsonBuilder();
    // Register an adapter to manage the date types as long values
    builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {

        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            return new Date(json.getAsJsonPrimitive().getAsLong());
        }
    });
    Gson gson = builder.create();
    return gson;
}
Example 16
Project: ninja-ccc-master  File: ApiControllerTest.java View source code
private Gson getGsonWithLongToDateParsing() {
    // Creates the json object which will manage the information received
    GsonBuilder builder = new GsonBuilder();
    // Register an adapter to manage the date types as long values
    builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {

        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            return new Date(json.getAsJsonPrimitive().getAsLong());
        }
    });
    Gson gson = builder.create();
    return gson;
}
Example 17
Project: Ninja-master  File: ApiControllerTest.java View source code
private Gson getGsonWithLongToDateParsing() {
    // Creates the json object which will manage the information received
    GsonBuilder builder = new GsonBuilder();
    // Register an adapter to manage the date types as long values
    builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {

        @Override
        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            return new Date(json.getAsJsonPrimitive().getAsLong());
        }
    });
    Gson gson = builder.create();
    return gson;
}
Example 18
Project: Uber-Android-SDK-master  File: Uber.java View source code
/**
     * initialize Uber app by constructing all APIs services
     *
     * @param clientId A 32 character string (public)
     * @param clientSecret A 40 character string. DO NOT SHARE.
     *                     This should not be available on any public facing server or web site.
     *                     If you have been compromised or shared this token accidentally please reset your client_secret
     *                     via our web interface. This will require updating your application to use the newly issued client_secret.
     * @param serverToken A 40 character string. DO NOT SHARE.
     *                    This must be used for requests that are not issued on behalf of a User.
     * @param clientRedirectUri These URLs will be used during OAuth Authentication. To learn more about using OAuth please refer to OAuth Guide.
     */
public void init(String clientId, String clientSecret, String serverToken, String clientRedirectUri) {
    this.clientId = clientId;
    this.clientSecret = clientSecret;
    this.serverToken = serverToken;
    this.clientRedirectUri = clientRedirectUri;
    GsonBuilder gsonBuilder = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {

        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            return new Date(json.getAsJsonPrimitive().getAsLong());
        }
    });
    gson = gsonBuilder.create();
    RestAdapter apiRestAdapter = new RestAdapter.Builder().setEndpoint(UberURLs.API_URL).setConverter(new GsonConverter(gson)).setRequestInterceptor(new RequestInterceptor() {

        @Override
        public void intercept(RequestFacade request) {
            if (hasAccessToken()) {
                request.addHeader("Authorization", "Bearer " + getAccessToken().getAccessTokenValue());
                return;
            } else if (hasServerToken()) {
                request.addHeader("Authorization", "Token " + getServerToken());
            }
        }
    }).setErrorHandler(new ErrorHandler() {

        @Override
        public Throwable handleError(RetrofitError retrofitError) {
            if (retrofitError != null && retrofitError.getResponse() != null) {
                switch(retrofitError.getResponse().getStatus()) {
                    case //Unauthorized
                    401:
                        return new UnauthorizedException();
                    case //Forbidden
                    403:
                        return new ForbiddenException();
                }
            }
            return retrofitError;
        }
    }).setLogLevel(RestAdapter.LogLevel.FULL).build();
    uberAPIService = apiRestAdapter.create(UberAPIService.class);
    RestAdapter authRestAdapter = new RestAdapter.Builder().setEndpoint(UberURLs.OAUTH_URL).setLogLevel(BuildConfig.DEBUG ? RestAdapter.LogLevel.FULL : RestAdapter.LogLevel.NONE).setConverter(new GsonConverter(gson)).build();
    uberAuthService = authRestAdapter.create(UberAuthService.class);
    RestAdapter sandboxRestAdapter = new RestAdapter.Builder().setEndpoint(UberURLs.SANDBOX_URL).setLogLevel(BuildConfig.DEBUG ? RestAdapter.LogLevel.FULL : RestAdapter.LogLevel.NONE).setConverter(new GsonConverter(gson)).build();
    uberSandboxService = sandboxRestAdapter.create(UberSandboxService.class);
}
Example 19
Project: sosies-generator-master  File: CustomTypeAdaptersTest.java View source code
@Test(timeout = 1000)
public void testCustomDeserializers_add1025() {
    fr.inria.diversify.testamplification.logger.Logger.writeTestStart(Thread.currentThread(), this, "testCustomDeserializers_add1025");
    Gson gson = new GsonBuilder().registerTypeAdapter(TestTypes.ClassWithCustomTypeConverter.class, new JsonDeserializer<com.google.gson.common.TestTypes.ClassWithCustomTypeConverter>() {

        public TestTypes.ClassWithCustomTypeConverter deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
            JsonObject jsonObject = json.getAsJsonObject();
            int value = jsonObject.get("bag").getAsInt();
            return new TestTypes.ClassWithCustomTypeConverter(new TestTypes.BagOfPrimitives(value, value, false, ""), value);
        }
    }).create();
    String json = "{\"bag\":5,\"value\":25}";
    TestTypes.ClassWithCustomTypeConverter target = gson.fromJson(json, TestTypes.ClassWithCustomTypeConverter.class);
    fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 1135, target.getBag(), 1134, target.getBag().getIntValue());
    fr.inria.diversify.testamplification.logger.Logger.writeTestFinish(Thread.currentThread());
}
Example 20
Project: AngularBeans-master  File: AngularBeansUtils.java View source code
public void initJsonSerialiser() {
    GsonBuilder builder = new GsonBuilder().serializeNulls();
    builder.setExclusionStrategies(NGConfiguration.getGsonExclusionStrategy());
    builder.registerTypeAdapter(LobWrapper.class, new LobWrapperJsonAdapter(cache));
    builder.registerTypeAdapter(byte[].class, new ByteArrayJsonAdapter(cache, contextPath));
    builder.registerTypeAdapter(LobWrapper.class, new JsonDeserializer<LobWrapper>() {

        @Override
        public LobWrapper deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
            return null;
        }
    });
    if (NGConfiguration.getProperty("DATE_PATTERN") != null) {
        final SimpleDateFormat dateFormat = new SimpleDateFormat(NGConfiguration.getProperty("DATE_PATTERN"));
        if (dateFormat != null && NGConfiguration.getProperty("TIME_ZONE") != null) {
            dateFormat.setTimeZone(TimeZone.getTimeZone(NGConfiguration.getProperty("TIME_ZONE")));
        }
        builder.registerTypeAdapter(java.sql.Date.class, new JsonSerializer<java.sql.Date>() {

            @Override
            public JsonElement serialize(java.sql.Date src, Type typeOfSrc, JsonSerializationContext context) {
                if (src != null) {
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(src);
                    cal.set(Calendar.HOUR_OF_DAY, 0);
                    cal.set(Calendar.MINUTE, 0);
                    cal.set(Calendar.SECOND, 0);
                    cal.set(Calendar.MILLISECOND, 0);
                    return new JsonPrimitive(dateFormat.format(cal.getTime()));
                }
                return null;
            }
        });
        builder.registerTypeAdapter(java.sql.Date.class, new JsonDeserializer<java.sql.Date>() {

            @Override
            public java.sql.Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
                try {
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(dateFormat.parse(json.getAsString()));
                    cal.set(Calendar.HOUR_OF_DAY, 0);
                    cal.set(Calendar.MINUTE, 0);
                    cal.set(Calendar.SECOND, 0);
                    cal.set(Calendar.MILLISECOND, 0);
                    return new java.sql.Date(cal.getTime().getTime());
                } catch (Exception e) {
                }
                return null;
            }
        });
        builder.registerTypeAdapter(java.sql.Time.class, new JsonSerializer<java.sql.Time>() {

            @Override
            public JsonElement serialize(java.sql.Time src, Type typeOfSrc, JsonSerializationContext context) {
                if (src != null) {
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(src);
                    return new JsonPrimitive(dateFormat.format(cal.getTime()));
                }
                return null;
            }
        });
        builder.registerTypeAdapter(java.sql.Time.class, new JsonDeserializer<java.sql.Time>() {

            @Override
            public java.sql.Time deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
                try {
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(dateFormat.parse(json.getAsString()));
                    return new java.sql.Time(cal.getTime().getTime());
                } catch (Exception e) {
                }
                return null;
            }
        });
        builder.registerTypeAdapter(java.sql.Timestamp.class, new JsonSerializer<java.sql.Timestamp>() {

            @Override
            public JsonElement serialize(java.sql.Timestamp src, Type typeOfSrc, JsonSerializationContext context) {
                if (src != null) {
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(src);
                    return new JsonPrimitive(dateFormat.format(cal.getTime()));
                }
                return null;
            }
        });
        builder.registerTypeAdapter(java.sql.Timestamp.class, new JsonDeserializer<java.sql.Timestamp>() {

            @Override
            public java.sql.Timestamp deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
                try {
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(dateFormat.parse(json.getAsString()));
                    return new java.sql.Timestamp(cal.getTime().getTime());
                } catch (Exception e) {
                }
                return null;
            }
        });
        builder.registerTypeAdapter(java.util.Date.class, new JsonSerializer<java.util.Date>() {

            @Override
            public JsonElement serialize(java.util.Date src, Type typeOfSrc, JsonSerializationContext context) {
                return src == null ? null : new JsonPrimitive(dateFormat.format(src));
            }
        });
        builder.registerTypeAdapter(java.util.Date.class, new JsonDeserializer<java.util.Date>() {

            @Override
            public java.util.Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
                try {
                    return dateFormat.parse(json.getAsString());
                } catch (Exception e) {
                }
                return null;
            }
        });
    }
    mainSerializer = builder.create();
}
Example 21
Project: cathode-master  File: TraktModule.java View source code
@Provides
@Singleton
@Trakt
Gson provideGson() {
    GsonBuilder builder = new GsonBuilder();
    builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
    builder.registerTypeAdapter(int.class, new IntTypeAdapter());
    builder.registerTypeAdapter(Integer.class, new IntTypeAdapter());
    builder.registerTypeAdapter(IsoTime.class, new JsonDeserializer<IsoTime>() {

        @Override
        public IsoTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            String iso = json.getAsString();
            if (iso == null) {
                return null;
            }
            long timeInMillis = TimeUtils.getMillis(iso);
            return new IsoTime(iso, timeInMillis);
        }
    });
    builder.registerTypeAdapter(GrantType.class, new JsonDeserializer<GrantType>() {

        @Override
        public GrantType deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
            return GrantType.fromValue(jsonElement.getAsString());
        }
    });
    builder.registerTypeAdapter(TokenType.class, new JsonDeserializer<TokenType>() {

        @Override
        public TokenType deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
            return TokenType.fromValue(jsonElement.getAsString());
        }
    });
    builder.registerTypeAdapter(Scope.class, new JsonDeserializer<Scope>() {

        @Override
        public Scope deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
            return Scope.fromValue(jsonElement.getAsString());
        }
    });
    builder.registerTypeAdapter(ItemType.class, new JsonDeserializer<ItemType>() {

        @Override
        public ItemType deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
            return ItemType.fromValue(jsonElement.getAsString());
        }
    });
    builder.registerTypeAdapter(Action.class, new JsonDeserializer<Action>() {

        @Override
        public Action deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
            return Action.fromValue(jsonElement.getAsString());
        }
    });
    builder.registerTypeAdapter(ShowStatus.class, new JsonDeserializer<ShowStatus>() {

        @Override
        public ShowStatus deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
            return ShowStatus.fromValue(jsonElement.getAsString());
        }
    });
    builder.registerTypeAdapter(Gender.class, new JsonDeserializer<Gender>() {

        @Override
        public Gender deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
            return Gender.fromValue(jsonElement.getAsString());
        }
    });
    builder.registerTypeAdapter(Privacy.class, new JsonDeserializer<Privacy>() {

        @Override
        public Privacy deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
            return Privacy.fromValue(jsonElement.getAsString());
        }
    });
    builder.registerTypeAdapter(HiddenSection.class, new JsonDeserializer<HiddenSection>() {

        @Override
        public HiddenSection deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            return HiddenSection.fromValue(json.getAsString());
        }
    });
    builder.registerTypeAdapter(CommentType.class, new JsonDeserializer<CommentType>() {

        @Override
        public CommentType deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            return CommentType.fromValue(json.getAsString());
        }
    });
    builder.registerTypeAdapter(ItemTypes.class, new JsonDeserializer<ItemTypes>() {

        @Override
        public ItemTypes deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            return ItemTypes.fromValue(json.getAsString());
        }
    });
    builder.registerTypeAdapter(Department.class, new JsonDeserializer<Department>() {

        @Override
        public Department deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            return Department.fromValue(json.getAsString());
        }
    });
    return builder.create();
}
Example 22
Project: cloudstack-master  File: RESTServiceConnector.java View source code
private static Gson setGsonDeserializer(final Map<Class<?>, JsonDeserializer<?>> classToDeserializerMap) {
    final GsonBuilder gsonBuilder = new GsonBuilder();
    for (final Map.Entry<Class<?>, JsonDeserializer<?>> entry : classToDeserializerMap.entrySet()) {
        gsonBuilder.registerTypeAdapter(entry.getKey(), entry.getValue());
    }
    return gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
}
Example 23
Project: contextfw-master  File: Configuration.java View source code
/**
     * Creates the default configuration.
     * 
     * <p>
     *  This is the recommended way to initialize properties.
     * </p>
     */
public static Configuration getDefaults() {
    return new Configuration().set(DEVELOPMENT_MODE, true).set(CLASS_RELOADING_ENABLED, true).set(LOG_XML, true).set(RESOURCES_PREFIX, "/resources").set(XML_PARAM_NAME, null).set(XML_RESPONSE_LOGGER.asInstance(new DefaultXMLResponseLogger())).set(PROPERTY_PROVIDER, new SystemPropertyProvider()).set(REQUEST_INVOCATION_FILTER, new DefaultRequestInvocationFilter()).set(LIFECYCLE_LISTENER.as(DefaultLifecycleListener.class)).set(WEB_APPLICATION_STORAGE.as(DefaultWebApplicationStorage.class)).set(RESOURCE_PATH, new HashSet<String>()).set(VIEW_COMPONENT_ROOT_PACKAGE, new HashSet<String>()).set(INITIAL_MAX_INACTIVITY.inSeconds(30)).set(REMOVAL_SCHEDULE_PERIOD.inMinutes(1)).set(MAX_INACTIVITY.inMinutes(2)).set(NAMESPACE, new HashSet<KeyValue<String, String>>()).set(ATTRIBUTE_JSON_SERIALIZER, new HashSet<KeyValue<Class<?>, Class<? extends AttributeJsonSerializer<?>>>>()).set(JSON_SERIALIZER, new HashSet<KeyValue<Class<?>, Class<? extends JsonSerializer<?>>>>()).set(JSON_DESERIALIZER, new HashSet<KeyValue<Class<?>, Class<? extends JsonDeserializer<?>>>>()).set(ATTRIBUTE_SERIALIZER, new HashSet<KeyValue<Class<?>, Class<? extends AttributeSerializer<?>>>>());
}
Example 24
Project: DCPUAlpha-master  File: EditorShip.java View source code
public static EditorShip fromJson(String json) {
    EditorShip ship;
    GsonBuilder gb = new GsonBuilder();
    gb.registerTypeAdapter(EditorShipPart.class, new JsonDeserializer<EditorShipPart>() {

        public EditorShipPart deserialize(JsonElement obj, Type type, JsonDeserializationContext ctx) throws JsonParseException {
            BlueprintLocation bpl = ctx.deserialize(obj.getAsJsonObject().get("location"), BlueprintLocation.class);
            System.out.println(obj.toString());
            String types = obj.getAsJsonObject().get("part").getAsJsonObject().get("type").getAsJsonObject().get("name").getAsString();
            try {
                CatalogPartType tp = PartCatalog.getTypeByName(types);
                CatalogPart part = tp.create(bpl);
                part.loadOptions(obj.getAsJsonObject().get("part").getAsJsonObject());
                return new EditorShipPart(part, bpl);
            } catch (Throwable e) {
                e.printStackTrace();
            }
            return null;
        }
    });
    ship = gb.create().fromJson(json, EditorShip.class);
    return ship;
}
Example 25
Project: doctester-master  File: ApiControllerTest.java View source code
private Gson getGsonWithLongToDateParsing() {
    // Creates the json object which will manage the information received
    GsonBuilder builder = new GsonBuilder();
    // Register an adapter to manage the date types as long values
    builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {

        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            return new Date(json.getAsJsonPrimitive().getAsLong());
        }
    });
    Gson gson = builder.create();
    return gson;
}
Example 26
Project: geo-platform-master  File: GeoPlatformJsonTest.java View source code
@Test
@Ignore(value = "With api 1.1.0 Authentication required on all endpoints")
public void testTwitterSearch() throws Exception {
    URL url = new URL("http://search.twitter.com/search.json?q=jenkins");
    JsonDeserializer<Date> dateDeserializer = new JsonDeserializer<Date>() {

        @Override
        public Date deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException {
            return je == null ? null : new Date(je.getAsString());
        }
    };
    Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, dateDeserializer).create();
    SearchResults r = gson.fromJson(new InputStreamReader(url.openStream()), SearchResults.class);
    logger.info("FOUND : {} Results  ", r.getResults().size());
    String googleJsonFile = "target/googleJson.json";
    File f = new File(googleJsonFile);
    String json = gson.toJson(r);
    FileWriter fileWriter = new FileWriter(f, true);
    BufferedWriter bufferFileWriter = new BufferedWriter(fileWriter);
    bufferFileWriter.append(json);
    bufferFileWriter.close();
}
Example 27
Project: github-java-sdk-master  File: BaseGitHubService.java View source code
/**
	 * Gets the gson builder.
	 * 
	 * @return the gson builder
	 */
protected GsonBuilder getGsonBuilder() {
    GsonBuilder builder = new GsonBuilder();
    builder.setDateFormat(ApplicationConstants.DATE_FORMAT);
    builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
    builder.registerTypeAdapter(Issue.State.class, new JsonDeserializer<Issue.State>() {

        @Override
        public Issue.State deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            return Issue.State.fromValue(arg0.getAsString());
        }
    });
    builder.registerTypeAdapter(Milestone.State.class, new JsonDeserializer<Milestone.State>() {

        @Override
        public Milestone.State deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            return Milestone.State.fromValue(arg0.getAsString());
        }
    });
    builder.registerTypeAdapter(Milestone.State.class, new JsonSerializer<Milestone.State>() {

        @Override
        public JsonElement serialize(State arg0, Type arg1, JsonSerializationContext arg2) {
            return new JsonPrimitive(arg0.value());
        }
    });
    builder.registerTypeAdapter(Repository.Visibility.class, new JsonDeserializer<Repository.Visibility>() {

        @Override
        public Repository.Visibility deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            return (arg0.getAsBoolean()) ? Repository.Visibility.PRIVATE : Repository.Visibility.PUBLIC;
        }
    });
    builder.registerTypeAdapter(Gist.Visibility.class, new JsonDeserializer<Gist.Visibility>() {

        @Override
        public Gist.Visibility deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            return (arg0.getAsBoolean()) ? Gist.Visibility.PUBLIC : Gist.Visibility.PRIVATE;
        }
    });
    builder.registerTypeAdapter(Language.class, new JsonDeserializer<Language>() {

        @Override
        public Language deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            return Language.fromValue(arg0.getAsString());
        }
    });
    builder.registerTypeAdapter(Tree.Type.class, new JsonDeserializer<Tree.Type>() {

        @Override
        public Tree.Type deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            return Tree.Type.fromValue(arg0.getAsString());
        }
    });
    builder.registerTypeAdapter(Organization.Type.class, new JsonDeserializer<Organization.Type>() {

        @Override
        public Organization.Type deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            return Organization.Type.fromValue(arg0.getAsString());
        }
    });
    builder.registerTypeAdapter(Discussion.Type.class, new JsonDeserializer<Discussion.Type>() {

        @Override
        public Discussion.Type deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            return Discussion.Type.fromValue(arg0.getAsString());
        }
    });
    builder.registerTypeAdapter(Event.Type.class, new JsonDeserializer<Event.Type>() {

        @Override
        public Event.Type deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            return Event.Type.fromValue(arg0.getAsString());
        }
    });
    builder.registerTypeAdapter(Permission.class, new JsonDeserializer<Permission>() {

        @Override
        public Permission deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            return Permission.fromValue(arg0.getAsString());
        }
    });
    builder.registerTypeAdapter(Job.Type.class, new JsonDeserializer<Job.Type>() {

        @Override
        public Job.Type deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            return Job.Type.fromValue(arg0.getAsString());
        }
    });
    return builder;
}
Example 28
Project: google-gson-master  File: DefaultTypeAdaptersTest.java View source code
public void testDateSerializationWithPatternNotOverridenByTypeAdapter() throws Exception {
    String pattern = "yyyy-MM-dd";
    DateFormat formatter = new SimpleDateFormat(pattern);
    Gson gson = new GsonBuilder().setDateFormat(pattern).registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {

        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            return new Date();
        }
    }).create();
    Date now = new Date();
    String expectedDateString = "\"" + formatter.format(now) + "\"";
    String json = gson.toJson(now);
    assertEquals(expectedDateString, json);
}
Example 29
Project: Jockey-master  File: DemoMusicStore.java View source code
@SuppressWarnings("ThrowFromFinallyBlock")
private <T extends Comparable<? super T>> List<T> parseJson(String filename, Class<? extends T[]> type) throws IOException {
    InputStream stream = null;
    InputStreamReader reader = null;
    try {
        File json = new File(mContext.getExternalFilesDir(null), filename);
        stream = new FileInputStream(json);
        reader = new InputStreamReader(stream);
        Gson gson = new GsonBuilder().registerTypeAdapter(Uri.class, (JsonDeserializer) ( src,  srcType,  c) -> Uri.parse(src.getAsString())).create();
        T[] values = gson.fromJson(reader, type);
        ArrayList<T> list = new ArrayList<>(Arrays.asList(values));
        Collections.sort(list);
        return list;
    } finally {
        if (stream != null)
            stream.close();
        if (reader != null)
            reader.close();
    }
}
Example 30
Project: NewCommands-master  File: JsonUtilities.java View source code
public <T> JsonDeserializer<T> cachedDeserializer(final JsonDeserializer<T> deserializer) {
    return new JsonDeserializer<T>() {

        final ThreadLocal<Map<JsonElement, Map<Type, CacheResult>>> cached = Builder.this.cached;

        @Override
        public T deserialize(final JsonElement json, final Type type, final JsonDeserializationContext context) throws JsonParseException {
            final Map<Type, CacheResult> cached = this.cached.get().get(json);
            if (cached == null)
                return deserializer.deserialize(json, type, context);
            final CacheResult res = cached.get(type);
            if (res != null)
                return res.get();
            try {
                final T tmp = deserializer.deserialize(json, type, context);
                cached.put(type, new CacheResult.Res(tmp));
                return tmp;
            } catch (final JsonParseException ex) {
                cached.put(type, new CacheResult.Ex(ex));
                throw ex;
            }
        }
    };
}
Example 31
Project: package-drone-master  File: ChannelModelProvider.java View source code
static Gson createGson() {
    final GsonBuilder builder = new GsonBuilder();
    builder.setPrettyPrinting();
    builder.setLongSerializationPolicy(LongSerializationPolicy.STRING);
    builder.setDateFormat(DATE_FORMAT);
    builder.registerTypeAdapter(MetaKey.class, new JsonDeserializer<MetaKey>() {

        @Override
        public MetaKey deserialize(final JsonElement json, final Type type, final JsonDeserializationContext ctx) throws JsonParseException {
            return MetaKey.fromString(json.getAsString());
        }
    });
    return builder.create();
}
Example 32
Project: sgithub-master  File: BaseGitHubService.java View source code
/**
	 * Gets the gson builder.
	 * 
	 * @return the gson builder
	 */
protected GsonBuilder getGsonBuilder() {
    GsonBuilder builder = new GsonBuilder();
    builder.setDateFormat(ApplicationConstants.DATE_FORMAT);
    builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
    builder.registerTypeAdapter(Issue.State.class, new JsonDeserializer<Issue.State>() {

        @Override
        public Issue.State deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            return Issue.State.fromValue(arg0.getAsString());
        }
    });
    builder.registerTypeAdapter(Repository.Visibility.class, new JsonDeserializer<Repository.Visibility>() {

        @Override
        public Repository.Visibility deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            return (arg0.getAsBoolean()) ? Repository.Visibility.PRIVATE : Repository.Visibility.PUBLIC;
        }
    });
    builder.registerTypeAdapter(Gist.Visibility.class, new JsonDeserializer<Gist.Visibility>() {

        @Override
        public Gist.Visibility deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            return (arg0.getAsBoolean()) ? Gist.Visibility.PUBLIC : Gist.Visibility.PRIVATE;
        }
    });
    builder.registerTypeAdapter(Language.class, new JsonDeserializer<Language>() {

        @Override
        public Language deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            return Language.fromValue(arg0.getAsString());
        }
    });
    builder.registerTypeAdapter(Tree.Type.class, new JsonDeserializer<Tree.Type>() {

        @Override
        public Tree.Type deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            return Tree.Type.fromValue(arg0.getAsString());
        }
    });
    builder.registerTypeAdapter(Organization.Type.class, new JsonDeserializer<Organization.Type>() {

        @Override
        public Organization.Type deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            return Organization.Type.fromValue(arg0.getAsString());
        }
    });
    builder.registerTypeAdapter(Discussion.Type.class, new JsonDeserializer<Discussion.Type>() {

        @Override
        public Discussion.Type deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            return Discussion.Type.fromValue(arg0.getAsString());
        }
    });
    builder.registerTypeAdapter(Permission.class, new JsonDeserializer<Permission>() {

        @Override
        public Permission deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            return Permission.fromValue(arg0.getAsString());
        }
    });
    builder.registerTypeAdapter(Job.Type.class, new JsonDeserializer<Job.Type>() {

        @Override
        public Job.Type deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            return Job.Type.fromValue(arg0.getAsString());
        }
    });
    return builder;
}
Example 33
Project: stackoverflow-java-sdk-master  File: BaseStackOverflowApiQuery.java View source code
protected GsonBuilder getGsonBuilder() {
    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {

        @Override
        public Date deserialize(JsonElement source, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            return new Date(source.getAsLong() * 1000);
        }
    });
    builder.registerTypeAdapter(BadgeRank.class, new JsonDeserializer<BadgeRank>() {

        @Override
        public BadgeRank deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            return BadgeRank.fromValue(arg0.getAsString());
        }
    });
    builder.registerTypeAdapter(PostType.class, new JsonDeserializer<PostType>() {

        @Override
        public PostType deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            return PostType.fromValue(arg0.getAsString());
        }
    });
    builder.registerTypeAdapter(PostTimelineType.class, new JsonDeserializer<PostTimelineType>() {

        @Override
        public PostTimelineType deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            return PostTimelineType.fromValue(arg0.getAsString());
        }
    });
    builder.registerTypeAdapter(UserTimelineType.class, new JsonDeserializer<UserTimelineType>() {

        @Override
        public UserTimelineType deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            return UserTimelineType.fromValue(arg0.getAsString());
        }
    });
    builder.registerTypeAdapter(UserType.class, new JsonDeserializer<UserType>() {

        @Override
        public UserType deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            return UserType.fromValue(arg0.getAsString());
        }
    });
    builder.registerTypeAdapter(RevisionType.class, new JsonDeserializer<RevisionType>() {

        @Override
        public RevisionType deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            return RevisionType.fromValue(arg0.getAsString());
        }
    });
    builder.registerTypeAdapter(TagRestriction.class, new JsonDeserializer<TagRestriction>() {

        @Override
        public TagRestriction deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            return TagRestriction.fromValue(arg0.getAsString());
        }
    });
    builder.registerTypeAdapter(SiteState.class, new JsonDeserializer<SiteState>() {

        @Override
        public SiteState deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            return SiteState.fromValue(arg0.getAsString());
        }
    });
    builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
    return builder;
}
Example 34
Project: Thesis-Work-master  File: BaseGoogleSearchApiQuery.java View source code
/**
	 * Gets the gson builder.
	 * 
	 * @return the gson builder
	 */
protected GsonBuilder getGsonBuilder() {
    GsonBuilder builder = new GsonBuilder();
    builder.setDateFormat(ApplicationConstants.RFC822DATEFORMAT);
    builder.registerTypeAdapter(ListingType.class, new JsonDeserializer<ListingType>() {

        @Override
        public ListingType deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            return ListingType.fromValue(arg0.getAsString());
        }
    });
    builder.registerTypeAdapter(PatentStatus.class, new JsonDeserializer<PatentStatus>() {

        @Override
        public PatentStatus deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            return PatentStatus.fromValue(arg0.getAsString());
        }
    });
    builder.registerTypeAdapter(VideoType.class, new JsonDeserializer<VideoType>() {

        @Override
        public VideoType deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            return VideoType.fromValue(arg0.getAsString());
        }
    });
    builder.registerTypeAdapter(ViewPortMode.class, new JsonDeserializer<ViewPortMode>() {

        @Override
        public ViewPortMode deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            return ViewPortMode.fromValue(arg0.getAsString());
        }
    });
    builder.registerTypeAdapter(GsearchResultClass.class, new JsonDeserializer<GsearchResultClass>() {

        @Override
        public GsearchResultClass deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            return GsearchResultClass.fromValue(arg0.getAsString());
        }
    });
    builder.registerTypeAdapter(PhoneNumberType.class, new JsonDeserializer<PhoneNumberType>() {

        @Override
        public PhoneNumberType deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            return PhoneNumberType.fromValue(arg0.getAsString());
        }
    });
    builder.registerTypeAdapter(Language.class, new JsonDeserializer<Language>() {

        @Override
        public Language deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            return Language.fromValue(arg0.getAsString());
        }
    });
    return builder;
}
Example 35
Project: Edge-Node-master  File: CouchDbClientBase.java View source code
/**
	 * Builds {@link Gson} and registers any required serializer/deserializer.
	 * @return {@link Gson} instance
	 */
private Gson initGson(GsonBuilder gsonBuilder) {
    gsonBuilder.registerTypeAdapter(JsonObject.class, new JsonDeserializer<JsonObject>() {

        public JsonObject deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            return json.getAsJsonObject();
        }
    });
    return gsonBuilder.create();
}
Example 36
Project: plusTimer-master  File: PuzzleType.java View source code
private void upgradeDatabase(Context context) {
    mHistoryFileName = mLegacyName + ".json";
    mCurrentSessionFileName = mLegacyName + "-current.json";
    mHistorySessionsLegacy = new HistorySessions(mHistoryFileName);
    //TODO
    //AFTER UPDATING APP////////////
    int savedVersionCode = PrefUtils.getVersionCode(context);
    if (savedVersionCode <= 10) {
        // name first
        if (!mScrambler.equals("333") || mLegacyName.equals("THREE")) {
            mHistorySessionsLegacy.setFilename(mScrambler + ".json");
            mHistorySessionsLegacy.init(context);
            mHistorySessionsLegacy.setFilename(mHistoryFileName);
            if (mHistorySessionsLegacy.getList().size() > 0) {
                mHistorySessionsLegacy.save(context);
            }
            File oldFile = new File(context.getFilesDir(), mScrambler + ".json");
            oldFile.delete();
        }
    }
    if (savedVersionCode <= 13) {
        //Version <=13: ScrambleAndSvg json structure changes
        Gson gson = new GsonBuilder().registerTypeAdapter(Session.class, (JsonDeserializer<Session>) ( json,  typeOfT,  sessionJsonDeserializer) -> {
            Gson gson1 = new GsonBuilder().registerTypeAdapter(ScrambleAndSvg.class, (JsonDeserializer<ScrambleAndSvg>) ( json1,  typeOfT1,  context1) -> new ScrambleAndSvg(json1.getAsJsonPrimitive().getAsString(), null)).create();
            Session s = gson1.fromJson(json, typeOfT);
            return s;
        }).create();
        Utils.updateData(context, mHistoryFileName, gson);
        Utils.updateData(context, mCurrentSessionFileName, gson);
    }
    mHistorySessionsLegacy.setFilename(null);
////////////////////////////
}
Example 37
Project: vraptor-master  File: GsonDeserializerTest.java View source code
@Before
public void setUp() throws Exception {
    provider = mock(ParameterNameProvider.class);
    localization = mock(Localization.class);
    request = mock(HttpServletRequest.class);
    when(localization.getLocale()).thenReturn(new Locale("pt", "BR"));
    List<JsonDeserializer> deserializers = new ArrayList<JsonDeserializer>();
    CalendarDeserializer calendarDeserializer = new CalendarDeserializer(localization);
    deserializers.add(calendarDeserializer);
    deserializer = new GsonDeserialization(provider, new DefaultJsonDeserializers(deserializers), request);
    DefaultResourceClass resourceClass = new DefaultResourceClass(DogController.class);
    woof = new DefaultResourceMethod(resourceClass, DogController.class.getDeclaredMethod("woof"));
    bark = new DefaultResourceMethod(resourceClass, DogController.class.getDeclaredMethod("bark", Dog.class));
    jump = new DefaultResourceMethod(resourceClass, DogController.class.getDeclaredMethod("jump", Dog.class, Integer.class));
    dropDead = new DefaultResourceMethod(resourceClass, DogController.class.getDeclaredMethod("dropDead", Integer.class, Dog.class));
    adopt = new DefaultResourceMethod(resourceClass, DogController.class.getDeclaredMethod("adopt", List.class));
    sell = new DefaultResourceMethod(resourceClass, DogController.class.getDeclaredMethod("sell", List.class, String.class));
}
Example 38
Project: medsavant-master  File: MedSavantServlet.java View source code
@Override
public void init() throws ServletException {
    LOG.info("MedSavant JSON Client/Server booted.");
    try {
        loadConfiguration();
        initializeRegistry(this.medSavantServerHost, Integer.toString(this.medSavantServerPort));
        session = new Session(sessionManager, username, password, db);
        GsonBuilder gsonBuilder = new GsonBuilder();
        // Handle the condition type.
        gsonBuilder.registerTypeAdapter(Condition.class, new JsonDeserializer<Condition>() {

            @Override
            public Condition deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException {
                return gson.fromJson(je, SimplifiedCondition.class).getCondition(session.getSessionId(), variantManager);
            }
        });
        gson = gsonBuilder.create();
    } catch (Exception ex) {
        LOG.error(ex);
        throw new ServletException("Failed to initialize the medsavant JSON client: " + ex.getMessage());
    }
}
Example 39
Project: zulip-android-master  File: ZulipApp.java View source code
private Gson buildGson() {
    final Gson naiveGson = new GsonBuilder().registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {

        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            return new Date(json.getAsJsonPrimitive().getAsLong() * 1000);
        }
    }).registerTypeAdapter(MessageType.class, new JsonDeserializer<MessageType>() {

        @Override
        public MessageType deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            return json.getAsString().equalsIgnoreCase("stream") ? MessageType.STREAM_MESSAGE : MessageType.PRIVATE_MESSAGE;
        }
    }).create();
    final Gson nestedGson = new GsonBuilder().registerTypeAdapter(Message.class, new JsonDeserializer<Message>() {

        @Override
        public Message deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            if (BuildConfig.DEBUG) {
                Log.d("RAW MESSAGES", json.toString());
            }
            Message genMess;
            if ("stream".equalsIgnoreCase(json.getAsJsonObject().get("type").getAsString())) {
                Message.ZulipStreamMessage msg = naiveGson.fromJson(json, Message.ZulipStreamMessage.class);
                msg.setRecipients(msg.getDisplayRecipient());
                genMess = msg;
            } else {
                Message.ZulipDirectMessage msg = naiveGson.fromJson(json, Message.ZulipDirectMessage.class);
                if (msg.getDisplayRecipient() != null) {
                    // set the correct person id for message recipients
                    List<Person> people = msg.getDisplayRecipient();
                    for (Person person : people) {
                        // this is needed as the json field name for person id is
                        // "user_id" in realm configuration response and "id" in
                        // GET v1/messages response.
                        person.setId(person.getRecipientId());
                    }
                    msg.setRecipients(people.toArray(new Person[people.size()]));
                }
                msg.setContent(Message.formatContent(msg.getFormattedContent(), ZulipApp.get()).toString());
                genMess = msg;
            }
            if (genMess._history != null && genMess._history.size() != 0) {
                genMess.updateFromHistory(genMess._history.get(0));
            }
            return genMess;
        }
    }).create();
    return new GsonBuilder().registerTypeAdapter(UserConfigurationResponse.class, new TypeAdapter<UserConfigurationResponse>() {

        @Override
        public void write(JsonWriter out, UserConfigurationResponse value) throws IOException {
            nestedGson.toJson(nestedGson.toJsonTree(value), out);
        }

        @Override
        public UserConfigurationResponse read(JsonReader in) throws IOException {
            return nestedGson.fromJson(in, UserConfigurationResponse.class);
        }
    }).registerTypeAdapter(EventsBranch.class, new JsonDeserializer<EventsBranch>() {

        @Override
        public EventsBranch deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            EventsBranch invalid = nestedGson.fromJson(json, EventsBranch.class);
            if (BuildConfig.DEBUG) {
                Log.d("RAW EVENTS", json.toString());
            }
            Class<? extends EventsBranch> event = EventsBranch.BranchType.fromRawType(invalid);
            if (event != null) {
                if (event.getSimpleName().equalsIgnoreCase("SubscriptionWrapper")) {
                    // check operation
                    if (SubscriptionWrapper.OPERATION_ADD.equalsIgnoreCase(json.getAsJsonObject().get("op").getAsString()) || SubscriptionWrapper.OPERATION_REMOVE.equalsIgnoreCase(json.getAsJsonObject().get("op").getAsString()) || SubscriptionWrapper.OPERATION_UPDATE.equalsIgnoreCase(json.getAsJsonObject().get("op").getAsString())) {
                        Type type = new TypeToken<SubscriptionWrapper<Stream>>() {
                        }.getType();
                        return nestedGson.fromJson(json, type);
                    } else {
                        Type type = new TypeToken<SubscriptionWrapper<String>>() {
                        }.getType();
                        return nestedGson.fromJson(json, type);
                    }
                }
                return nestedGson.fromJson(json, event);
            }
            Log.w("GSON", "Attempted to deserialize and unregistered EventBranch... See EventBranch.BranchType");
            return invalid;
        }
    }).registerTypeAdapter(Message.class, nestedGson.getAdapter(Message.class)).create();
}
Example 40
Project: falcon-master  File: InstanceUtil.java View source code
public static APIResult hitUrl(String url, String method, String user) throws URISyntaxException, IOException, AuthenticationException, InterruptedException {
    BaseRequest request = new BaseRequest(url, method, user);
    HttpResponse response = request.run();
    String responseString = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
    LOGGER.info("The web service response is:\n" + Util.prettyPrintXmlOrJson(responseString));
    APIResult result;
    if (url.contains("/summary/")) {
        result = new InstancesSummaryResult(APIResult.Status.FAILED, responseString);
    } else if (url.contains("/listing/")) {
        result = new FeedInstanceResult(APIResult.Status.FAILED, responseString);
    } else if (url.contains("instance/dependencies")) {
        result = new InstanceDependencyResult(APIResult.Status.FAILED, responseString);
    } else if (url.contains("instance/triage")) {
        result = new TriageResult(APIResult.Status.FAILED, responseString);
    } else {
        result = new InstancesResult(APIResult.Status.FAILED, responseString);
    }
    Assert.assertNotNull(result, "APIResult is null");
    for (ResponseErrors error : ResponseErrors.values()) {
        if (responseString.contains(error.getError())) {
            return result;
        }
    }
    final String[] errorStrings = { "(FEED) not found", "is beforePROCESS  start", "is after end date", "is after PROCESS's end", "is before PROCESS's  start", "is before the entity was scheduled" };
    for (String error : errorStrings) {
        if (responseString.contains(error)) {
            return result;
        }
    }
    try {
        result = new GsonBuilder().registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {

            @Override
            public Date deserialize(JsonElement json, Type t, JsonDeserializationContext c) {
                return new DateTime(json.getAsString()).toDate();
            }
        }).create().fromJson(responseString, getClassOfResult(url));
    } catch (JsonSyntaxException e) {
        Assert.fail("Not a valid json:\n" + responseString);
    }
    LOGGER.info("statusCode: " + response.getStatusLine().getStatusCode());
    LOGGER.info("message: " + result.getMessage());
    LOGGER.info("APIResult.Status: " + result.getStatus());
    return result;
}
Example 41
Project: LightCouch-master  File: CouchDbClientBase.java View source code
/**
	 * Builds {@link Gson} and registers any required serializer/deserializer.
	 * @return {@link Gson} instance
	 */
private Gson initGson(GsonBuilder gsonBuilder) {
    gsonBuilder.registerTypeAdapter(JsonObject.class, new JsonDeserializer<JsonObject>() {

        public JsonObject deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            return json.getAsJsonObject();
        }
    });
    gsonBuilder.registerTypeAdapter(JsonObject.class, new JsonSerializer<JsonObject>() {

        public JsonElement serialize(JsonObject src, Type typeOfSrc, JsonSerializationContext context) {
            return src.getAsJsonObject();
        }
    });
    return gsonBuilder.create();
}
Example 42
Project: super_volley-master  File: DataManagerHelper.java View source code
/**
	 * Create a gson builder with a more advanced date parser.
	 * http://danwiechert.blogspot.dk/2013/02/gson-and-date-formatting.html
	 *
	 * @param dateFormat
	 * @return
	 */
private static Gson createGsonBuilder(final String dateFormat) {
    final GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {

        final DateFormat df = new SimpleDateFormat(dateFormat, Locale.US);

        @Override
        public Date deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException {
            try {
                return df.parse(json.getAsString());
            } catch (final java.text.ParseException e) {
                Log.e(TAG, "ParseException: " + e);
                return null;
            }
        }
    });
    return builder.create();
}
Example 43
Project: CIAPI.Java-master  File: GsonHelper.java View source code
/**
	 * Will retrieve a new custom Gson.
	 * 
	 * @param exception
	 *            this type will not have a custom handeler asigned to it
	 * @return
	 */
public static Gson gson(Class<?> exception) {
    GsonBuilder gb = new GsonBuilder();
    for (Entry<Class<?>, JsonDeserializer<?>> e : customs.entrySet()) {
        if (!e.getKey().equals(exception)) {
            gb.registerTypeAdapter(e.getKey(), e.getValue());
        }
    }
    return gb.create();
}
Example 44
Project: com.nimbits-master  File: SerializationHelper.java View source code
public static JsonDeserializer getDeserializer(final EntityType type) {
    return new NimbitsDeserializer(type);
}
Example 45
Project: ProjectAres-master  File: GsonBinder.java View source code
public <T> LinkedBindingBuilder<JsonDeserializer<? extends T>> bindDeserializer(Class<T> type) {
    return (LinkedBindingBuilder) adapters.addBinding(type);
}
Example 46
Project: ci-eye-master  File: CodeBook.java View source code
public <T> CodeBook withJsonDeserializerFor(Class<T> type, JsonDeserializer<T> deserialiser) {
    return new CodeBook(this.username, this.password, this.dateFormat, this.munger, extend(this.deserialisers, type, deserialiser));
}
Example 47
Project: frisbee-master  File: Utils.java View source code
public static Gson getGson(FieldNamingPolicy policy, JsonDeserializer<DateTime> dateTimeDeserializer) {
    return new GsonBuilder().setFieldNamingPolicy(policy).registerTypeAdapter(DateTime.class, dateTimeDeserializer).create();
}
Example 48
Project: gandalf-master  File: Gandalf.java View source code
private static Gandalf createInstance(@NonNull final Context context, @NonNull final OkHttpClient okHttpClient, @NonNull final String bootstrapUrl, @NonNull final HistoryChecker historyChecker, @NonNull final GateKeeper gateKeeper, @NonNull final OnUpdateSelectedListener onUpdateSelectedListener, @Nullable final JsonDeserializer<Bootstrap> customDeserializer, @NonNull final DialogStringsHolder dialogStringsHolder) {
    return new Gandalf(context, okHttpClient, bootstrapUrl, historyChecker, gateKeeper, onUpdateSelectedListener, customDeserializer, dialogStringsHolder);
}
Example 49
Project: SMSSync-master  File: InternalMessageDataRepository.java View source code
@NonNull
private Gson getGson() {
    JsonDeserializer<Date> date = ( json,  typeOfT,  context) -> json == null ? null : new Date(json.getAsLong());
    return new GsonBuilder().registerTypeAdapter(Date.class, date).setDateFormat("h:mm a").create();
}
Example 50
Project: active-directory-android-master  File: MobileServiceClient.java View source code
/**
	 * Registers a JsonDeserializer for the specified type
	 * 
	 * @param type
	 *            The type to use in the registration
	 * @param deserializer
	 *            The deserializer to use in the registration
	 */
public <T> void registerDeserializer(Type type, JsonDeserializer<T> deserializer) {
    mGsonBuilder.registerTypeAdapter(type, deserializer);
}