Java Code Examples for com.google.gson.JsonDeserializer

The following examples show how to use com.google.gson.JsonDeserializer. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: arcusplatform   Source File: MessagesModule.java    License: Apache License 2.0 7 votes vote down vote up
@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);
}
 
Example 2
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();
}
 
Example 3
Source Project: arcusplatform   Source File: GsonModule.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 4
Source Project: ambari-logsearch   Source File: JsonManagerBase.java    License: Apache License 2.0 6 votes vote down vote up
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());
    }

  };
}
 
Example 5
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;
}
 
Example 6
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());

    }
 
Example 7
Source Project: customstuff4   Source File: Attribute.java    License: GNU General Public License v3.0 6 votes vote down vote up
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));
        }
    };
}
 
Example 8
Source Project: customstuff4   Source File: TestUtil.java    License: GNU General Public License v3.0 6 votes vote down vote up
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;
}
 
Example 9
Source Project: cosmic   Source File: NiciraNvpApi.java    License: Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 10
Source Project: gandalf   Source File: BootstrapApi.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example 11
Source Project: thunderboard-android   Source File: ShortenUrl.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 12
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());
}
 
Example 13
Source Project: triplea   Source File: JsonDecoder.java    License: GNU General Public License v3.0 6 votes vote down vote up
@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();
}
 
Example 14
Source Project: packagedrone   Source File: ChannelModelProvider.java    License: Eclipse Public License 1.0 6 votes vote down vote up
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 15
Source Project: QiQuYingServer   Source File: JsonUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 将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;
}
 
Example 16
Source Project: incubator-gobblin   Source File: FSDagStateStore.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 17
Source Project: cloudstack   Source File: NiciraNvpApi.java    License: Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 18
Source Project: vraptor4   Source File: GsonDeserializerTest.java    License: Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example 19
Source Project: vraptor4   Source File: GsonJSONSerializationTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 20
Source Project: arcusplatform   Source File: TestJSON.java    License: Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 21
Source Project: arcusplatform   Source File: GsonModule.java    License: Apache License 2.0 5 votes vote down vote up
@Provides
public GsonFactory gson(
   Set<TypeAdapterFactory> typeAdapterFactories,
   Set<TypeAdapter<?>> typeAdapters,
   Set<JsonSerializer<?>> serializers,
   Set<JsonDeserializer<?>> deserializers
) {
   return new GsonFactory(typeAdapterFactories, typeAdapters, serializers, deserializers, serializeNulls);
}
 
Example 22
Source Project: arcusplatform   Source File: GsonFactory.java    License: Apache License 2.0 5 votes vote down vote up
public GsonFactory(
      Set<TypeAdapterFactory> typeAdapterFactories,
      Set<TypeAdapter<?>> typeAdapters,
      Set<JsonSerializer<?>> serializers,
      Set<JsonDeserializer<?>> deserializers
) {
   this(typeAdapterFactories, typeAdapters, serializers, deserializers, true);
}
 
Example 23
Source Project: arcusplatform   Source File: GsonFactory.java    License: Apache License 2.0 5 votes vote down vote up
public GsonFactory(
      Set<TypeAdapterFactory> typeAdapterFactories,
      Set<TypeAdapter<?>> typeAdapters,
      Set<JsonSerializer<?>> serializers,
      Set<JsonDeserializer<?>> deserializers,
      boolean serializeNulls
) {
   this.gson = create(typeAdapterFactories, typeAdapters, serializers, deserializers, serializeNulls);
}
 
Example 24
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);
    };
}
 
Example 25
Source Project: YCAudioPlayer   Source File: JsonUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 第二种方式
 * @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;
}
 
Example 26
Source Project: icure-backend   Source File: ICureHelper.java    License: GNU General Public License v2.0 5 votes vote down vote up
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;
 }
 
Example 27
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();
}
 
Example 28
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();

    }
 
Example 29
Source Project: vraptor4   Source File: DefaultStatusTest.java    License: Apache License 2.0 5 votes vote down vote up
@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\"")));
}
 
Example 30
Source Project: esjc   Source File: ClusterEndpointDiscoverer.java    License: MIT License 5 votes vote down vote up
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();
}