com.google.gson.JsonSerializer Java Examples

The following examples show how to use com.google.gson.JsonSerializer. 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: JsonRenderer.java    From gocd with 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 #3
Source File: EventsExportEventsToJSON.java    From unitime with 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 #4
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 #5
Source File: SerializationTests.java    From azure-mobile-apps-android-client with Apache License 2.0 6 votes vote down vote up
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 #6
Source File: MavenHandler.java    From packagedrone with 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 #7
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 #8
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 #9
Source File: TransportFormat.java    From javamelody with 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 #10
Source File: ConvertUtils.java    From das with 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 #11
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 #12
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 #13
Source File: JsonAdapterAnnotationOnClassesTest.java    From gson with 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 #14
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 #15
Source File: Backend.java    From quantumdb with Apache License 2.0 5 votes vote down vote up
public Backend() {
	this.gson = new GsonBuilder()
			.registerTypeAdapter(ColumnType.class, (JsonDeserializer<ColumnType>) (element, type, context) -> {
				String fullType = element.getAsString().toUpperCase();

				String sqlType = fullType;
				if (fullType.contains("(")) {
					sqlType = fullType.substring(0, fullType.indexOf('('));
				}

				if (fullType.contains("(")) {
					int beginIndex = fullType.indexOf("(") + 1;
					int endIndex = fullType.lastIndexOf(")");
					List<Integer> arguments = Arrays.stream(fullType.substring(beginIndex, endIndex)
							.split(","))
							.map(String::trim)
							.map(Ints::tryParse)
							.collect(Collectors.toList());

					return PostgresTypes.from(sqlType, arguments.get(0));
				}
				return PostgresTypes.from(sqlType, null);
			})
			.registerTypeAdapter(ColumnType.class, (JsonSerializer<ColumnType>)
					(element, type, context) -> new JsonPrimitive(element.getNotation()))
			.create();
}
 
Example #16
Source File: MockSerializationResult.java    From vraptor4 with Apache License 2.0 5 votes vote down vote up
public MockSerializationResult() {
	this(new JavassistProxifier(), XStreamBuilderImpl.cleanInstance(),
			new GsonBuilderWrapper(new MockInstanceImpl<>(new ArrayList<JsonSerializer<?>>()), 
					new MockInstanceImpl<>(new ArrayList<JsonDeserializer<?>>()), 
					new Serializee(new DefaultReflectionProvider()) , new DefaultReflectionProvider()),
					new DefaultReflectionProvider());
}
 
Example #17
Source File: I18nMessageSerializationTest.java    From vraptor4 with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
	stream = new ByteArrayOutputStream();
	
	Environment environment = mock(Environment.class);

	HttpServletResponse response = mock(HttpServletResponse.class);
	writer = new PrintWriter(stream);
	when(response.getWriter()).thenReturn(writer);
	DefaultTypeNameExtractor extractor = new DefaultTypeNameExtractor();
	XStreamBuilder builder = XStreamBuilderImpl.cleanInstance(new MessageConverter());
	XStreamXMLSerialization xmlSerialization = new XStreamXMLSerialization(response, builder, environment);

	List<JsonSerializer<?>> jsonSerializers = new ArrayList<>();
	List<JsonDeserializer<?>> jsonDeserializers = new ArrayList<>();
	jsonSerializers.add(new CalendarGsonConverter());
	jsonSerializers.add(new MessageGsonConverter());

	GsonSerializerBuilder gsonBuilder =  new GsonBuilderWrapper(new MockInstanceImpl<>(jsonSerializers), 
			new MockInstanceImpl<>(jsonDeserializers), new Serializee(new DefaultReflectionProvider()), new DefaultReflectionProvider());
	GsonJSONSerialization jsonSerialization = new GsonJSONSerialization(response, extractor, gsonBuilder, environment,
			new DefaultReflectionProvider());

	Container container = mock(Container.class);
	when(container.instanceFor(JSONSerialization.class)).thenReturn(jsonSerialization);
	when(container.instanceFor(XMLSerialization.class)).thenReturn(xmlSerialization);

	ResourceBundle bundle = new SingletonResourceBundle("message.cat", "Just another {0} in {1}");
	serialization = new I18nMessageSerialization(container , bundle);
}
 
Example #18
Source File: GsonBuilderWrapper.java    From vraptor4 with Apache License 2.0 5 votes vote down vote up
@Inject
public GsonBuilderWrapper(@Any Instance<JsonSerializer<?>> jsonSerializers, 
		@Any Instance<JsonDeserializer<?>> jsonDeserializers,
		Serializee serializee, ReflectionProvider reflectionProvider) {
	this.jsonSerializers = jsonSerializers;
	this.jsonDeserializers = jsonDeserializers;
	this.serializee = serializee;
	ExclusionStrategy exclusion = new Exclusions(serializee, reflectionProvider);
	exclusions = singletonList(exclusion);
}
 
Example #19
Source File: BurntSushiValidTest.java    From toml4j with MIT License 5 votes vote down vote up
private static <T> JsonSerializer<T> serialize(final Class<T> aClass) {
  return new JsonSerializer<T>() {
    @Override
    public JsonElement serialize(T src, Type typeOfSrc, JsonSerializationContext context) {
      return context.serialize(new Value(toTomlType(aClass), src.toString()));
    }
  };
}
 
Example #20
Source File: GsonDeserializerTest.java    From vraptor4 with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
	MockitoAnnotations.initMocks(this);
	
	TimeZone.setDefault(TimeZone.getTimeZone("GMT-0300"));
	provider = new ParanamerNameProvider();
	request = mock(HttpServletRequest.class);
	List<JsonDeserializer<?>> jsonDeserializers = new ArrayList<>();
	List<JsonSerializer<?>> jsonSerializers = new ArrayList<>();
	jsonDeserializers.add(new CalendarGsonConverter());
	jsonDeserializers.add(new DateGsonConverter());

	builder = new GsonBuilderWrapper(new MockInstanceImpl<>(jsonSerializers), new MockInstanceImpl<>(jsonDeserializers), 
			new Serializee(new DefaultReflectionProvider()), new DefaultReflectionProvider());
	deserializer = new GsonDeserialization(builder, provider, request, container, deserializeeInstance);
	BeanClass controllerClass = new DefaultBeanClass(DogController.class);

	noParameter = new DefaultControllerMethod(controllerClass, DogController.class.getDeclaredMethod("noParameter"));
	dogParameter = new DefaultControllerMethod(controllerClass, DogController.class.getDeclaredMethod("dogParameter", Dog.class));
	dateParameter = new DefaultControllerMethod(controllerClass, DogController.class.getDeclaredMethod("dateParameter", Date.class));
	dogAndIntegerParameter = new DefaultControllerMethod(controllerClass, DogController.class.getDeclaredMethod("dogAndIntegerParameter", Dog.class,
			Integer.class));
	integerAndDogParameter = new DefaultControllerMethod(controllerClass, DogController.class.getDeclaredMethod("integerAndDogParameter",
			Integer.class, Dog.class));
	listDog = new DefaultControllerMethod(controllerClass, DogController.class.getDeclaredMethod("list", List.class));
	dogParameterWithoutRoot = new DefaultControllerMethod(controllerClass, DogController.class.getDeclaredMethod("dogParameterWithoutRoot", Dog.class));
	dogParameterNameEqualsJsonPropertyWithoutRoot = new DefaultControllerMethod(controllerClass, DogController.class.getDeclaredMethod("dogParameterNameEqualsJsonPropertyWithoutRoot", Dog.class));

	when(deserializeeInstance.get()).thenReturn(new Deserializee());
	when(container.instanceFor(WithRoot.class)).thenReturn(new WithRoot());
	when(container.instanceFor(WithoutRoot.class)).thenReturn(new WithoutRoot());
}
 
Example #21
Source File: NullObjectAndFieldTest.java    From gson with Apache License 2.0 5 votes vote down vote up
public void testCustomTypeAdapterPassesNullSerialization() {
  Gson gson = new GsonBuilder()
      .registerTypeAdapter(ObjectWithField.class, new JsonSerializer<ObjectWithField>() {
        @Override public JsonElement serialize(ObjectWithField src, Type typeOfSrc,
            JsonSerializationContext context) {
          return context.serialize(null);
        }
      }).create();
  ObjectWithField target = new ObjectWithField();
  target.value = "value1";
  String json = gson.toJson(target);
  assertFalse(json.contains("value1"));
}
 
Example #22
Source File: MapTest.java    From gson with Apache License 2.0 5 votes vote down vote up
public final void testInterfaceTypeMapWithSerializer() {
  MapClass element = new MapClass();
  TestTypes.Sub subType = new TestTypes.Sub();
  element.addBase("Test", subType);
  element.addSub("Test", subType);

  Gson tempGson = new Gson();
  String subTypeJson = tempGson.toJson(subType);
  final JsonElement baseTypeJsonElement = tempGson.toJsonTree(subType, TestTypes.Base.class);
  String baseTypeJson = tempGson.toJson(baseTypeJsonElement);
  String expected = "{\"bases\":{\"Test\":" + baseTypeJson + "},"
      + "\"subs\":{\"Test\":" + subTypeJson + "}}";

  JsonSerializer<TestTypes.Base> baseTypeAdapter = new JsonSerializer<TestTypes.Base>() {
    public JsonElement serialize(TestTypes.Base src, Type typeOfSrc,
        JsonSerializationContext context) {
      return baseTypeJsonElement;
    }
  };

  Gson gson = new GsonBuilder()
      .enableComplexMapKeySerialization()
      .registerTypeAdapter(TestTypes.Base.class, baseTypeAdapter)
      .create();
  String json = gson.toJson(element);
  assertEquals(expected, json);

  gson = new GsonBuilder()
      .registerTypeAdapter(TestTypes.Base.class, baseTypeAdapter)
      .create();
  json = gson.toJson(element);
  assertEquals(expected, json);
}
 
Example #23
Source File: ObjectTest.java    From gson with Apache License 2.0 5 votes vote down vote up
public void testAnonymousLocalClassesCustomSerialization() throws Exception {
  gson = new GsonBuilder()
      .registerTypeHierarchyAdapter(ClassWithNoFields.class,
          new JsonSerializer<ClassWithNoFields>() {
            public JsonElement serialize(
                ClassWithNoFields src, Type typeOfSrc, JsonSerializationContext context) {
              return new JsonObject();
            }
          }).create();

  assertEquals("null", gson.toJson(new ClassWithNoFields() {
    // empty anonymous class
  }));
}
 
Example #24
Source File: CollectionTest.java    From gson with Apache License 2.0 5 votes vote down vote up
public void testUserCollectionTypeAdapter() {
  Type listOfString = new TypeToken<List<String>>() {}.getType();
  Object stringListSerializer = new JsonSerializer<List<String>>() {
    public JsonElement serialize(List<String> src, Type typeOfSrc,
        JsonSerializationContext context) {
      return new JsonPrimitive(src.get(0) + ";" + src.get(1));
    }
  };
  Gson gson = new GsonBuilder()
      .registerTypeAdapter(listOfString, stringListSerializer)
      .create();
  assertEquals("\"ab;cd\"", gson.toJson(Arrays.asList("ab", "cd"), listOfString));
}
 
Example #25
Source File: CustomTypeAdaptersTest.java    From gson with Apache License 2.0 5 votes vote down vote up
public void testCustomByteArraySerializer() {
  Gson gson = new GsonBuilder().registerTypeAdapter(byte[].class, new JsonSerializer<byte[]>() {
    @Override
    public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) {
      StringBuilder sb = new StringBuilder(src.length);
      for (byte b : src) {
        sb.append(b);
      }
      return new JsonPrimitive(sb.toString());
    }
  }).create();
  byte[] data = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
  String json = gson.toJson(data);
  assertEquals("\"0123456789\"", json);
}
 
Example #26
Source File: CustomTypeAdaptersTest.java    From gson with Apache License 2.0 5 votes vote down vote up
public void testCustomSerializerInvokedForPrimitives() {
  Gson gson = new GsonBuilder()
      .registerTypeAdapter(boolean.class, new JsonSerializer<Boolean>() {
        @Override public JsonElement serialize(Boolean s, Type t, JsonSerializationContext c) {
          return new JsonPrimitive(s ? 1 : 0);
        }
      })
      .create();
  assertEquals("1", gson.toJson(true, boolean.class));
  assertEquals("true", gson.toJson(true, Boolean.class));
}
 
Example #27
Source File: CustomTypeAdaptersTest.java    From gson with Apache License 2.0 5 votes vote down vote up
public void testCustomNestedSerializers() {
  Gson gson = new GsonBuilder().registerTypeAdapter(
      BagOfPrimitives.class, new JsonSerializer<BagOfPrimitives>() {
        @Override public JsonElement serialize(BagOfPrimitives src, Type typeOfSrc,
        JsonSerializationContext context) {
      return new JsonPrimitive(6);
    }
  }).create();
  ClassWithCustomTypeConverter target = new ClassWithCustomTypeConverter();
  assertEquals("{\"bag\":6,\"value\":10}", gson.toJson(target));
}
 
Example #28
Source File: CustomTypeAdaptersTest.java    From gson with Apache License 2.0 5 votes vote down vote up
public void testCustomSerializers() {
  Gson gson = builder.registerTypeAdapter(
      ClassWithCustomTypeConverter.class, new JsonSerializer<ClassWithCustomTypeConverter>() {
        @Override public JsonElement serialize(ClassWithCustomTypeConverter src, Type typeOfSrc,
            JsonSerializationContext context) {
      JsonObject json = new JsonObject();
      json.addProperty("bag", 5);
      json.addProperty("value", 25);
      return json;
    }
  }).create();
  ClassWithCustomTypeConverter target = new ClassWithCustomTypeConverter();
  assertEquals("{\"bag\":5,\"value\":25}", gson.toJson(target));
}
 
Example #29
Source File: TypeAdapterPrecedenceTest.java    From gson with Apache License 2.0 5 votes vote down vote up
private JsonSerializer<Foo> newSerializer(final String name) {
  return new JsonSerializer<Foo>() {
    @Override
    public JsonElement serialize(Foo src, Type typeOfSrc, JsonSerializationContext context) {
      return new JsonPrimitive(src.name + " via " + name);
    }
  };
}
 
Example #30
Source File: TreeTypeAdapter.java    From gson with 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;
}