当前位置: 首页>>代码示例>>Java>>正文


Java JsonDeserializer类代码示例

本文整理汇总了Java中com.google.gson.JsonDeserializer的典型用法代码示例。如果您正苦于以下问题:Java JsonDeserializer类的具体用法?Java JsonDeserializer怎么用?Java JsonDeserializer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


JsonDeserializer类属于com.google.gson包,在下文中一共展示了JsonDeserializer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: jsonToBeanDateSerializer

import com.google.gson.JsonDeserializer; //导入依赖的package包/类
/**
 * 将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;
}
 
开发者ID:tong12580,项目名称:OutsourcedProject,代码行数:23,代码来源:JsonUtil.java

示例2: createService

import com.google.gson.JsonDeserializer; //导入依赖的package包/类
/**
 * 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);
}
 
开发者ID:whats-this,项目名称:owo.java,代码行数:31,代码来源:OwO.java

示例3: createGson

import com.google.gson.JsonDeserializer; //导入依赖的package包/类
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();
}
 
开发者ID:hsj-xiaokang,项目名称:OSchina_resources_android,代码行数:25,代码来源:AppOperator.java

示例4: gatherParsers

import com.google.gson.JsonDeserializer; //导入依赖的package包/类
@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);
        }
    });
}
 
开发者ID:tterrag1098,项目名称:MCBot,代码行数:25,代码来源:CommandQuote.java

示例5: deserializer

import com.google.gson.JsonDeserializer; //导入依赖的package包/类
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));
        }
    };
}
 
开发者ID:cubex2,项目名称:customstuff4,代码行数:19,代码来源:Attribute.java

示例6: createGson

import com.google.gson.JsonDeserializer; //导入依赖的package包/类
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;
}
 
开发者ID:cubex2,项目名称:customstuff4,代码行数:25,代码来源:TestUtil.java

示例7: buildGsonConverterFactory

import com.google.gson.JsonDeserializer; //导入依赖的package包/类
/**
 * 构建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);
}
 
开发者ID:qiaop,项目名称:basicapp,代码行数:20,代码来源:RetrofitHelper.java

示例8: getRetrofitInstance

import com.google.gson.JsonDeserializer; //导入依赖的package包/类
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;
}
 
开发者ID:WorldBank-Transport,项目名称:RoadLab-Pro,代码行数:21,代码来源:RestClient.java

示例9: testCustomDeserializerInvokedForPrimitives

import com.google.gson.JsonDeserializer; //导入依赖的package包/类
@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));
}
 
开发者ID:osonus,项目名称:oson,代码行数:17,代码来源:CustomTypeAdaptersTest.java

示例10: provideGson

import com.google.gson.JsonDeserializer; //导入依赖的package包/类
@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();
}
 
开发者ID:erlymon,项目名称:erlymon-monitor-android,代码行数:22,代码来源:GsonModule.java

示例11: createRestConnector

import com.google.gson.JsonDeserializer; //导入依赖的package包/类
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();
}
 
开发者ID:MissionCriticalCloud,项目名称:cosmic,代码行数:21,代码来源:NiciraNvpApi.java

示例12: createInstance

import com.google.gson.JsonDeserializer; //导入依赖的package包/类
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);
}
 
开发者ID:btkelly,项目名称:gandalf,代码行数:18,代码来源:Gandalf.java

示例13: BootstrapApi

import com.google.gson.JsonDeserializer; //导入依赖的package包/类
/**
 * 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;
    }
}
 
开发者ID:btkelly,项目名称:gandalf,代码行数:27,代码来源:BootstrapApi.java

示例14: getGsonBuilder

import com.google.gson.JsonDeserializer; //导入依赖的package包/类
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;
}
 
开发者ID:SiliconLabs,项目名称:thunderboard-android,代码行数:18,代码来源:ShortenUrl.java

示例15: ResultParser

import com.google.gson.JsonDeserializer; //导入依赖的package包/类
/**
 * @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();
}
 
开发者ID:OpenCode4Workspace,项目名称:Watson-Work-Services-Java-SDK,代码行数:28,代码来源:ResultParser.java


注:本文中的com.google.gson.JsonDeserializer类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。