private GsonBuilder configureGsonBuilder() { GsonBuilder gsonBuilder = new GsonBuilder(); JsonSerializer<NavigationArriveEvent> arriveSerializer = new ArriveEventSerializer(); gsonBuilder.registerTypeAdapter(NavigationArriveEvent.class, arriveSerializer); JsonSerializer<NavigationDepartEvent> departSerializer = new DepartEventSerializer(); gsonBuilder.registerTypeAdapter(NavigationDepartEvent.class, departSerializer); JsonSerializer<NavigationCancelEvent> cancelSerializer = new CancelEventSerializer(); gsonBuilder.registerTypeAdapter(NavigationCancelEvent.class, cancelSerializer); JsonSerializer<NavigationFeedbackEvent> feedbackSerializer = new FeedbackEventSerializer(); gsonBuilder.registerTypeAdapter(NavigationFeedbackEvent.class, feedbackSerializer); JsonSerializer<NavigationRerouteEvent> rerouteSerializer = new RerouteEventSerializer(); gsonBuilder.registerTypeAdapter(NavigationRerouteEvent.class, rerouteSerializer); JsonSerializer<NavigationFasterRouteEvent> fasterRouteSerializer = new FasterRouteEventSerializer(); gsonBuilder.registerTypeAdapter(NavigationFasterRouteEvent.class, fasterRouteSerializer); return gsonBuilder; }
@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)); }
public HanaDBTemplate() { GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Point.class, (JsonSerializer<Point>) (Point src, Type type, JsonSerializationContext context) -> { JsonObject obj = new JsonObject(); // serialize it all to strings for reasons.. obj.addProperty("ZEITREIHE", src.getTimeseries()); obj.addProperty("TIME", String.valueOf(src.getTimestamp())); obj.addProperty("VALUE", src.getValue().toString()); return obj; }); gson = builder.create(); OkHttpClient.Builder okHBuilder = new OkHttpClient.Builder(); okHBuilder.readTimeout(30, TimeUnit.SECONDS); okHBuilder.writeTimeout(30, TimeUnit.SECONDS); okHttpClient = okHBuilder.build(); }
/** * Returns a new JSON serializer, specialized for {@link SettingsManager} * objects. * * @return The serializer to serialize {@code SettingsManager} objects with. */ static JsonSerializer<SettingsManager> newSettingsSerializer() { return (settingsManager, typeOfObject, context) -> { if (settingsManager == null) return null; Map<String, String> settings = settingsManager.getAllAsMap(); if (isEmpty(settings)) return null; JsonObject jsonObject = new JsonObject(); for (Map.Entry<String, String> entry : settings.entrySet()) jsonObject.addProperty(entry.getKey(), entry.getValue()); return jsonObject; }; }
/** * Returns a new JSON serializer, specialized for {@link Configuration} * objects. * * @return The serializer to serialize {@code Configuration} objects with. */ static JsonSerializer<Configuration> newConfigurationSerializer() { return (configuration, typeOfObject, context) -> { if (configuration == null) return null; JsonObject jsonObject = new JsonObject(); HeaderManager defaultResponseHeaderManager = configuration.defaultResponseHeaderManager(); if (defaultResponseHeaderManager.keyCount() > 0) jsonObject.add("defaultResponseHeaders", context.serialize(defaultResponseHeaderManager)); SettingsManager settingsManager = configuration.settingsManager(); if (settingsManager.entryCount() > 0) jsonObject.add("settings", context.serialize(settingsManager)); List<MockRequest> requests = configuration.requests(); if (requests.size() > 0) jsonObject.add("requests", context.serialize(requests)); return jsonObject; }; }
/** * Returns a new JSON serializer, specialized for {@link MockRequest} * objects. * * @return The serializer to serialize {@code MockRequest} objects with. */ static JsonSerializer<MockRequest> newRequestSerializer() { return (request, typeOfObject, context) -> { if (request == null) return null; JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("url", request.url()); jsonObject.addProperty("method", request.method()); HeaderManager headerManager = request.headerManager(); if (headerManager.keyCount() > 0) jsonObject.add("headers", context.serialize(headerManager)); SettingsManager settingsManager = request.settingsManager(); if (settingsManager.entryCount() > 0) jsonObject.add("settings", context.serialize(settingsManager)); List<MockResponse> responses = request.responses(); if (notEmpty(responses)) jsonObject.add("responses", context.serialize(responses)); return jsonObject; }; }
/** * Returns a new JSON serializer, specialized for {@link MockResponse} * objects. * * @return The serializer to serialize {@code MockResponse} objects with. */ static JsonSerializer<MockResponse> newResponseSerializer() { return (response, typeOfObject, context) -> { if (response == null) return null; JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("code", response.code()); jsonObject.addProperty("phrase", response.phrase()); String source = response.source(); if (notEmpty(source)) jsonObject.addProperty("source", source); HeaderManager headerManager = response.headerManager(); if (headerManager.keyCount() > 0) jsonObject.add("headers", context.serialize(headerManager)); SettingsManager settingsManager = response.settingsManager(); if (settingsManager.entryCount() > 0) jsonObject.add("settings", context.serialize(settingsManager)); return jsonObject; }; }
public GSONJSONEngine() { this.serializer = new JsonSerializer<JSONSerializable>() { public JsonElement serialize(JSONSerializable src, Type typeOfSrc, JsonSerializationContext context) { Object o = src.toJSON(GSONJSONEngine.this); if(o instanceof GSONJSONObject) return context.serialize(((GSONJSONObject) o).gsonObj); else if(o instanceof GSONJSONArray) return context.serialize(((GSONJSONArray) o).gsonArr); return context.serialize(o); } }; GsonBuilder builder = new GsonBuilder(); builder.registerTypeHierarchyAdapter(JSONSerializable.class, this.serializer); if(Urmusic.DEBUG) builder.setPrettyPrinting(); this.gson = builder.create(); }
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); }
public static <T> T jsonToObject(String jsonString, Class<T> classOfT) { // Gson gson = new Gson(); Gson gson = new GsonBuilder() .registerTypeHierarchyAdapter(Date.class, new JsonSerializer<Date>() { @Override public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { SimpleDateFormat format = new SimpleDateFormat( dateformat); return new JsonPrimitive(format.format(src)); } }).setDateFormat(dateformat).create(); Object object = gson.fromJson(jsonString, (Type) classOfT); return Primitives.wrap(classOfT).cast(object); }
/** * The serializer overrides field adapter, but for deserializer the fieldAdapter is used. */ @Test(timeout = 1000) public void testRegisteredSerializerOverridesJsonAdapter_add1167() { fr.inria.diversify.testamplification.logger.Logger.writeTestStart(Thread.currentThread(),this, "testRegisteredSerializerOverridesJsonAdapter_add1167"); 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")); fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(),1677,json); A target = gson.fromJson("abcd", A.class); fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(),1678,target.value); fr.inria.diversify.testamplification.logger.Logger.writeTestFinish(Thread.currentThread()); }
/** * The serializer overrides field adapter, but for deserializer the fieldAdapter is used. */ @Test(timeout = 1000) public void testRegisteredSerializerOverridesJsonAdapter_remove984() { fr.inria.diversify.testamplification.logger.Logger.writeTestStart(Thread.currentThread(),this, "testRegisteredSerializerOverridesJsonAdapter_remove984"); 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")); fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(),1677,json); A target = gson.fromJson("abcd", A.class); fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(),1678,target.value); fr.inria.diversify.testamplification.logger.Logger.writeTestFinish(Thread.currentThread()); }
@Test(timeout = 1000) public void testCustomSerializers_add1030() { fr.inria.diversify.testamplification.logger.Logger.writeTestStart(Thread.currentThread(),this, "testCustomSerializers_add1030"); Gson gson = builder.registerTypeAdapter(TestTypes.ClassWithCustomTypeConverter.class, new JsonSerializer<com.google.gson.common.TestTypes.ClassWithCustomTypeConverter>() { public JsonElement serialize(TestTypes.ClassWithCustomTypeConverter src, Type typeOfSrc, JsonSerializationContext context) { JsonObject json = new JsonObject(); json.addProperty("bag", 5); json.addProperty("bag", 5); json.addProperty("value", 25); return json; } }).create(); TestTypes.ClassWithCustomTypeConverter target = new TestTypes.ClassWithCustomTypeConverter(); fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(),1145,gson,1144,gson.toJson(target)); fr.inria.diversify.testamplification.logger.Logger.writeTestFinish(Thread.currentThread()); }
@Test(timeout = 1000) public void testCustomSerializers_add1031() { fr.inria.diversify.testamplification.logger.Logger.writeTestStart(Thread.currentThread(),this, "testCustomSerializers_add1031"); Gson gson = builder.registerTypeAdapter(TestTypes.ClassWithCustomTypeConverter.class, new JsonSerializer<com.google.gson.common.TestTypes.ClassWithCustomTypeConverter>() { public JsonElement serialize(TestTypes.ClassWithCustomTypeConverter src, Type typeOfSrc, JsonSerializationContext context) { JsonObject json = new JsonObject(); json.addProperty("bag", 5); json.addProperty("value", 25); json.addProperty("value", 25); return json; } }).create(); TestTypes.ClassWithCustomTypeConverter target = new TestTypes.ClassWithCustomTypeConverter(); fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(),1145,gson,1144,gson.toJson(target)); fr.inria.diversify.testamplification.logger.Logger.writeTestFinish(Thread.currentThread()); }
@Test(timeout = 1000) public void testCustomByteArraySerializer_add1022() { fr.inria.diversify.testamplification.logger.Logger.writeTestStart(Thread.currentThread(),this, "testCustomByteArraySerializer_add1022"); Gson gson = new GsonBuilder().registerTypeAdapter(byte[].class, new JsonSerializer<byte[]>() { public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) { java.lang.StringBuilder sb = new java.lang.StringBuilder(src.length); for (byte b : src) { sb.append(b); } return new JsonPrimitive(sb.toString()); } }).create(); byte[] data = new byte[]{ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 }; String json = gson.toJson(data); fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(),1127,json); fr.inria.diversify.testamplification.logger.Logger.writeTestFinish(Thread.currentThread()); }
@Test(timeout = 1000) public void testCustomByteArraySerializer_add1023() { fr.inria.diversify.testamplification.logger.Logger.writeTestStart(Thread.currentThread(),this, "testCustomByteArraySerializer_add1023"); Gson gson = new GsonBuilder().registerTypeAdapter(byte[].class, new JsonSerializer<byte[]>() { public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) { java.lang.StringBuilder sb = new java.lang.StringBuilder(src.length); for (byte b : src) { sb.append(b); sb.append(b); } return new JsonPrimitive(sb.toString()); } }).create(); byte[] data = new byte[]{ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 }; String json = gson.toJson(data); fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(),1127,json); fr.inria.diversify.testamplification.logger.Logger.writeTestFinish(Thread.currentThread()); }
public void testCustomByteArraySerializer() { fr.inria.diversify.testamplification.logger.Logger.writeTestStart(Thread.currentThread(),this, "testCustomByteArraySerializer"); Gson gson = new GsonBuilder().registerTypeAdapter(byte[].class, new JsonSerializer<byte[]>() { public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) { java.lang.StringBuilder sb = new java.lang.StringBuilder(src.length); for (byte b : src) { sb.append(b); } return new JsonPrimitive(sb.toString()); } }).create(); byte[] data = new byte[]{ -1 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 }; String json = gson.toJson(data); fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(),1127,json); fr.inria.diversify.testamplification.logger.Logger.writeTestFinish(Thread.currentThread()); }
public void testCustomByteArraySerializer_literalMutation1058() { fr.inria.diversify.testamplification.logger.Logger.writeTestStart(Thread.currentThread(),this, "testCustomByteArraySerializer_literalMutation1058"); Gson gson = new GsonBuilder().registerTypeAdapter(byte[].class, new JsonSerializer<byte[]>() { public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) { java.lang.StringBuilder sb = new java.lang.StringBuilder(src.length); for (byte b : src) { sb.append(b); } return new JsonPrimitive(sb.toString()); } }).create(); byte[] data = new byte[]{ 0 , 0 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 }; String json = gson.toJson(data); fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(),1127,json); fr.inria.diversify.testamplification.logger.Logger.writeTestFinish(Thread.currentThread()); }
public void testCustomByteArraySerializer_literalMutation1059() { fr.inria.diversify.testamplification.logger.Logger.writeTestStart(Thread.currentThread(),this, "testCustomByteArraySerializer_literalMutation1059"); Gson gson = new GsonBuilder().registerTypeAdapter(byte[].class, new JsonSerializer<byte[]>() { public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) { java.lang.StringBuilder sb = new java.lang.StringBuilder(src.length); for (byte b : src) { sb.append(b); } return new JsonPrimitive(sb.toString()); } }).create(); byte[] data = new byte[]{ 0 , 1 , 3 , 3 , 4 , 5 , 6 , 7 , 8 , 9 }; String json = gson.toJson(data); fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(),1127,json); fr.inria.diversify.testamplification.logger.Logger.writeTestFinish(Thread.currentThread()); }
public void testCustomByteArraySerializer_literalMutation1060() { fr.inria.diversify.testamplification.logger.Logger.writeTestStart(Thread.currentThread(),this, "testCustomByteArraySerializer_literalMutation1060"); Gson gson = new GsonBuilder().registerTypeAdapter(byte[].class, new JsonSerializer<byte[]>() { public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) { java.lang.StringBuilder sb = new java.lang.StringBuilder(src.length); for (byte b : src) { sb.append(b); } return new JsonPrimitive(sb.toString()); } }).create(); byte[] data = new byte[]{ 0 , 1 , 2 , 2 , 4 , 5 , 6 , 7 , 8 , 9 }; String json = gson.toJson(data); fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(),1127,json); fr.inria.diversify.testamplification.logger.Logger.writeTestFinish(Thread.currentThread()); }
public void testCustomByteArraySerializer_literalMutation1061() { fr.inria.diversify.testamplification.logger.Logger.writeTestStart(Thread.currentThread(),this, "testCustomByteArraySerializer_literalMutation1061"); Gson gson = new GsonBuilder().registerTypeAdapter(byte[].class, new JsonSerializer<byte[]>() { public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) { java.lang.StringBuilder sb = new java.lang.StringBuilder(src.length); for (byte b : src) { sb.append(b); } return new JsonPrimitive(sb.toString()); } }).create(); byte[] data = new byte[]{ 0 , 1 , 2 , 3 , 5 , 5 , 6 , 7 , 8 , 9 }; String json = gson.toJson(data); fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(),1127,json); fr.inria.diversify.testamplification.logger.Logger.writeTestFinish(Thread.currentThread()); }
public void testCustomByteArraySerializer_literalMutation1062() { fr.inria.diversify.testamplification.logger.Logger.writeTestStart(Thread.currentThread(),this, "testCustomByteArraySerializer_literalMutation1062"); Gson gson = new GsonBuilder().registerTypeAdapter(byte[].class, new JsonSerializer<byte[]>() { public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) { java.lang.StringBuilder sb = new java.lang.StringBuilder(src.length); for (byte b : src) { sb.append(b); } return new JsonPrimitive(sb.toString()); } }).create(); byte[] data = new byte[]{ 0 , 1 , 2 , 3 , 4 , 6 , 6 , 7 , 8 , 9 }; String json = gson.toJson(data); fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(),1127,json); fr.inria.diversify.testamplification.logger.Logger.writeTestFinish(Thread.currentThread()); }
public void testCustomByteArraySerializer_literalMutation1063() { fr.inria.diversify.testamplification.logger.Logger.writeTestStart(Thread.currentThread(),this, "testCustomByteArraySerializer_literalMutation1063"); Gson gson = new GsonBuilder().registerTypeAdapter(byte[].class, new JsonSerializer<byte[]>() { public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) { java.lang.StringBuilder sb = new java.lang.StringBuilder(src.length); for (byte b : src) { sb.append(b); } return new JsonPrimitive(sb.toString()); } }).create(); byte[] data = new byte[]{ 0 , 1 , 2 , 3 , 4 , 5 , 5 , 7 , 8 , 9 }; String json = gson.toJson(data); fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(),1127,json); fr.inria.diversify.testamplification.logger.Logger.writeTestFinish(Thread.currentThread()); }
public void testCustomByteArraySerializer_literalMutation1064() { fr.inria.diversify.testamplification.logger.Logger.writeTestStart(Thread.currentThread(),this, "testCustomByteArraySerializer_literalMutation1064"); Gson gson = new GsonBuilder().registerTypeAdapter(byte[].class, new JsonSerializer<byte[]>() { public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) { java.lang.StringBuilder sb = new java.lang.StringBuilder(src.length); for (byte b : src) { sb.append(b); } return new JsonPrimitive(sb.toString()); } }).create(); byte[] data = new byte[]{ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 8 , 8 , 9 }; String json = gson.toJson(data); fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(),1127,json); fr.inria.diversify.testamplification.logger.Logger.writeTestFinish(Thread.currentThread()); }
public void testCustomByteArraySerializer_literalMutation1065() { fr.inria.diversify.testamplification.logger.Logger.writeTestStart(Thread.currentThread(),this, "testCustomByteArraySerializer_literalMutation1065"); Gson gson = new GsonBuilder().registerTypeAdapter(byte[].class, new JsonSerializer<byte[]>() { public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) { java.lang.StringBuilder sb = new java.lang.StringBuilder(src.length); for (byte b : src) { sb.append(b); } return new JsonPrimitive(sb.toString()); } }).create(); byte[] data = new byte[]{ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 7 , 9 }; String json = gson.toJson(data); fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(),1127,json); fr.inria.diversify.testamplification.logger.Logger.writeTestFinish(Thread.currentThread()); }
public void testCustomByteArraySerializer_literalMutation1066() { fr.inria.diversify.testamplification.logger.Logger.writeTestStart(Thread.currentThread(),this, "testCustomByteArraySerializer_literalMutation1066"); Gson gson = new GsonBuilder().registerTypeAdapter(byte[].class, new JsonSerializer<byte[]>() { public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) { java.lang.StringBuilder sb = new java.lang.StringBuilder(src.length); for (byte b : src) { sb.append(b); } return new JsonPrimitive(sb.toString()); } }).create(); byte[] data = new byte[]{ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 10 }; String json = gson.toJson(data); fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(),1127,json); fr.inria.diversify.testamplification.logger.Logger.writeTestFinish(Thread.currentThread()); }
@Test(timeout = 1000) public void testCustomByteArraySerializer_remove848() { fr.inria.diversify.testamplification.logger.Logger.writeTestStart(Thread.currentThread(),this, "testCustomByteArraySerializer_remove848"); Gson gson = new GsonBuilder().registerTypeAdapter(byte[].class, new JsonSerializer<byte[]>() { public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) { java.lang.StringBuilder sb = new java.lang.StringBuilder(src.length); for (byte b : src) { sb.append(b); } return new JsonPrimitive(sb.toString()); } }).create(); byte[] data = new byte[]{ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 }; String json = gson.toJson(data); fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(),1127,json); fr.inria.diversify.testamplification.logger.Logger.writeTestFinish(Thread.currentThread()); }
@Test(timeout = 1000) public void testCustomByteArraySerializer_remove849() { fr.inria.diversify.testamplification.logger.Logger.writeTestStart(Thread.currentThread(),this, "testCustomByteArraySerializer_remove849"); Gson gson = new GsonBuilder().registerTypeAdapter(byte[].class, new JsonSerializer<byte[]>() { public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) { java.lang.StringBuilder sb = new java.lang.StringBuilder(src.length); for (byte b : src) { } return new JsonPrimitive(sb.toString()); } }).create(); byte[] data = new byte[]{ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 }; String json = gson.toJson(data); fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(),1127,json); fr.inria.diversify.testamplification.logger.Logger.writeTestFinish(Thread.currentThread()); }
public static JSONObject toJson(LogSession logSession) throws JSONException { // Creates the json object which will manage the information received GsonBuilder builder = new GsonBuilder(); // Register an adapter to manage the date types as long values builder.registerTypeAdapter(Date.class, new JsonSerializer<Date>() { @Override public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { return context.serialize(src.getTime()); } }); Gson gson = builder.create(); try { return new JSONObject(gson.toJson(logSession, LogSession.class)); } catch (JSONException | JsonIOException e) { throw new JSONException(e.getMessage()); } }
private void serializeConfigurableProperties(JsonObject configJsonObject, Object configInstance, JsonSerializationContext jsonSerializationContext) { List<Field> configurableFields = Arrays.stream(configInstance.getClass().getFields()) .filter(field -> field.getAnnotation(ConfigurableProperty.class) != null).collect(Collectors.toList()); configurableFields.forEach(field -> { String fieldName = determineNameToUseForField(field); Object fieldValue = ReflectionUtils.getValue(field, configInstance); if (fieldValue != null) { JsonElement fieldJsonObject; if (field.getAnnotation(JsonAdapter.class) != null) { try { JsonSerializer customSerializer = (JsonSerializer) field.getAnnotation(JsonAdapter.class).value().newInstance(); fieldJsonObject = customSerializer.serialize(fieldValue, field.getType(), jsonSerializationContext); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeReflectiveOperationException(e); } } else { fieldJsonObject = jsonSerializationContext.serialize(fieldValue); } configJsonObject.add(fieldName, fieldJsonObject); } }); }
@Override public JsonElement serialize(Match src, Type typeOfSrc, JsonSerializationContext context) { JsonSerializer<Player> playerSerializer = new Player.PlayerSerializer(); JsonObject root = new JsonObject(); root.addProperty("id", src.id); if (src.black != null) { root.add("white", playerSerializer.serialize(src.white, Player.class, context)); } if (src.black != null) { root.add("black", playerSerializer.serialize(src.black, Player.class, context)); } if (src.result != null) { root.addProperty("result", src.result.name()); } root.addProperty("displayResult", src.displayResult); return root; }
/** * 将对象转换成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; }
public ScheduleDebugController( ChannelResolver channelResolver, EquivalentScheduleStore equivalentScheduleStore, ScheduleStore scheduleStore) { this.channelResolver = channelResolver; this.equivalentScheduleStore = equivalentScheduleStore; this.scheduleStore = scheduleStore; this.gson = new GsonBuilder() .registerTypeAdapter( DateTime.class, (JsonSerializer<DateTime>) (src, typeOfSrc, context) -> new JsonPrimitive(src.toString()) ) .registerTypeAdapter( Interval.class, (JsonSerializer<Interval>) (src, typeOfSrc, context) -> new JsonPrimitive(src.toString()) ) .create(); }
private <T> De_Serializator(Type type, JsonSerializer<T> typeAdapter) { Loggers.getGsonLoggersForSpecificClass(type).debug("Declare serializer " + type.getTypeName()); this.type = type; if (Loggers.getGsonLoggersForSpecificClass(type).isTraceEnabled()) { this.typeAdapter = new JsonSerializer<T>() { public JsonElement serialize(T src, Type typeOfSrc, JsonSerializationContext context) { JsonElement result = typeAdapter.serialize(src, typeOfSrc, context); Loggers.getGsonLoggersForSpecificClass(type).trace("Serialize to " + result.toString()); return result; } }; } else { this.typeAdapter = typeAdapter; } }
@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)); }
@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()); }
public <T> void register( String uri , Class<T> clazz , JsonSerializer<T> serializer , JsonDeserializer<T> deserializer ) { this.dicionary.register(uri, clazz); if (serializer != null) { builder.registerTypeAdapter(clazz, serializer); } if (deserializer != null) { builder.registerTypeAdapter(clazz, deserializer); } }
public static void main(String[] args) throws IOException, ParseException { configureLog(); if (args.length != 1) { System.out.println("Usage: main <apk path>"); System.exit(-1); } String apkPath = args[0]; GsonBuilder gsonBuilder = new GsonBuilder(); JsonSerializer<TObjectIntMap> serializer = (src, typeOfSrc, context) -> { JsonObject jsonMerchant = new JsonObject(); for (Object key : src.keys()) { int value = src.get(key); jsonMerchant.addProperty(key.toString(), value); } return jsonMerchant; }; gsonBuilder.registerTypeAdapter(TObjectIntMap.class, serializer); Gson gson = gsonBuilder .disableHtmlEscaping() .serializeSpecialFloatingPointValues() .setExclusionStrategies(new JarFileExclusionStrategy()) .setPrettyPrinting() .create(); Writer writer = new OutputStreamWriter(System.out); ApkFile apkFile = new ApkFile(apkPath, true, true, true, true, false); gson.toJson(apkFile, writer); writer.close(); apkFile.close(); }
@Override public Object create(String modelId, Map<String, Object> valueMap) throws ClassNotFoundException { Gson gson = new GsonBuilder(). registerTypeAdapter(Double.class, (JsonSerializer<Double>) (src, typeOfSrc, context) -> { if (src == src.longValue()) return new JsonPrimitive(src.longValue()); return new JsonPrimitive(src); }).create(); String json = gson.toJson(valueMap); Class modelClass = Class.forName(modelId); IParser fhirContextParser = FhirContext.forDstu3().newJsonParser(); return fhirContextParser.parseResource(modelClass, json); }