com.google.gson.JsonDeserializer Java Examples

The following examples show how to use com.google.gson.JsonDeserializer. 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 File: MessagesModule.java    From arcusplatform with 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
Source File: GsonJSONSerializationTest.java    From vraptor4 with 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 #3
Source File: GsonModule.java    From arcusplatform with 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 File: GsonMessageBodyHandler.java    From icure-backend with GNU General Public License v2.0 6 votes vote down vote up
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 #5
Source File: JsonManagerBase.java    From ambari-logsearch with 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 #6
Source File: QuoinexContext.java    From cryptotrader with GNU Affero General Public License v3.0 6 votes vote down vote up
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 File: Attribute.java    From customstuff4 with 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 File: TestUtil.java    From customstuff4 with 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 File: NiciraNvpApi.java    From cosmic with 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 File: BootstrapApi.java    From gandalf with 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 File: SerializationTests.java    From azure-mobile-apps-android-client with Apache License 2.0 6 votes vote down vote up
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 #12
Source File: JsonDecoder.java    From triplea with 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 #13
Source File: ChannelModelProvider.java    From packagedrone with 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 #14
Source File: JsonUtil.java    From QiQuYingServer with 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 #15
Source File: FSDagStateStore.java    From incubator-gobblin with 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 #16
Source File: ShortenUrl.java    From thunderboard-android with 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 #17
Source File: NiciraNvpApi.java    From cloudstack with 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 File: YoutubeJExtractor.java    From youtube-jextractor with GNU General Public License v2.0 6 votes vote down vote up
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 #19
Source File: GsonDeserializerTest.java    From vraptor4 with 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 #20
Source File: TreeTypeAdapter.java    From gson with Apache License 2.0 5 votes vote down vote up
public TreeTypeAdapter(JsonSerializer<T> serializer, JsonDeserializer<T> deserializer,
    Gson gson, TypeToken<T> typeToken, TypeAdapterFactory skipPast) {
  this.serializer = serializer;
  this.deserializer = deserializer;
  this.gson = gson;
  this.typeToken = typeToken;
  this.skipPast = skipPast;
}
 
Example #21
Source File: TreeTypeAdapter.java    From gson with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked") // guarded by typeToken.equals() call
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
  boolean matches = exactType != null
      ? exactType.equals(type) || matchRawType && exactType.getType() == type.getRawType()
      : hierarchyType.isAssignableFrom(type.getRawType());
  return matches
      ? new TreeTypeAdapter<T>((JsonSerializer<T>) serializer,
          (JsonDeserializer<T>) deserializer, gson, type, this)
      : null;
}
 
Example #22
Source File: MysqlDagStateStore.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
public MysqlDagStateStore(Config config, Map<URI, TopologySpec> topologySpecMap) {
  if (config.hasPath(CONFIG_PREFIX)) {
    config = config.getConfig(CONFIG_PREFIX).withFallback(config);
  }

  this.mysqlStateStore = (MysqlStateStore<State>) createStateStore(config);

  JsonSerializer<List<JobExecutionPlan>> serializer = new JobExecutionPlanListSerializer();
  JsonDeserializer<List<JobExecutionPlan>> deserializer = new JobExecutionPlanListDeserializer(topologySpecMap);
  Type typeToken = new TypeToken<List<JobExecutionPlan>>() {
  }.getType();
  this.serDe = new GsonSerDe<>(typeToken, serializer, deserializer);
  this.jobExecPlanDagFactory = new JobExecutionPlanDagFactory();
}
 
Example #23
Source File: GsonModule.java    From arcusplatform with 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 #24
Source File: OAuthStoreHandlerImpl.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
public StorageFacade(Storage<String> storage) {
    this.storage = storage;
    // Add adapters for LocalDateTime
    gson = new GsonBuilder()
            .registerTypeAdapter(LocalDateTime.class,
                    (JsonDeserializer<LocalDateTime>) (json, typeOfT, context) -> LocalDateTime
                            .parse(json.getAsString()))
            .registerTypeAdapter(LocalDateTime.class,
                    (JsonSerializer<LocalDateTime>) (date, type,
                            jsonSerializationContext) -> new JsonPrimitive(date.toString()))
            .setPrettyPrinting().create();
}
 
Example #25
Source File: ForecastClient.java    From forecast-android with Apache License 2.0 5 votes vote down vote up
private static Gson createGson() {
    final long MILLIS = 1000;
    GsonBuilder builder = new GsonBuilder();

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

    return builder.create();
}
 
Example #26
Source File: CommunityProjectPullRequestsLoader.java    From sonarqube-community-branch-plugin with GNU General Public License v3.0 5 votes vote down vote up
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 #27
Source File: JsonUtils.java    From YCAudioPlayer with 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 #28
Source File: GsonSerDe.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
public GsonSerDe(Type type, JsonSerializer<T> serializer, JsonDeserializer<T> deserializer) {
  this.serializer = serializer;
  this.deserializer = deserializer;
  this.type = type;

  this.gson = new GsonBuilder().registerTypeAdapter(type, serializer)
      .registerTypeAdapter(type, deserializer)
      .create();
}
 
Example #29
Source File: Gandalf.java    From gandalf with Apache License 2.0 5 votes vote down vote up
private static Gandalf createInstance(@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(okHttpClient,
            bootstrapUrl,
            historyChecker,
            gateKeeper,
            onUpdateSelectedListener,
            customDeserializer,
            dialogStringsHolder);
}
 
Example #30
Source File: GsonFactory.java    From arcusplatform with 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);
}