Java Code Examples for com.google.gson.JsonSerializer

The following examples show how to use com.google.gson.JsonSerializer. 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: das   Source File: ConvertUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static Entity pojo2Entity(Object row, EntityMeta meta)  {
    checkNotNull(row);

    if(row instanceof Entity) {
        return (Entity) row;
    }

    if(meta == null || row instanceof Map) {
        String json = new GsonBuilder().registerTypeHierarchyAdapter(Date.class, (JsonSerializer<Date>) (date, typeOfSrc, context) ->
                new JsonPrimitive(date.getTime())
        ).create().toJson(row);
        return new Entity().setValue(json);
    }

    Set<Map.Entry<String, JsonElement>> tree = ((JsonObject)
            new GsonBuilder()
                    .registerTypeHierarchyAdapter(Date.class, (JsonSerializer<Date>) (date, typeOfSrc, context) ->
                            new JsonPrimitive(date.getTime())
                    ).create().toJsonTree(row)).entrySet();

    Map<String, Object> entity = new HashMap<>();
    Map<String, String> map = HashBiMap.create(meta.getFieldMap()).inverse();
    tree.forEach(e-> entity.put(map.get(e.getKey()), e.getValue()));
    return new Entity().setValue(new Gson().toJson(entity)).setEntityMeta(meta);
}
 
Example 2
Source Project: arcusplatform   Source File: MessagesModule.java    License: Apache License 2.0 6 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 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 void testCustomSerializationWithoutUsingMobileServiceTable() {
    ComplexPersonTestObject person = new ComplexPersonTestObject("John", "Doe", new Address("1345 Washington St", 1313, "US"));

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

        @Override
        public JsonElement serialize(Address arg0, Type arg1, JsonSerializationContext arg2) {

            JsonObject json = new JsonObject();
            json.addProperty("zipcode", arg0.getZipCode());
            json.addProperty("country", arg0.getCountry());
            json.addProperty("streetaddress", arg0.getStreetAddress());

            return json;
        }
    });

    String serializedObject = gsonBuilder.create().toJson(person);

    // Asserts
    assertEquals(
            "{\"address\":{\"zipcode\":1313,\"country\":\"US\",\"streetaddress\":\"1345 Washington St\"},\"firstName\":\"John\",\"id\":0,\"lastName\":\"Doe\"}",
            serializedObject);
}
 
Example 7
Source Project: packagedrone   Source File: MavenHandler.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private void renderDirAsJson ( final HttpServletResponse response, final Node node ) throws IOException
{
    final GsonBuilder gsonBuilder = new GsonBuilder ();
    gsonBuilder.registerTypeAdapter ( DataNode.class, new JsonSerializer<DataNode> () {

        @Override
        public JsonElement serialize ( final DataNode src, final Type typeOfSrc, final JsonSerializationContext context )
        {
            final JsonObject jsonObject = new JsonObject ();
            // final String data = new String ( src.getData () );
            // jsonObject.addProperty("data", data);
            jsonObject.addProperty ( "mimeType", src.getMimeType () );
            return jsonObject;
        }
    } );
    response.setContentType ( "application/json" );
    gsonBuilder.create ().toJson ( node, response.getWriter () );
}
 
Example 8
Source Project: javamelody   Source File: TransportFormat.java    License: Apache License 2.0 6 votes vote down vote up
static void writeToGson(Serializable serializable, BufferedOutputStream bufferedOutput)
		throws IOException {
	final JsonSerializer<StackTraceElement> stackTraceElementJsonSerializer = new JsonSerializer<StackTraceElement>() {
		@Override
		public JsonElement serialize(StackTraceElement src, Type typeOfSrc,
				JsonSerializationContext context) {
			return new JsonPrimitive(src.toString());
		}
	};
	final Gson gson = new GsonBuilder()
			// .setPrettyPrinting() : prettyPrinting pas nécessaire avec un viewer de json
			.registerTypeAdapter(StackTraceElement.class, stackTraceElementJsonSerializer)
			.create();
	final OutputStreamWriter writer = new OutputStreamWriter(bufferedOutput,
			GSON_CHARSET_NAME);
	try {
		gson.toJson(serializable, writer);
	} finally {
		writer.close();
	}
}
 
Example 9
Source Project: gson   Source File: JsonAdapterAnnotationOnClassesTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * The serializer overrides field adapter, but for deserializer the fieldAdapter is used.
 */
public void testRegisteredSerializerOverridesJsonAdapter() {
  JsonSerializer<A> serializer = new JsonSerializer<A>() {
    public JsonElement serialize(A src, Type typeOfSrc,
        JsonSerializationContext context) {
      return new JsonPrimitive("registeredSerializer");
    }
  };
  Gson gson = new GsonBuilder()
    .registerTypeAdapter(A.class, serializer)
    .create();
  String json = gson.toJson(new A("abcd"));
  assertEquals("\"registeredSerializer\"", json);
  A target = gson.fromJson("abcd", A.class);
  assertEquals("jsonAdapter", target.value);
}
 
Example 10
Source Project: unitime   Source File: EventsExportEventsToJSON.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void print(ExportHelper helper, EventLookupRpcRequest request, List<EventInterface> events, int eventCookieFlags, EventMeetingSortBy sort, boolean asc) throws IOException {
	helper.setup("application/json", reference(), false);
	
   	Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new JsonSerializer<Date>() {
		@Override
		public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
			return new JsonPrimitive(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(src));
		}
	})
	.setFieldNamingStrategy(new FieldNamingStrategy() {
		Pattern iPattern = Pattern.compile("i([A-Z])(.*)");
		@Override
		public String translateName(Field f) {
			Matcher matcher = iPattern.matcher(f.getName());
			if (matcher.matches())
				return matcher.group(1).toLowerCase() + matcher.group(2);
			else
				return f.getName();
		}
	})
	.setPrettyPrinting().create();
   	
   	helper.getWriter().write(gson.toJson(events));
}
 
Example 11
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 12
Source Project: gocd   Source File: JsonRenderer.java    License: Apache License 2.0 6 votes vote down vote up
private static Gson gsonBuilder(final GoRequestContext requestContext) {
    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(JsonUrl.class, (JsonSerializer<JsonUrl>) (src, typeOfSrc, context) -> {
        if (requestContext == null) {
            return new JsonPrimitive(src.getUrl());
        } else {
            return new JsonPrimitive(requestContext.getFullRequestPath() + src.getUrl());
        }
    });

    builder.registerTypeHierarchyAdapter(MessageSourceResolvable.class, (JsonSerializer<MessageSourceResolvable>) (src, typeOfSrc, context) -> {
        if (requestContext == null) {
            return new JsonPrimitive(src.getDefaultMessage());
        } else {
            return new JsonPrimitive(requestContext.getMessage(src));
        }
    });

    builder.serializeNulls();
    return builder.create();
}
 
Example 13
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 14
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 15
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 16
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 17
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 18
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 19
Source Project: influxdb-client-java   Source File: JSON.java    License: MIT License 5 votes vote down vote up
public JSON() {
    gson = createGson()
        .registerTypeAdapter(Date.class, dateTypeAdapter)
        .registerTypeAdapter(java.sql.Date.class, sqlDateTypeAdapter)
        .registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter)
        .registerTypeAdapter(LocalDate.class, localDateTypeAdapter)
        .registerTypeAdapter(PostNotificationEndpoint.class, (JsonSerializer<PostNotificationEndpoint>)
            (src, type, context) -> context.serialize(src, src.getClass()))
        .registerTypeAdapter(PostNotificationRule.class, (JsonSerializer<PostNotificationRule>)
            (src, type, context) -> context.serialize(src, src.getClass()))
        .registerTypeAdapter(PostCheck.class, (JsonSerializer<PostCheck>)
            (src, type, context) -> context.serialize(src, src.getClass()))
        .create();
}
 
Example 20
Source Project: oneops   Source File: HTTPMsgService.java    License: Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void init() {
    // Meter to measure the rate of messages.
    http = metrics.meter(name(ANTENNA, "http.count"));
    httpErr = metrics.meter(name(ANTENNA, "http.error"));
    hpom = metrics.meter(name(ANTENNA, "hpom.count"));
    hpomErr = metrics.meter(name(ANTENNA, "hpom.error"));
    GsonBuilder builder = new GsonBuilder();

    builder.registerTypeAdapter(Date.class,
        (JsonSerializer<Date>) (date, typeOfSrc, context) -> new JsonPrimitive(date.getTime()));
    gson = builder.create();
}
 
Example 21
Source Project: SocialSdkLibrary   Source File: GsonJsonAdapter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String toJson(Object object) {
    GsonBuilder gsonBuilder = new GsonBuilder()
            .registerTypeAdapter(Date.class, new JsonSerializer<Date>() {
                @Override
                public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
                    return new JsonPrimitive(src.getTime());
                }
            }).setDateFormat(DateFormat.LONG);
    return gsonBuilder.create().toJson(object);
}
 
Example 22
private Gson buildSerializer() {
	GsonBuilder builder = new GsonBuilder();
	builder.setDateFormat(API_JSON_DATETIME_PATTERN);
	builder.serializeNulls();
	builder.setExclusionStrategies(JsUtil.GSON_EXCLUSION_STRATEGIES);
	builder.registerTypeAdapter(NoShortcutSerializationWrapper.class, new JsonSerializer<NoShortcutSerializationWrapper<?>>() {

		@Override
		public JsonElement serialize(NoShortcutSerializationWrapper<?> src, Type typeOfSrc, JsonSerializationContext context) {
			return context.serialize(src.getVo());
		}
	});
	return builder.create();
}
 
Example 23
private Gson buildShortcutSerializer() {
	GsonBuilder builder = new GsonBuilder();
	builder.setDateFormat(API_JSON_DATETIME_PATTERN);
	builder.serializeNulls();
	builder.setExclusionStrategies(JsUtil.GSON_EXCLUSION_STRATEGIES);
	builder.registerTypeAdapter(NoShortcutSerializationWrapper.class, new JsonSerializer<NoShortcutSerializationWrapper<?>>() {

		@Override
		public JsonElement serialize(NoShortcutSerializationWrapper<?> src, Type typeOfSrc, JsonSerializationContext context) {
			return serializer.toJsonTree(src.getVo()); // use regular serializer
		}
	});
	JsUtil.registerGsonTypeAdapters(builder, JsUtil.GSON_SHORTCUT_SERIALISATIONS);
	return builder.create();
}
 
Example 24
Source Project: ctsms   Source File: JsUtil.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
public static GsonBuilder registerGsonTypeAdapters(GsonBuilder builder, HashMap<Class, JsonSerializer> serialisations) {
	Iterator<Entry<Class, JsonSerializer>> it = serialisations.entrySet().iterator();
	while (it.hasNext()) {
		Entry<Class, JsonSerializer> shortcut = it.next();
		builder.registerTypeAdapter(shortcut.getKey(), shortcut.getValue());
	}
	return builder;
}
 
Example 25
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 26
Source Project: SkyTube   Source File: SubscriptionsDb.java    License: GNU General Public License v3.0 5 votes vote down vote up
private Gson createGson() {
   	return new GsonBuilder().registerTypeAdapter(YouTubeChannel.class, new JsonSerializer<YouTubeChannel>() {

		@Override
		public JsonElement serialize(YouTubeChannel src, Type typeOfSrc, JsonSerializationContext context) {
			JsonObject obj = new JsonObject();
			obj.addProperty("id", src.getId());
			obj.addProperty("title", src.getTitle());
			obj.addProperty("description", src.getDescription());
			obj.addProperty("thumbnailNormalUrl", src.getThumbnailUrl());
			obj.addProperty("bannerUrl", src.getBannerUrl());
			return obj;
		}
	}).create();
}
 
Example 27
Source Project: QiQuYingServer   Source File: JsonUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 将对象转换成json格式(并自定义日期格式)
 * @param ts
 * @return
 */
public static String objectToJsonDateSerializer(Object ts,final String dateformat){
	String jsonStr=null;
	gson=new GsonBuilder().registerTypeHierarchyAdapter(Date.class, new JsonSerializer<Date>() {
		public JsonElement serialize(Date src, Type typeOfSrc,
				JsonSerializationContext context) {
			SimpleDateFormat format = new SimpleDateFormat(dateformat);
			return new JsonPrimitive(format.format(src));
		}
	}).setDateFormat(dateformat).create();
	if(gson!=null){
		jsonStr=gson.toJson(ts);
	}
	return jsonStr;
}
 
Example 28
Source Project: gson   Source File: TreeTypeAdapter.java    License: 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 29
Source Project: gson   Source File: TreeTypeAdapter.java    License: Apache License 2.0 5 votes vote down vote up
SingleTypeFactory(Object typeAdapter, TypeToken<?> exactType, boolean matchRawType,
    Class<?> hierarchyType) {
  serializer = typeAdapter instanceof JsonSerializer
      ? (JsonSerializer<?>) typeAdapter
      : null;
  deserializer = typeAdapter instanceof JsonDeserializer
      ? (JsonDeserializer<?>) typeAdapter
      : null;
  $Gson$Preconditions.checkArgument(serializer != null || deserializer != null);
  this.exactType = exactType;
  this.matchRawType = matchRawType;
  this.hierarchyType = hierarchyType;
}
 
Example 30
Source Project: gson   Source File: TreeTypeAdapter.java    License: 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;
}