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

下面列出了怎么用com.google.gson.JsonDeserializer的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: youtube-jextractor   文件: YoutubeJExtractor.java
private Gson initGson() {
    GsonBuilder gsonBuilder = new GsonBuilder();
    JsonDeserializer<Cipher> cipherDeserializer = (json, typeOfT, context) -> {
        Cipher cipher = gson.fromJson(urlParamsToJson(json.getAsString()), Cipher.class);
        cipher.setUrl(urlDecode(cipher.getUrl()));
        return cipher;
    };

    JsonDeserializer<PlayerResponse> playerResponseJsonDeserializer = (json, typeOfT, context) -> {
        Gson tempGson = new GsonBuilder().registerTypeAdapter(Cipher.class, cipherDeserializer).create();
        String jsonRaw = json.getAsString();
        return tempGson.fromJson(jsonRaw, PlayerResponse.class);
    };
    gsonBuilder.registerTypeAdapter(PlayerResponse.class, playerResponseJsonDeserializer);
    return gsonBuilder.create();
}
 
源代码2 项目: arcusplatform   文件: MessagesModule.java
@Override
protected void configure() {
   Multibinder<TypeAdapterFactory> typeAdapterFactoryBinder = Multibinder.newSetBinder(binder(), new TypeLiteral<TypeAdapterFactory>() {});
   typeAdapterFactoryBinder.addBinding().to(AddressTypeAdapterFactory.class);
   typeAdapterFactoryBinder.addBinding().to(GsonReferenceTypeAdapterFactory.class);
   typeAdapterFactoryBinder.addBinding().to(MessageTypeAdapterFactory.class);
   typeAdapterFactoryBinder.addBinding().to(MessageBodyTypeAdapterFactory.class);

   Multibinder<TypeAdapter<?>> typeAdapterBinder = Multibinder.newSetBinder(binder(), new TypeLiteral<TypeAdapter<?>>() {});
   typeAdapterBinder.addBinding().to(ProtocolDeviceIdTypeAdapter.class);
   typeAdapterBinder.addBinding().to(HubMessageTypeAdapter.class);

   Multibinder<JsonSerializer<?>> serializerBinder = Multibinder.newSetBinder(binder(), new TypeLiteral<JsonSerializer<?>>() {});
   serializerBinder.addBinding().to(ClientMessageTypeAdapter.class);
   serializerBinder.addBinding().to(ResultTypeAdapter.class);

   Multibinder<JsonDeserializer<?>> deserializerBinder = Multibinder.newSetBinder(binder(), new TypeLiteral<JsonDeserializer<?>>() {});
   deserializerBinder.addBinding().to(ClientMessageTypeAdapter.class);
   deserializerBinder.addBinding().to(ResultTypeAdapter.class);
}
 
源代码3 项目: arcusplatform   文件: GsonModule.java
@Override
protected void configure() {
   bind(com.iris.io.json.JsonSerializer.class).to(GsonSerializerImpl.class);
   bind(com.iris.io.json.JsonDeserializer.class).to(GsonDeserializerImpl.class);

   Multibinder
   	.newSetBinder(binder(), new TypeLiteral<com.google.gson.JsonSerializer<?>>() {})
   	.addBinding()
   	.to(AttributeMapSerializer.class);
   Multibinder
   	.newSetBinder(binder(), new TypeLiteral<com.google.gson.JsonDeserializer<?>>() {})
   	.addBinding()
   	.to(AttributeMapSerializer.class);
   Multibinder
      .newSetBinder(binder(), new TypeLiteral<TypeAdapter<?>>() {})
      .addBinding()
      .to(ByteArrayToBase64TypeAdapter.class);
   Multibinder
      .newSetBinder(binder(), new TypeLiteral<TypeAdapterFactory>() {})
      .addBinding()
      .to(TypeTypeAdapterFactory.class);
}
 
源代码4 项目: ambari-logsearch   文件: JsonManagerBase.java
public JsonManagerBase() {
  jsonDateSerialiazer = new JsonSerializer<Date>() {

    @Override
    public JsonElement serialize(Date paramT, java.lang.reflect.Type paramType, JsonSerializationContext paramJsonSerializationContext) {
      return paramT == null ? null : new JsonPrimitive(paramT.getTime());
    }
  };

  jsonDateDeserialiazer = new JsonDeserializer<Date>() {

    @Override
    public Date deserialize(JsonElement json, java.lang.reflect.Type typeOfT, JsonDeserializationContext context)
      throws JsonParseException {
      return json == null ? null : new Date(json.getAsLong());
    }

  };
}
 
源代码5 项目: icure-backend   文件: GsonMessageBodyHandler.java
public Gson getGson() {
	if (gson == null) {
		final GsonBuilder gsonBuilder = new GsonBuilder();

		gsonBuilder
				.registerTypeAdapter(PaginatedDocumentKeyIdPair.class, (JsonDeserializer<PaginatedDocumentKeyIdPair>) (json, typeOfT, context) -> {
					Map<String, Object> obj = context.deserialize(json, Map.class);
					return new PaginatedDocumentKeyIdPair<>((List<String>) obj.get("startKey"), (String) obj.get("startKeyDocId"));
				})
				.registerTypeAdapter(Predicate.class, new DiscriminatedTypeAdapter<>(Predicate.class))
				.registerTypeHierarchyAdapter(byte[].class, new ByteArrayToBase64TypeAdapter())
				.registerTypeAdapter(org.taktik.icure.dto.filter.Filter.class, new DiscriminatedTypeAdapter<>(org.taktik.icure.dto.filter.Filter.class))
				.registerTypeAdapter(org.taktik.icure.dto.gui.Editor.class, new DiscriminatedTypeAdapter<>(org.taktik.icure.dto.gui.Editor.class))
				.registerTypeAdapter(org.taktik.icure.dto.gui.type.Data.class, new DiscriminatedTypeAdapter<>(org.taktik.icure.dto.gui.type.Data.class))
				.registerTypeAdapter(org.taktik.icure.services.external.rest.v1.dto.filter.Filter.class, new DiscriminatedTypeAdapter<>(org.taktik.icure.services.external.rest.v1.dto.filter.Filter.class))
				.registerTypeAdapter(org.taktik.icure.services.external.rest.v1.dto.gui.type.Data.class, new DiscriminatedTypeAdapter<>(org.taktik.icure.services.external.rest.v1.dto.gui.type.Data.class))
				.registerTypeAdapter(org.taktik.icure.services.external.rest.v1.dto.gui.Editor.class, new DiscriminatedTypeAdapter<>(org.taktik.icure.services.external.rest.v1.dto.gui.Editor.class))
				.registerTypeAdapter(Double.class, (JsonSerializer<Double>) (src, typeOfSrc, context) -> src == null ? null : new JsonPrimitive(src.isNaN() ? 0d : src.isInfinite() ? (src > 0 ? MAX_VALUE : MIN_VALUE) : src))
				.registerTypeAdapter(Boolean.class, (JsonDeserializer<Boolean>) (json, typeOfSrc, context) -> ((JsonPrimitive)json).isBoolean() ? json.getAsBoolean() : ((JsonPrimitive)json).isString() ? json.getAsString().equals("true") : json.getAsInt() != 0);
		gson = gsonBuilder.create();
	}
	return gson;
}
 
源代码6 项目: cryptotrader   文件: QuoinexContext.java
public QuoinexContext() {

        super(ID);

        gson = new GsonBuilder()
                .registerTypeAdapter(Instant.class,
                        (JsonDeserializer<Instant>) (j, t, c) -> Instant.ofEpochSecond(j.getAsLong())
                )
                .registerTypeAdapter(BigDecimal.class,
                        (JsonDeserializer<BigDecimal>) (j, t, c) -> StringUtils.isEmpty(j.getAsString()) ? null : j.getAsBigDecimal()
                )
                .create();

        jwtHead = Base64.getUrlEncoder().encodeToString(gson.toJson(Stream.of(
                new SimpleEntry<>("typ", "JWT"),
                new SimpleEntry<>("alg", "HS256")
        ).collect(Collectors.toMap(Entry::getKey, Entry::getValue))).getBytes());

    }
 
源代码7 项目: 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));
        }
    };
}
 
源代码8 项目: 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;
}
 
源代码9 项目: 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();
}
 
源代码10 项目: 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;
    }
}
 
源代码11 项目: 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;
}
 
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());
}
 
源代码13 项目: triplea   文件: JsonDecoder.java
@VisibleForTesting
static Gson decoder() {
  return new GsonBuilder()
      .registerTypeAdapter(
          Instant.class,
          (JsonDeserializer<Instant>)
              (json, type, jsonDeserializationContext) -> {
                Preconditions.checkState(
                    json.getAsJsonPrimitive().getAsString().contains("."),
                    "Unexpected json date format, expected {[epoch second].[epoch nano]}, "
                        + "value received was: "
                        + json.getAsJsonPrimitive().getAsString());

                final long[] timeStampParts = splitTimestamp(json);
                return Instant.ofEpochSecond(timeStampParts[0], timeStampParts[1]);
              })
      .create();
}
 
源代码14 项目: 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 ();
}
 
源代码15 项目: 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;
}
 
源代码16 项目: incubator-gobblin   文件: FSDagStateStore.java
public FSDagStateStore(Config config, Map<URI, TopologySpec> topologySpecMap) throws IOException {
  this.dagCheckpointDir = config.getString(DAG_STATESTORE_DIR);
  File checkpointDir = new File(this.dagCheckpointDir);
  if (!checkpointDir.exists()) {
    if (!checkpointDir.mkdirs()) {
      throw new IOException("Could not create dag state store dir - " + this.dagCheckpointDir);
    }
  }

  JsonSerializer<List<JobExecutionPlan>> serializer = new JobExecutionPlanListSerializer();
  JsonDeserializer<List<JobExecutionPlan>> deserializer = new JobExecutionPlanListDeserializer(topologySpecMap);

  /** {@link Type} object will need to strictly match with the generic arguments being used
   * to define {@link GsonSerDe}
   * Due to type erasure, the {@link Type} needs to initialized here instead of inside {@link GsonSerDe}.
   * */
  Type typeToken = new TypeToken<List<JobExecutionPlan>>(){}.getType();
  this.serDe = new GsonSerDe<>(typeToken, serializer, deserializer);
}
 
源代码17 项目: 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();
}
 
源代码18 项目: 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));
}
 
源代码19 项目: 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());
}
 
源代码20 项目: arcusplatform   文件: TestJSON.java
@Before
public void setUp() throws Exception {
 GsonFactory gsonFactory = new GsonFactory(
 		null,
 		null,
 		IrisCollections.<JsonSerializer<?>>setOf(new DefaultPrincipalTypeAdapter(), 
 				new PrincipalCollectionTypeAdapter()),
	IrisCollections.<JsonDeserializer<?>>setOf(new DefaultPrincipalTypeAdapter(), 
 				new PrincipalCollectionTypeAdapter()));
 gson = gsonFactory.get();
}
 
源代码21 项目: arcusplatform   文件: GsonModule.java
@Provides
public GsonFactory gson(
   Set<TypeAdapterFactory> typeAdapterFactories,
   Set<TypeAdapter<?>> typeAdapters,
   Set<JsonSerializer<?>> serializers,
   Set<JsonDeserializer<?>> deserializers
) {
   return new GsonFactory(typeAdapterFactories, typeAdapters, serializers, deserializers, serializeNulls);
}
 
源代码22 项目: arcusplatform   文件: GsonFactory.java
public GsonFactory(
      Set<TypeAdapterFactory> typeAdapterFactories,
      Set<TypeAdapter<?>> typeAdapters,
      Set<JsonSerializer<?>> serializers,
      Set<JsonDeserializer<?>> deserializers
) {
   this(typeAdapterFactories, typeAdapters, serializers, deserializers, true);
}
 
源代码23 项目: arcusplatform   文件: GsonFactory.java
public GsonFactory(
      Set<TypeAdapterFactory> typeAdapterFactories,
      Set<TypeAdapter<?>> typeAdapters,
      Set<JsonSerializer<?>> serializers,
      Set<JsonDeserializer<?>> deserializers,
      boolean serializeNulls
) {
   this.gson = create(typeAdapterFactories, typeAdapters, serializers, deserializers, serializeNulls);
}
 
private static JsonDeserializer<PullRequestInfo> createPullRequestInfoJsonDeserialiser() {
    return (jsonElement, type, jsonDeserializationContext) -> {
        JsonObject jsonObject = jsonElement.getAsJsonObject();
        long parsedDate = 0;
        try {
            parsedDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
                    .parse(jsonObject.get("analysisDate").getAsString()).getTime();
        } catch (ParseException e) {
            LOGGER.warn("Could not parse date from Pull Requests API response. Will use '0' date", e);
        }
        final String base = Optional.ofNullable(jsonObject.get("base")).map(JsonElement::getAsString).orElse(null);
        return new PullRequestInfo(jsonObject.get("key").getAsString(), jsonObject.get("branch").getAsString(),
                base, parsedDate);
    };
}
 
源代码25 项目: YCAudioPlayer   文件: JsonUtils.java
/**
 * 第二种方式
 * @return              Gson对象
 */
public static Gson getGson() {
    if (gson == null) {
        gson = new GsonBuilder()            //builder构建者模式
                .setLenient()               //json宽松
                .enableComplexMapKeySerialization() //支持Map的key为复杂对象的形式
                .setPrettyPrinting()        //格式化输出
                .serializeNulls()           //智能null
                //.setDateFormat("yyyy-MM-dd HH:mm:ss:SSS")       //格式化时间
                .disableHtmlEscaping()      //默认是GSON把HTML转义的
                .registerTypeAdapter(int.class, new JsonDeserializer<Integer>() {
                    //根治服务端int 返回""空字符串
                    @Override
                    public Integer deserialize(JsonElement json, Type typeOfT,
                                               JsonDeserializationContext context)
                            throws JsonParseException {
                        //try catch不影响效率
                        try {
                            return json.getAsInt();
                        } catch (NumberFormatException e) {
                            return 0;
                        }
                    }
                })
                .create();
    }
    return gson;
}
 
源代码26 项目: icure-backend   文件: ICureHelper.java
public Gson getGson() {
     if (gson == null) {
         final GsonBuilder gsonBuilder = new GsonBuilder();

gsonBuilder.serializeSpecialFloatingPointValues().registerTypeAdapter(PaginatedDocumentKeyIdPair.class, (JsonDeserializer<PaginatedDocumentKeyIdPair>) (json, typeOfT, context) -> {
	Map<String,Object> obj = context.deserialize(json,Map.class);
	return new PaginatedDocumentKeyIdPair<>((List<String>)obj.get("startKey"), (String)obj.get("startKeyDocId"));
}).registerTypeAdapter(Filter.class, new DiscriminatedTypeAdapter<>(Filter.class));

         gson = gsonBuilder.create();
     }
     return gson;
 }
 
源代码27 项目: icure-backend   文件: GsonSerializerFactory.java
public Gson getGsonSerializer() {
	final GsonBuilder gsonBuilder = new GsonBuilder();

	gsonBuilder.serializeSpecialFloatingPointValues()
		.registerTypeAdapter(Predicate.class, new DiscriminatedTypeAdapter<>(Predicate.class))
		.registerTypeAdapter(Filter.class, new DiscriminatedTypeAdapter<>(Filter.class))
		.registerTypeAdapter(Editor.class, new DiscriminatedTypeAdapter<>(Editor.class))
		.registerTypeAdapter(Data.class, new DiscriminatedTypeAdapter<>(Data.class))
		.registerTypeAdapter(org.taktik.icure.services.external.rest.v1.dto.filter.Filter.class, new DiscriminatedTypeAdapter<>(org.taktik.icure.services.external.rest.v1.dto.filter.Filter.class))
		.registerTypeAdapter(org.taktik.icure.services.external.rest.v1.dto.gui.type.Data.class, new DiscriminatedTypeAdapter<>(org.taktik.icure.services.external.rest.v1.dto.gui.type.Data.class))
		.registerTypeAdapter(org.taktik.icure.services.external.rest.v1.dto.gui.Editor.class, new DiscriminatedTypeAdapter<>(org.taktik.icure.services.external.rest.v1.dto.gui.Editor.class))
		.registerTypeAdapter(byte[].class, (JsonDeserializer<byte[]>) (json, typeOfT, context) -> {
			if (json.isJsonPrimitive() && ((JsonPrimitive)json).isString()) {
				return Base64.getDecoder().decode(json.getAsString());
			} else if (json.isJsonArray() && (((JsonArray)json).size() == 0 || ((JsonArray)json).get(0).isJsonPrimitive() )) {
				byte[] res = new byte[((JsonArray)json).size()];
				for (int i=0;i<((JsonArray)json).size();i++) {
					res[i] = ((JsonArray)json).get(i).getAsByte();
				}
				return res;
			}
			throw new IllegalArgumentException("byte[] are expected to be encoded as base64 strings");
		})
	;

	return gsonBuilder.create();
}
 
源代码28 项目: cryptotrader   文件: BtcboxContext.java
public BtcboxContext() {

        super(ID);

        gson = new GsonBuilder()
                .registerTypeAdapter(Instant.class,
                        (JsonDeserializer<Instant>) (j, t, c) -> Instant.ofEpochSecond(j.getAsLong())
                )
                .registerTypeAdapter(ZonedDateTime.class,
                        (JsonDeserializer<ZonedDateTime>) (j, t, c) -> ZonedDateTime.parse(j.getAsString(), DTF)
                )
                .create();

    }
 
源代码29 项目: vraptor4   文件: DefaultStatusTest.java
@SuppressWarnings("deprecation")
@Test
public void shouldSerializeErrorMessagesInJSON() throws Exception {
	Message normal = new SimpleMessage("category", "The message");
	I18nMessage i18ned = new I18nMessage("category", "message");
	i18ned.setBundle(new SingletonResourceBundle("message", "Something else"));

	List<JsonSerializer<?>> gsonSerializers = new ArrayList<>();
	List<JsonDeserializer<?>> gsonDeserializers = new ArrayList<>();
	gsonSerializers.add(new MessageGsonConverter());

	GsonSerializerBuilder gsonBuilder = new GsonBuilderWrapper(new MockInstanceImpl<>(gsonSerializers), new MockInstanceImpl<>(gsonDeserializers), 
			new Serializee(new DefaultReflectionProvider()), new DefaultReflectionProvider());
	MockSerializationResult result = new MockSerializationResult(null, null, gsonBuilder, new DefaultReflectionProvider()) {
		@Override
		public <T extends View> T use(Class<T> view) {
			return view.cast(new DefaultRepresentationResult(new FormatResolver() {
				@Override
				public String getAcceptFormat() {
					return "json";
				}

			}, this, new MockInstanceImpl<Serialization>(super.use(JSONSerialization.class))));
		}
	};
	DefaultStatus status = new DefaultStatus(response, result, config, new JavassistProxifier(), router);

	status.badRequest(Arrays.asList(normal, i18ned));

	String serialized = result.serializedResult();
	assertThat(serialized, containsString("\"message\":\"The message\""));
	assertThat(serialized, containsString("\"category\":\"category\""));
	assertThat(serialized, containsString("\"message\":\"Something else\""));
	assertThat(serialized, not(containsString("\"validationMessage\"")));
	assertThat(serialized, not(containsString("\"i18nMessage\"")));
}
 
源代码30 项目: esjc   文件: ClusterEndpointDiscoverer.java
public ClusterEndpointDiscoverer(ClusterNodeSettings settings, ScheduledExecutorService scheduler) {
    checkNotNull(settings, "settings is null");
    checkNotNull(scheduler, "scheduler is null");

    this.settings = settings;
    this.scheduler = scheduler;

    gson = new GsonBuilder()
        .registerTypeAdapter(Instant.class,
            (JsonDeserializer<Instant>) (json, type, ctx) -> Instant.parse(json.getAsJsonPrimitive().getAsString()))
        .create();
}
 
 类所在包
 类方法
 同包方法