Java Code Examples for com.google.gson.GsonBuilder#registerTypeHierarchyAdapter()

The following examples show how to use com.google.gson.GsonBuilder#registerTypeHierarchyAdapter() . 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: EventServlet.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public EventServlet(LeshanServer server, int securePort) {
    this.server = server;
    server.getClientRegistry().addListener(this.clientRegistryListener);
    server.getObservationRegistry().addListener(this.observationRegistryListener);

    // add an interceptor to each endpoint to trace all CoAP messages
    coapMessageTracer = new CoapMessageTracer(server.getClientRegistry());
    for (Endpoint endpoint : server.getCoapServer().getEndpoints()) {
        endpoint.addInterceptor(coapMessageTracer);
    }

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeHierarchyAdapter(Client.class, new ClientSerializer(securePort));
    gsonBuilder.registerTypeHierarchyAdapter(LwM2mNode.class, new LwM2mNodeSerializer());
    gsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
    this.gson = gsonBuilder.create();
}
 
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: EventServlet.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public EventServlet(LeshanServer server, int securePort) {
    this.server = server;
    server.getClientRegistry().addListener(this.clientRegistryListener);
    server.getObservationRegistry().addListener(this.observationRegistryListener);

    // add an interceptor to each endpoint to trace all CoAP messages
    coapMessageTracer = new CoapMessageTracer(server.getClientRegistry());
    for (Endpoint endpoint : server.getCoapServer().getEndpoints()) {
        endpoint.addInterceptor(coapMessageTracer);
    }

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeHierarchyAdapter(Client.class, new ClientSerializer(securePort));
    gsonBuilder.registerTypeHierarchyAdapter(LwM2mNode.class, new LwM2mNodeSerializer());
    gsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
    this.gson = gsonBuilder.create();
}
 
Example 4
Source File: HibernateProxySerializer.java    From JDeSurvey with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public JsonElement serialize(HibernateProxy proxyObj, Type arg1, JsonSerializationContext arg2) {
    try {
        GsonBuilder gsonBuilder = new GsonBuilder();
        //below ensures deep deproxied serialization
        gsonBuilder.registerTypeHierarchyAdapter(HibernateProxy.class, new HibernateProxySerializer());
        Object deProxied = proxyObj.getHibernateLazyInitializer().getImplementation();
        return gsonBuilder.create().toJsonTree(deProxied);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 5
Source File: ObjectSpecServlet.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public ObjectSpecServlet(LwM2mModelProvider pModelProvider) {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeHierarchyAdapter(ObjectModel.class, new ObjectModelSerializer());
    gsonBuilder.registerTypeHierarchyAdapter(ResourceModel.class, new ResourceModelSerializer());
    this.gson = gsonBuilder.create();

    // use the provider from the server and return a model by client
    modelProvider = pModelProvider;
}
 
Example 6
Source File: ClientServlet.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public ClientServlet(LwM2mServer server, int securePort) {
    this.server = server;

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeHierarchyAdapter(Client.class, new ClientSerializer(securePort));
    gsonBuilder.registerTypeHierarchyAdapter(LwM2mResponse.class, new ResponseSerializer());
    gsonBuilder.registerTypeHierarchyAdapter(LwM2mNode.class, new LwM2mNodeSerializer());
    gsonBuilder.registerTypeHierarchyAdapter(LwM2mNode.class, new LwM2mNodeDeserializer());
    gsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
    this.gson = gsonBuilder.create();
}
 
Example 7
Source File: JsonSerializer.java    From mobile-messaging-sdk-android with Apache License 2.0 5 votes vote down vote up
public JsonSerializer(boolean serializeNulls, ObjectAdapter... adapters) {
    GsonBuilder builder = new GsonBuilder();
    if (serializeNulls) {
        builder.serializeNulls();
    }
    if (adapters.length > 0) {
        for (ObjectAdapter adapter : adapters) {
            builder.registerTypeHierarchyAdapter(adapter.getCls(), new CustomTypeAdapter(adapter));
        }
    }
    gson = builder.create();
}
 
Example 8
Source File: FbBotMillJsonUtils.java    From fb-botmill with MIT License 5 votes vote down vote up
/**
 * Initializes the current Gson object if null and returns it. The Gson
 * object has custom adapters to manage datatypes according to Facebook
 * formats.
 * 
 * @return the current instance of Gson.
 */
private static Gson getGson() {
	if (gson == null) {
		// Creates the Gson object which will manage the information
		// received
		GsonBuilder builder = new GsonBuilder();

		// Serializes enums as lower-case.
		builder.registerTypeHierarchyAdapter(Enum.class,
				new EnumLowercaseSerializer());

		// Serializes calendar in format YYYY-MM-DDThh:mm.
		builder.registerTypeHierarchyAdapter(Calendar.class,
				new CalendarSerializer());

		// Deserializes payloads from interface.
		builder.registerTypeAdapter(Attachment.class,
				new AttachmentDeserializer());

		// Serializes/deserializes buttons from interface.
		builder.registerTypeAdapter(Button.class, new ButtonSerializer());

		// Deserializes incoming messages from interface.
		builder.registerTypeAdapter(IncomingMessage.class,
				new IncomingMessageDeserializer());

		// Deserializes timestamp as Calendar.
		builder.registerTypeAdapter(Calendar.class,
				new CalendarFromTimestampJsonDeserializer());

		gson = builder.create();
	}
	return gson;
}
 
Example 9
Source File: ApiServlet.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public ApiServlet(LwM2mServer server, int securePort) {
    this.server = server;

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeHierarchyAdapter(Client.class, new ClientSerializer(securePort));
    gsonBuilder.registerTypeHierarchyAdapter(LwM2mResponse.class, new ResponseSerializer());
    gsonBuilder.registerTypeHierarchyAdapter(LwM2mNode.class, new LwM2mNodeSerializer());
    gsonBuilder.registerTypeHierarchyAdapter(LwM2mNode.class, new LwM2mNodeDeserializer());
    gsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
    this.gson = gsonBuilder.create();
}
 
Example 10
Source File: ClientServlet.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public ClientServlet(LwM2mServer server, int securePort) {
    this.server = server;

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeHierarchyAdapter(Client.class, new ClientSerializer(securePort));
    gsonBuilder.registerTypeHierarchyAdapter(LwM2mResponse.class, new ResponseSerializer());
    gsonBuilder.registerTypeHierarchyAdapter(LwM2mNode.class, new LwM2mNodeSerializer());
    gsonBuilder.registerTypeHierarchyAdapter(LwM2mNode.class, new LwM2mNodeDeserializer());
    gsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
    this.gson = gsonBuilder.create();
}
 
Example 11
Source File: ObjectSpecServlet.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public ObjectSpecServlet(LwM2mModelProvider pModelProvider) {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeHierarchyAdapter(ObjectModel.class, new ObjectModelSerializer());
    gsonBuilder.registerTypeHierarchyAdapter(ResourceModel.class, new ResourceModelSerializer());
    this.gson = gsonBuilder.create();

    // use the provider from the server and return a model by client
    modelProvider = pModelProvider;
}
 
Example 12
Source File: GsonWrapper.java    From activitystreams with Apache License 2.0 4 votes vote down vote up
/**
 * Method initGsonBuilder.
 * @param builder Builder

 * @return GsonBuilder */
private static GsonBuilder initGsonBuilder(
  Builder builder, 
  Schema schema, 
  ASObjectAdapter base,
  Iterable<AdapterEntry<?>> adapters) {
  
  GsonBuilder gson = new GsonBuilder()
  .registerTypeHierarchyAdapter(TypeValue.class, new TypeValueAdapter(schema))
  .registerTypeHierarchyAdapter(LinkValue.class, new LinkValueAdapter(schema))
  .registerTypeHierarchyAdapter(Iterable.class, ITERABLE)
  .registerTypeHierarchyAdapter(ASObject.class, base)
  .registerTypeHierarchyAdapter(Collection.class, base)
  .registerTypeHierarchyAdapter(Activity.class, base)
  .registerTypeHierarchyAdapter(NLV.class, NLV)
  .registerTypeHierarchyAdapter(ActionsValue.class, ACTIONS)
  .registerTypeHierarchyAdapter(Optional.class, OPTIONAL)
  .registerTypeHierarchyAdapter(Range.class, RANGE)
  .registerTypeHierarchyAdapter(Table.class, TABLE)
  .registerTypeHierarchyAdapter(LazilyParsedNumber.class, NUMBER)
  .registerTypeHierarchyAdapter(LazilyParsedNumberComparable.class, NUMBER)
  .registerTypeHierarchyAdapter(ReadableDuration.class, DURATION)
  .registerTypeHierarchyAdapter(ReadablePeriod.class, PERIOD)
  .registerTypeHierarchyAdapter(ReadableInterval.class, INTERVAL)
  .registerTypeAdapter(
    Activity.Status.class, 
    forEnum(
      Activity.Status.class, 
      Activity.Status.OTHER))
  .registerTypeAdapter(Date.class, DATE)
  .registerTypeAdapter(DateTime.class, DATETIME)
  .registerTypeAdapter(MediaType.class, MIMETYPE)
  .registerTypeHierarchyAdapter(Multimap.class, MULTIMAP);
  
  for (AdapterEntry<?> entry : adapters) {
    if (entry.hier)
      gson.registerTypeHierarchyAdapter(
        entry.type, 
        entry.adapter!=null ?
          entry.adapter : base);
    else
      gson.registerTypeAdapter(
        entry.type, 
        entry.adapter!=null ? 
          entry.adapter:base);
  }
  
  return gson;

}
 
Example 13
Source File: JsonHelperService.java    From JDeSurvey with GNU Affero General Public License v3.0 4 votes vote down vote up
public String serializeSurveyDefinition(SurveyDefinition surveyDefinition){
	try{
		GsonBuilder gsonBuilder = new GsonBuilder();
		//set up the fields to skip in the serialization
		gsonBuilder = gsonBuilder.setExclusionStrategies(new ExclusionStrategy() {
	        						public boolean shouldSkipClass(Class<?> clazz) {
	        							return false;
	        						}
	        						@Override
	        						public boolean shouldSkipField(FieldAttributes f) {
	        						boolean skip = (f.getDeclaringClass() == SurveyDefinition.class && f.getName().equals("id"))||
	        									   (f.getDeclaringClass() == SurveyDefinition.class && f.getName().equals("version"))||
	        									   (f.getDeclaringClass() == SurveyDefinition.class && f.getName().equals("department"))||
	        									   (f.getDeclaringClass() == SurveyDefinition.class && f.getName().equals("users"))||
	        									   (f.getDeclaringClass() == SurveyDefinitionPage.class && f.getName().equals("id"))||
	        									   (f.getDeclaringClass() == SurveyDefinitionPage.class && f.getName().equals("surveyDefinition"))||
	        									   (f.getDeclaringClass() == Question.class && f.getName().equals("id"))||
	        									   (f.getDeclaringClass() == Question.class && f.getName().equals("version"))||
	        									   (f.getDeclaringClass() == Question.class && f.getName().equals("page"))||
	        									   (f.getDeclaringClass() == Question.class && f.getName().equals("optionsList"))||
	        									   (f.getDeclaringClass() == Question.class && f.getName().equals("rowLabelsList"))||
	        									   (f.getDeclaringClass() == Question.class && f.getName().equals("columnLabelsList"))||
	        									   (f.getDeclaringClass() == QuestionOption.class && f.getName().equals("id"))||
	        									   (f.getDeclaringClass() == QuestionOption.class && f.getName().equals("version"))||
	        						               (f.getDeclaringClass() == QuestionOption.class && f.getName().equals("question")) ||
	        						               (f.getDeclaringClass() == QuestionRowLabel.class && f.getName().equals("id"))||
	        									   (f.getDeclaringClass() == QuestionRowLabel.class && f.getName().equals("version"))||
	        						               (f.getDeclaringClass() == QuestionRowLabel.class && f.getName().equals("question")) ||
	        						               (f.getDeclaringClass() == QuestionColumnLabel.class && f.getName().equals("id"))||
	        									   (f.getDeclaringClass() == QuestionColumnLabel.class && f.getName().equals("version"))||
	        									   (f.getDeclaringClass() == QuestionColumnLabel.class && f.getName().equals("question"));
	        						return skip;
	        						}

	     });
		
		//de-proxy the object
		gsonBuilder.registerTypeHierarchyAdapter(HibernateProxy.class, new HibernateProxySerializer());
		Hibernate.initialize(surveyDefinition);
		if (surveyDefinition instanceof HibernateProxy)  {
		  surveyDefinition = (SurveyDefinition) ((HibernateProxy)surveyDefinition).getHibernateLazyInitializer().getImplementation();
		}
		Gson gson =  gsonBuilder.serializeNulls().create();
		return gson.toJson(surveyDefinition);
	
	} 
	catch (Exception e) {
		log.error(e.getMessage(),e);
		throw (new RuntimeException(e));
	}
	
}
 
Example 14
Source File: WebApplicationExceptionMapper.java    From zeppelin with Apache License 2.0 4 votes vote down vote up
public WebApplicationExceptionMapper() {
  GsonBuilder gsonBuilder = new GsonBuilder().enableComplexMapKeySerialization();
  gsonBuilder.registerTypeHierarchyAdapter(
      Exception.class, new ExceptionSerializer());
  this.gson = gsonBuilder.create();
}
 
Example 15
Source File: CubaJavaScriptComponent.java    From cuba with Apache License 2.0 4 votes vote down vote up
protected static void setDefaultProperties(GsonBuilder builder) {
    builder.registerTypeHierarchyAdapter(Date.class, new DateJsonSerializer());
}
 
Example 16
Source File: JsonWorker.java    From ID-SDK with Apache License 2.0 4 votes vote down vote up
public static GsonBuilder initBuilder(GsonBuilder gb){
	gb.registerTypeHierarchyAdapter(PublicKey.class,new PublicKeyTypeAdapter());
	gb.registerTypeHierarchyAdapter(Permission.class, new PermissionTypeAdapter());
	return gb;
}
 
Example 17
Source File: GsonBuilderUtils.java    From spring4-understanding with Apache License 2.0 2 votes vote down vote up
/**
 * Obtain a {@link GsonBuilder} which Base64-encodes {@code byte[]}
 * properties when reading and writing JSON.
 * <p>A custom {@link com.google.gson.TypeAdapter} will be registered via
 * {@link GsonBuilder#registerTypeHierarchyAdapter(Class, Object)} which
 * serializes a {@code byte[]} property to and from a Base64-encoded String
 * instead of a JSON array.
 * <p><strong>NOTE:</strong> Use of this option requires the presence of the
 * Apache Commons Codec library on the classpath when running on Java 6 or 7.
 * On Java 8, the standard {@link java.util.Base64} facility is used instead.
 */
public static GsonBuilder gsonBuilderWithBase64EncodedByteArrays() {
	GsonBuilder builder = new GsonBuilder();
	builder.registerTypeHierarchyAdapter(byte[].class, new Base64TypeAdapter());
	return builder;
}
 
Example 18
Source File: GsonBuilderUtils.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Obtain a {@link GsonBuilder} which Base64-encodes {@code byte[]}
 * properties when reading and writing JSON.
 * <p>A custom {@link com.google.gson.TypeAdapter} will be registered via
 * {@link GsonBuilder#registerTypeHierarchyAdapter(Class, Object)} which
 * serializes a {@code byte[]} property to and from a Base64-encoded String
 * instead of a JSON array.
 * <p><strong>NOTE:</strong> Use of this option requires the presence of the
 * Apache Commons Codec library on the classpath when running on Java 6 or 7.
 * On Java 8, the standard {@link java.util.Base64} facility is used instead.
 */
public static GsonBuilder gsonBuilderWithBase64EncodedByteArrays() {
	GsonBuilder builder = new GsonBuilder();
	builder.registerTypeHierarchyAdapter(byte[].class, new Base64TypeAdapter());
	return builder;
}
 
Example 19
Source File: GsonBuilderUtils.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * Obtain a {@link GsonBuilder} which Base64-encodes {@code byte[]}
 * properties when reading and writing JSON.
 * <p>A custom {@link com.google.gson.TypeAdapter} will be registered via
 * {@link GsonBuilder#registerTypeHierarchyAdapter(Class, Object)} which
 * serializes a {@code byte[]} property to and from a Base64-encoded String
 * instead of a JSON array.
 */
public static GsonBuilder gsonBuilderWithBase64EncodedByteArrays() {
	GsonBuilder builder = new GsonBuilder();
	builder.registerTypeHierarchyAdapter(byte[].class, new Base64TypeAdapter());
	return builder;
}
 
Example 20
Source File: GsonBuilderUtils.java    From spring-analysis-note with MIT License 2 votes vote down vote up
/**
 * Obtain a {@link GsonBuilder} which Base64-encodes {@code byte[]}
 * properties when reading and writing JSON.
 * <p>A custom {@link com.google.gson.TypeAdapter} will be registered via
 * {@link GsonBuilder#registerTypeHierarchyAdapter(Class, Object)} which
 * serializes a {@code byte[]} property to and from a Base64-encoded String
 * instead of a JSON array.
 */
public static GsonBuilder gsonBuilderWithBase64EncodedByteArrays() {
	GsonBuilder builder = new GsonBuilder();
	builder.registerTypeHierarchyAdapter(byte[].class, new Base64TypeAdapter());
	return builder;
}