Refine search
private static String toJsonString(Object object) { Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); return gson.toJson(object); }
public static Gson getInstance() { if (gson == null) { gson = new GsonBuilder() .setPrettyPrinting() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .registerTypeAdapter(Date.class, new DateTypeAdapter()) .create(); } return gson; } }
@Override public void afterPropertiesSet() { GsonBuilder builder = (this.base64EncodeByteArrays ? GsonBuilderUtils.gsonBuilderWithBase64EncodedByteArrays() : new GsonBuilder()); if (this.serializeNulls) { builder.serializeNulls(); } if (this.prettyPrinting) { builder.setPrettyPrinting(); } if (this.disableHtmlEscaping) { builder.disableHtmlEscaping(); } if (this.dateFormatPattern != null) { builder.setDateFormat(this.dateFormatPattern); } this.gson = builder.create(); }
private static <T> void populate(GsonBuilder builder, String json, Class<T> type, final T into) { builder.registerTypeAdapter(type, (InstanceCreator<T>) t -> into) .create() .fromJson(json, type); } }
/** * 注册Gson解析对象. * * @param type Gson解析对象类型 * @param typeAdapter Gson解析对象适配器 */ public static synchronized void registerTypeAdapter(final Type type, final TypeAdapter typeAdapter) { GSON_BUILDER.registerTypeAdapter(type, typeAdapter); gson = GSON_BUILDER.create(); }
@Override public void print(Collection<TableModel> models) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonObject jsonRoot = new JsonObject(); if (file != null) { jsonRoot.add("file", new JsonPrimitive(file.toString())); } models.forEach(model -> { jsonRoot.add(model.name().toLowerCase(), tableToJson(model.table(), gson)); }); gson.toJson(jsonRoot, out); }
@Override public List<WxCpTag> tagGet() throws WxErrorException { String url = "https://qyapi.weixin.qq.com/cgi-bin/tag/list"; String responseContent = get(url, null); JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); return WxCpGsonBuilder.INSTANCE.create() .fromJson( tmpJsonElement.getAsJsonObject().get("taglist"), new TypeToken<List<WxCpTag>>() { }.getType() ); }
private Map<String, Object> getMetadataFromFile(String artifactId) throws IOException { final String fileToString = FileUtils.readFileToString(metadataFileDest, StandardCharsets.UTF_8); LOGGER.debug(format("Reading metadata from file %s.", metadataFileDest.getAbsolutePath())); final Type type = new TypeToken<Map<String, Object>>() { }.getType(); final Map<String, Map> allArtifactsPerPlugin = new GsonBuilder().create().fromJson(fileToString, type); return allArtifactsPerPlugin.get(artifactId); }
@Override public List<WxMpUserSummary> getUserSummary(Date beginDate, Date endDate) throws WxErrorException { String url = "https://api.weixin.qq.com/datacube/getusersummary"; JsonObject param = new JsonObject(); param.addProperty("begin_date", SIMPLE_DATE_FORMAT.format(beginDate)); param.addProperty("end_date", SIMPLE_DATE_FORMAT.format(endDate)); String responseContent = post(url, param.toString()); JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); return WxMpGsonBuilder.INSTANCE.create().fromJson(tmpJsonElement.getAsJsonObject().get("list"), new TypeToken<List<WxMpUserSummary>>() { }.getType()); }
@Override public String requestMessageForNotifyPluginSettingsChange(Map<String, String> pluginSettings) { return new GsonBuilder().create().toJson(pluginSettings); }
GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); gsonBuilder.registerTypeAdapter(Timestamp.class, new TimestampDeserializer()); Gson gson = gsonBuilder.create(); User[] users = gson.fromJson(jsonInput, User[].class); for (User user : users) throws JsonParseException long time = Long.parseLong(json.getAsString()); return new Timestamp(time);
public class Test { public static void main(String[] args) { IAnimal animals[] = new IAnimal[]{new Cat("Kitty"), new Dog("Brutus", 5)}; Gson gsonExt = null; { GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(IAnimal.class , new IAnimalAdapter()); gsonExt = builder.create(); } for (IAnimal animal : animals) { String animalJson = gsonExt.toJson(animal, IAnimal.class); System.out.println("serialized with the custom serializer:" +animalJson); IAnimal animal2 = gsonExt.fromJson(animalJson, IAnimal.class); System.out.println(animal2.sound()); } }
@NonNull public Command parse(@NonNull String json) JsonObject parsed = new JsonParser().parse(json).getAsJsonObject(); String event = parsed.get("event").getAsString(); Gson gson = new GsonBuilder().create(); .fromJson(json, ArchiveHabitsCommand.Record.class) .toCommand(habitList); .fromJson(json, ChangeHabitColorCommand.Record.class) .toCommand(habitList); .fromJson(json, CreateHabitCommand.Record.class) .toCommand(modelFactory, habitList);
private Event deserializeSpecificEventData(JsonObject jsonObject, String className) { Event result = null; Gson gson = new GsonBuilder().create(); GsonDeserializationContext deserializationContext = new GsonDeserializationContext(null); if (className.equals(CameraTargetChangedEvent.class.getName())) { EntityRef oldTarget = new RecordedEntityRef(jsonObject.get("OldTarget").getAsLong(), (LowLevelEntityManager) this.entityManager); EntityRef newTarget = new RecordedEntityRef(jsonObject.get("NewTarget").getAsLong(), (LowLevelEntityManager) this.entityManager); result = new CameraTargetChangedEvent(oldTarget, newTarget); } else if (className.equals(PlaySoundEvent.class.getName())) { float volume = jsonObject.get("volume").getAsFloat(); GsonPersistedData data = new GsonPersistedData(jsonObject.get("sound")); TypeHandler handler = typeSerializationLibrary.getTypeHandlerFromClass(StaticSound.class); GsonPersistedData data = new GsonPersistedData(jsonObject.get("movementMode")); MovementMode movementMode = (MovementMode) handler.deserialize(data, deserializationContext); TFloatList modifiers = gson.fromJson(jsonObject.get("modifiers"), TFloatArrayList.class); TFloatList multipliers = gson.fromJson(jsonObject.get("multipliers"), TFloatArrayList.class); TFloatList postModifiers = gson.fromJson(jsonObject.get("postModifiers"), TFloatArrayList.class); GetMaxSpeedEvent event = new GetMaxSpeedEvent(baseValue, movementMode); event.setPostModifiers(postModifiers);
GsonBuilder b = new GsonBuilder(); b.registerTypeAdapter(Apple.class, new JsonDeserializer<Apple>() { @Override public Apple deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { JsonObject appleObj = arg0.getAsJsonObject(); Gson g = new Gson(); // Construct an apple (this shouldn't try to parse the seeds stuff Apple a = g.fromJson(arg0, Apple.class); List<Seed> seeds = null; // Check to see if we were given a list or a single seed if (appleObj.get("seeds").isJsonArray()) { // if it's a list, just parse that from the JSON seeds = g.fromJson(appleObj.get("seeds"), new TypeToken<List<Seed>>() { }.getType()); } else { // otherwise, parse the single seed, // and add it to the list Seed single = g.fromJson(appleObj.get("seeds"), Seed.class); seeds = new ArrayList<Seed>(); seeds.add(single); } // set the correct seed list a.setSeeds(seeds); return a; } });
dateColumnMapping.put("created", JdbcType.TIMESTAMP); workUnitState.appendToListProp(AvroToJdbcEntryConverter.CONVERTER_AVRO_JDBC_DATE_FIELDS, new Gson().toJson(dateColumnMapping)); Gson gson = new GsonBuilder().registerTypeAdapter(JdbcEntryData.class, serializer).serializeNulls().create(); JsonElement actualSerialized = gson.toJsonTree(entries); JsonElement expectedSerialized = new JsonParser().parse(new InputStreamReader(getClass().getResourceAsStream("/converter/pickfields_nested_with_union.json")));
public static <T> T safeFromJson(final String jsonString, final Class<T> clazz) { GsonBuilder builder = new GsonBuilder(); Gson gson = builder.excludeFieldsWithoutExposeAnnotation().create(); try { return gson.fromJson(jsonString, clazz); } catch (Exception e) { return null; } } }
public JavadocJsonGenerator( RobolectricModel model, ProcessingEnvironment environment, File jsonDocsDir) { super(); this.model = model; this.messager = environment.getMessager(); gson = new GsonBuilder() .setPrettyPrinting() .create(); this.jsonDocsDir = jsonDocsDir; }
jsonWriter.setIndent(" "); JsonParser jsonParser = new JsonParser(); Gson gson = new GsonBuilder().create(); gson.toJson(jsonParser.parse(gson.toJson(zooKeeperEndpointConfig)).getAsJsonObject(), jsonWriter); gson.toJson(jsonParser.parse(gson.toJson(dataStatAclNode)).getAsJsonObject(), jsonWriter);
Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonParser jp = new JsonParser(); JsonElement je = jp.parse(uglyJSONString); String prettyJsonString = gson.toJson(je);