Java 类com.google.gson.JsonDeserializer 实例源码

项目:OutsourcedProject    文件:JsonUtil.java   
/**
 * 将json转换成bean对象
 *
 * @param jsonStr
 * @param cl
 * @return
 */
public static <T> T jsonToBeanDateSerializer(String jsonStr, Class<T> cl, final String pattern) {
    T bean;
    gson = new GsonBuilder().registerTypeAdapter(Date.class, (JsonDeserializer<Date>) (json, typeOfT, context) -> {
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        String dateStr = json.getAsString();
        try {
            return format.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }).setDateFormat(pattern).create();
    bean = gson.fromJson(jsonStr, cl);
    return bean;
}
项目:owo.java    文件:OwO.java   
/**
 * Create service
 * @param key OwO API key
 * @param endpoint Endpoint URL, defaults to {@link OwO#DEFAULT_ENDPOINT} when null
 * @param uploadUrl Upload URL, defaults to {@link OwO#DEFAULT_UPLOAD_URL} when null
 * @return service
 */
private static OwOService createService(@NotNull final String key, @Nullable String endpoint, @Nullable final String uploadUrl) {
    OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            HttpUrl url = request.url().newBuilder().addQueryParameter("key", key).build();
            return chain.proceed(request.newBuilder().header("User-Agent", USER_AGENT).url(url).build());
        }
    }).build();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(endpoint == null ? DEFAULT_ENDPOINT : endpoint)
            .client(client)
            .addConverterFactory(ScalarsConverterFactory.create())
            .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().registerTypeAdapter(OwOFile.class, new JsonDeserializer<OwOFile>() {
                @Override
                public OwOFile deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
                    return new Gson().fromJson(json.getAsJsonObject().get("files").getAsJsonArray().get(0), OwOFile.class).setFullUrl(uploadUrl == null ? DEFAULT_UPLOAD_URL : uploadUrl);
                }}).create()))
            .build();

    return retrofit.create(OwOService.class);
}
项目:OSchina_resources_android    文件:AppOperator.java   
public static Gson createGson() {
    GsonBuilder gsonBuilder = new GsonBuilder();
    //gsonBuilder.setExclusionStrategies(new SpecificClassExclusionStrategy(null, Model.class));
    gsonBuilder.setDateFormat("yyyy-MM-dd HH:mm:ss");

    JsonDeserializer deserializer = new IntegerJsonDeserializer();
    gsonBuilder.registerTypeAdapter(int.class, deserializer);
    gsonBuilder.registerTypeAdapter(Integer.class, deserializer);

    deserializer = new FloatJsonDeserializer();
    gsonBuilder.registerTypeAdapter(float.class, deserializer);
    gsonBuilder.registerTypeAdapter(Float.class, deserializer);

    deserializer = new DoubleJsonDeserializer();
    gsonBuilder.registerTypeAdapter(double.class, deserializer);
    gsonBuilder.registerTypeAdapter(Double.class, deserializer);

    deserializer = new StringJsonDeserializer();
    gsonBuilder.registerTypeAdapter(String.class, deserializer);

    gsonBuilder.registerTypeAdapter(Tweet.Image.class, new ImageJsonDeserializer());

    return gsonBuilder.create();
}
项目:MCBot    文件:CommandQuote.java   
@Override
public void gatherParsers(GsonBuilder builder) {
    super.gatherParsers(builder);
    builder.registerTypeAdapter(Quote.class, new JsonDeserializer<Quote>() {
        @Override
        public Quote deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            if (json.isJsonPrimitive() && json.getAsJsonPrimitive().isString()) {
                String quote = json.getAsString();
                if (IN_QUOTES_PATTERN.matcher(quote.trim()).matches()) {
                    quote = quote.trim().replace("\"", "");
                }
                int lastDash = quote.lastIndexOf('-');
                String author = lastDash < 0 ? "Anonymous" : quote.substring(lastDash + 1);
                quote = lastDash < 0 ? quote : quote.substring(0, lastDash);
                // run this twice in case the quotes were only around the "quote" part
                if (IN_QUOTES_PATTERN.matcher(quote.trim()).matches()) {
                    quote = quote.trim().replace("\"", "");
                }
                return new Quote(quote.trim(), author.trim(), MCBot.instance.getOurUser());
            }
            return new Gson().fromJson(json, Quote.class);
        }
    });
}
项目:customstuff4    文件:Attribute.java   
static <T> JsonDeserializer<Attribute<T>> deserializer(Type elementType)
{
    return (json, typeOfT, context) ->
    {


        if (isMetaMap(json))
        {
            FromMap<T> map = new FromMap<>();
            json.getAsJsonObject().entrySet()
                .forEach(e -> map.addEntry(Integer.parseInt(e.getKey()), context.deserialize(e.getValue(), elementType)));
            return map;
        } else
        {
            return constant(context.deserialize(json, elementType));
        }
    };
}
项目:customstuff4    文件:TestUtil.java   
public static Gson createGson()
{
    Bootstrap.register();

    if (gson == null)
    {
        GsonBuilder gsonBuilder = new GsonBuilder();

        if (!registered)
        {
            new VanillaPlugin().registerContent(CustomStuff4.contentRegistry);
            registered = true;
        }

        for (Pair<Type, JsonDeserializer<?>> pair : CustomStuff4.contentRegistry.getDeserializers())
        {
            gsonBuilder.registerTypeAdapter(pair.getLeft(), pair.getRight());
        }

        gson = gsonBuilder.create();
    }

    return gson;
}
项目:basicapp    文件:RetrofitHelper.java   
/**
 * 构建GSON转换器
 * @return GsonConverterFactory
 */
private static GsonConverterFactory buildGsonConverterFactory(){
    GsonBuilder builder = new GsonBuilder();
    builder.setLenient();

    // 注册类型转换适配器
    builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
        @Override
        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            return null == json ? null : new Date(json.getAsLong());
        }
    });

    Gson gson = builder.create();
    return GsonConverterFactory.create(gson);
}
项目:RoadLab-Pro    文件:RestClient.java   
private Retrofit getRetrofitInstance() {
    if (retrofit == null) {
        Gson gson = new GsonBuilder()
                .registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
                    public Date deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
                        return new Date(json.getAsJsonPrimitive().getAsLong());
                    }
                })
                .setPrettyPrinting()
                .create();

        retrofit = new Retrofit.Builder()
                .client(getUnsafeOkHttpClient())
                .baseUrl(Constants.GOOGLE_BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
        retrofit.client().interceptors().add(new RequestInterceptor());
    }
    return retrofit;
}
项目:oson    文件:CustomTypeAdaptersTest.java   
@SuppressWarnings("rawtypes")
public void testCustomDeserializerInvokedForPrimitives() {
  Gson gson = new GsonBuilder()
      .registerTypeAdapter(boolean.class, new JsonDeserializer() {
        @Override
        public Object deserialize(JsonElement json, Type t, JsonDeserializationContext context) {
          return json.getAsInt() != 0;
        }
      })
      .create();
  assertEquals(Boolean.TRUE, gson.fromJson("1", boolean.class));
  assertEquals(Boolean.TRUE, gson.fromJson("true", Boolean.class));

  assertEquals(Boolean.TRUE, oson.fromJson("1", boolean.class));
  assertEquals(Boolean.TRUE, oson.fromJson("true", Boolean.class));
}
项目:GankEssence    文件:RetrofitHelper.java   
/**
 * 构建GSON转换器
 * @return GsonConverterFactory
 */
private static GsonConverterFactory buildGsonConverterFactory(){
    GsonBuilder builder = new GsonBuilder();
    builder.setLenient();

    // 注册类型转换适配器
    builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
        @Override
        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            return null == json ? null : new Date(json.getAsLong());
        }
    });

    Gson gson = builder.create();
    return GsonConverterFactory.create(gson);
}
项目:erlymon-monitor-android    文件:GsonModule.java   
@Provides
@Singleton
Gson provideGson(SharedPreferences sharedPreferences) {
    return new GsonBuilder()
            //.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
            .registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
                final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.ENGLISH);
                @Override
                public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
                    try {
                        return new Date(df.parse(json.getAsString()).getTime());
                    } catch (final java.text.ParseException e) {
                        //e.printStackTrace();
                        return null;
                    }
                }
            })
            .setVersion(sharedPreferences.getFloat("protocolVersion", 3.4f))
            //.setVersion(3.4)
            .create();
}
项目:cosmic    文件:NiciraNvpApi.java   
private void createRestConnector(final Builder builder) {
    final Map<Class<?>, JsonDeserializer<?>> classToDeserializerMap = new HashMap<>();
    classToDeserializerMap.put(NatRule.class, new NatRuleAdapter());
    classToDeserializerMap.put(RoutingConfig.class, new RoutingConfigAdapter());

    final NiciraRestClient niciraRestClient = NiciraRestClient.create()
                                                              .client(builder.httpClient)
                                                              .clientContext(builder.httpClientContext)
                                                              .hostname(builder.host)
                                                              .username(builder.username)
                                                              .password(builder.password)
                                                              .loginUrl(NiciraConstants.LOGIN_URL)
                                                              .executionLimit(DEFAULT_MAX_RETRIES)
                                                              .build();

    restConnector = RESTServiceConnector.create()
                                        .classToDeserializerMap(classToDeserializerMap)
                                        .client(niciraRestClient)
                                        .build();
}
项目:gandalf    文件:Gandalf.java   
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);
}
项目:gandalf    文件:BootstrapApi.java   
/**
 * Creates a bootstrap api class
 *
 * @param context            - Android context used for setting up http cache directory
 * @param okHttpClient       - OkHttpClient to be used for requests, falls back to default if null
 * @param bootStrapUrl       - url to fetch the bootstrap file from
 * @param customDeserializer - a custom deserializer for parsing the JSON response
 */
public BootstrapApi(Context context, @Nullable OkHttpClient okHttpClient, String bootStrapUrl,
                    @Nullable JsonDeserializer<Bootstrap> customDeserializer) {
    this.bootStrapUrl = bootStrapUrl;
    this.customDeserializer = customDeserializer;

    if (okHttpClient == null) {
        File cacheDir = context.getCacheDir();
        Cache cache = new Cache(cacheDir, DEFAULT_CACHE_SIZE);

        this.okHttpClient = new OkHttpClient.Builder()
                .cache(cache)
                .connectTimeout(DEFAULT_CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS)
                .readTimeout(DEFAULT_CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS)
                .build();
    } else {
        this.okHttpClient = okHttpClient;
    }
}
项目:thunderboard-android    文件:ShortenUrl.java   
public static GsonBuilder getGsonBuilder() {
    GsonBuilder builder = new GsonBuilder();

    // class types
    builder.registerTypeAdapter(Integer.class, new JsonDeserializer<Integer>() {
        @Override
        public Integer deserialize(JsonElement json, Type typeOfT,
                                   JsonDeserializationContext context) throws JsonParseException {
            try {
                return Integer.valueOf(json.getAsInt());
            } catch (NumberFormatException e) {
                return null;
            }
        }
    });
    return builder;
}
项目:Watson-Work-Services-Java-SDK    文件:ResultParser.java   
/**
 * @param clazz
 *            Class with which to initialise the ResultParser
 * @param dateFormat
 *            String dateFormat to deserialise JSON with, currently only accepts "MILIS"
 * 
 * @since 0.5.0
 */
public ResultParser(Class<T> clazz, String dateFormat) {
    this.clazz = clazz;
    GsonBuilder builder = new GsonBuilder();
    if ("MILIS".equals(dateFormat)) {
        builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
            public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
                return new Date(json.getAsJsonPrimitive().getAsLong());
            }
        });

    } else {
        builder.setDateFormat(dateFormat);
    }
    builder.registerTypeAdapter(TokenType.class, new TokenTypeDeserializer());
    builder.registerTypeAdapter(TokenScope.class, new TokenScopeDeserializer());
    builder.registerTypeAdapter(PresenceStatus.class, new PersonPresenceDeserializer());
    builder.registerTypeAdapter(AnnotationType.class, new AnnotationTypeDeserializer());
    this.gson = builder.create();
}
项目:atlantis    文件:JsonSerializers.java   
/**
 * Returns a new JSON deserializer, specialized for {@link SettingsManager}
 * objects.
 *
 * @return The deserializer to parse {@code SettingsManager} JSON with.
 */
static JsonDeserializer<SettingsManager> newSettingsDeserializer() {
    return (json, typeOfT, context) -> {
        if (json == null)
            return null;

        SettingsManager settingsManager = new SettingsManager();
        if (json.isJsonObject()) {
            JsonObject jsonObject = json.getAsJsonObject();
            for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
                JsonElement jsonElement = entry.getValue();
                if (jsonElement.isJsonPrimitive())
                    settingsManager.set(entry.getKey(), jsonElement.getAsString());
            }
        }

        return settingsManager;
    };
}
项目:azure-mobile-apps-android-client    文件:SerializationTests.java   
public void testCustomDeserializationUsingWithoutUsingMobileServiceTable() {
    String serializedObject = "{\"address\":{\"zipcode\":1313,\"country\":\"US\",\"streetaddress\":\"1345 Washington St\"},\"firstName\":\"John\",\"lastName\":\"Doe\"}";
    JsonObject jsonObject = new JsonParser().parse(serializedObject).getAsJsonObject();

    gsonBuilder.registerTypeAdapter(Address.class, new JsonDeserializer<Address>() {

        @Override
        public Address deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
            Address a = new Address(arg0.getAsJsonObject().get("streetaddress").getAsString(), arg0.getAsJsonObject().get("zipcode").getAsInt(), arg0
                    .getAsJsonObject().get("country").getAsString());

            return a;
        }

    });

    ComplexPersonTestObject deserializedPerson = gsonBuilder.create().fromJson(jsonObject, ComplexPersonTestObject.class);

    // Asserts
    assertEquals("John", deserializedPerson.getFirstName());
    assertEquals("Doe", deserializedPerson.getLastName());
    assertEquals(1313, deserializedPerson.getAddress().getZipCode());
    assertEquals("US", deserializedPerson.getAddress().getCountry());
    assertEquals("1345 Washington St", deserializedPerson.getAddress().getStreetAddress());
}
项目:packagedrone    文件:ChannelModelProvider.java   
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 ();
}
项目:Jockey    文件:DemoMusicStore.java   
@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();
    }
}
项目:QiQuYingServer    文件:JsonUtil.java   
/**
 * 将json转换成bean对象
 * @param jsonStr
 * @param cl
 * @return
 */
@SuppressWarnings("unchecked")
public static <T> T  jsonToBeanDateSerializer(String jsonStr,Class<T> cl,final String pattern){
    Object obj=null;
    gson=new GsonBuilder().registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
        public Date deserialize(JsonElement json, Type typeOfT,
                JsonDeserializationContext context)
                throws JsonParseException {
                SimpleDateFormat format=new SimpleDateFormat(pattern);
                String dateStr=json.getAsString();
            try {
                return format.parse(dateStr);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return null;
        }
    }).setDateFormat(pattern).create();
    if(gson!=null){
        obj=gson.fromJson(jsonStr, cl);
    }
    return (T)obj;
}
项目:thermospy    文件:LogSession.java   
public static LogSession fromJson(String jsonString) throws JsonSyntaxException
{
    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();
    LogSession logSession =null;
    try {
      logSession = gson.fromJson(jsonString, LogSession.class);
    } catch (JsonSyntaxException ex)
    {
        throw ex;
    }
    return logSession;
}
项目:thermospy    文件:StopLogSessionReq.java   
@Override
public void onOkResponse(JSONObject response) {
    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 {
        LogSession logSession = gson.fromJson(response.toString(), LogSession.class);
        mListener.onStopLogSessionRecv(logSession);
    } catch (JsonSyntaxException ex)
    {
        mListener.onStopLogSessionError();
    }
}
项目:thermospy    文件:StartLogSessionReq.java   
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 (JSONException | JsonIOException e) {
        return null;
    }
}
项目:thermospy    文件:StartLogSessionReq.java   
@Override
public void onOkResponse(JSONObject response) {
    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 {
        LogSession logSession = gson.fromJson(response.toString(), LogSession.class);
        mListener.onStartLogSessionRecv(logSession);
    } catch (JsonSyntaxException ex)
    {
        mListener.onStartLogSessionError();
    }
}
项目:thermospy    文件:GetTemperatureEntryListReq.java   
@Override
public void onOkResponse(JSONArray response) {
    List<TemperatureEntry> logSessionsList = new ArrayList<TemperatureEntry>();
    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 {
        for (int i = 0; i < response.length(); i++) {
            logSessionsList.add(gson.fromJson(response.getJSONObject(i).toString(), TemperatureEntry.class));
        }
        mListener.onTemperatureEntryRecv(logSessionsList);
    } catch (JSONException ex)
    {
        mListener.onTemperatureEntryError();
    }
}
项目:thermospy    文件:GetLogSessionListReq.java   
@Override
public void onOkResponse(JSONArray response) {
    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 {
        for (int i = 0; i < response.length(); i++) {
            logSessionsList.add(gson.fromJson(response.getJSONObject(i).toString(), LogSession.class));
        }
        mListener.onLogSessionsRecv(logSessionsList);
    } catch (JSONException ex)
    {
        mListener.onLogSessionsError();
    }
}
项目:package-drone    文件:ChannelModelProvider.java   
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 ();
}
项目:CustomThings    文件:CompatUtil.java   
public static void registerDifficultyAdapter(GsonBuilder builder)
{
    builder.registerTypeAdapter(Difficulty.class, new JsonDeserializer<Difficulty>()
    {
        @Override
        public Difficulty deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
        {
            if (json.isJsonPrimitive())
            {
                String name = json.getAsString();
                Difficulty diff = Difficulty.valueOf(name);
                return diff;
            }
            return null;
        }
    });
}
项目:cloudstack    文件:NiciraNvpApi.java   
private NiciraNvpApi(final Builder builder) {
    final Map<Class<?>, JsonDeserializer<?>> classToDeserializerMap = new HashMap<>();
    classToDeserializerMap.put(NatRule.class, new NatRuleAdapter());
    classToDeserializerMap.put(RoutingConfig.class, new RoutingConfigAdapter());

    final NiciraRestClient niciraRestClient = NiciraRestClient.create()
        .client(builder.httpClient)
        .clientContext(builder.httpClientContext)
        .hostname(builder.host)
        .username(builder.username)
        .password(builder.password)
        .loginUrl(NiciraConstants.LOGIN_URL)
        .executionLimit(DEFAULT_MAX_RETRIES)
        .build();
    restConnector = RESTServiceConnector.create()
        .classToDeserializerMap(classToDeserializerMap)
        .client(niciraRestClient)
        .build();
}
项目:jade4ninja    文件:ApiControllerDocTest.java   
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;
}
项目:jade4ninja    文件:ApiControllerTest.java   
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;
}
项目:doctester    文件:ApiControllerDocTest.java   
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;
}
项目:doctester    文件:ApiControllerTest.java   
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;
}
项目:vraptor4    文件:GsonDeserializerTest.java   
@Test
public void shouldBeAbleToDeserializeADogWithDeserializerAdapter() throws Exception {
    List<JsonDeserializer<?>> deserializers = new ArrayList<>();
    List<JsonSerializer<?>> serializers = new ArrayList<>();
    deserializers.add(new DogDeserializer());

    builder = new GsonBuilderWrapper(new MockInstanceImpl<>(serializers), new MockInstanceImpl<>(deserializers), 
            new Serializee(new DefaultReflectionProvider()), new DefaultReflectionProvider());
    deserializer = new GsonDeserialization(builder, provider, request, container, deserializeeInstance);

    InputStream stream = asStream("{'dog':{'name':'Renan Reis','age':'0'}}");

    Object[] deserialized = deserializer.deserialize(stream, dogParameter);

    assertThat(deserialized.length, is(1));
    assertThat(deserialized[0], is(instanceOf(Dog.class)));
    Dog dog = (Dog) deserialized[0];
    assertThat(dog.name, is("Renan"));
    assertThat(dog.age, is(25));
}
项目:vraptor4    文件:GsonJSONSerializationTest.java   
@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());
}
项目:jSpace    文件:jSonUtils.java   
public <T> void register( String uri , Class<T> clazz , JsonSerializer<T> serializer , JsonDeserializer<T> deserializer ) {
    this.dicionary.register(uri, clazz);
    if (serializer != null) {
        builder.registerTypeAdapter(clazz, serializer);
    }
    if (deserializer != null) {
        builder.registerTypeAdapter(clazz, deserializer);
    }
}
项目:dracoon-dropzone    文件:RestClient.java   
/**
 * Create {@link Gson} instance
 */
private void initGson() {
    LOG.debug("Init Gson.");

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Void.class, new JsonDeserializer<Void>() {
        @Override
        public Void deserialize(JsonElement json, Type type, JsonDeserializationContext context)
                throws JsonParseException {
            return null;
        }
    });
    mGson = gsonBuilder.create();
}
项目:happy-news    文件:PostManager.java   
/**
 * Register an adapter to manage the date types as long values.
 *
 * @param builder The GsonBuilder to register the TypeAdapter to.
 */
private void registerTypeAdapter(GsonBuilder builder) {
    builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
            throws JsonParseException {
            return new Date(json.getAsJsonPrimitive().getAsLong());
        }
    });
}
项目:happy-news    文件:SourceManager.java   
/**
 * Register an adapter to manage the date types as long values.
 *
 * @param builder The GsonBuilder to register the TypeAdapter to.
 */
private void registerTypeAdapter(GsonBuilder builder) {
    builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
            throws JsonParseException {
            return new Date(json.getAsJsonPrimitive().getAsLong());
        }
    });
}