public void checkSimpleComposedObject() throws IOException { ValidatedConstructor x = new ValidatedConstructor(Optional.of(0), 1); ValidatedConstructor y = new ValidatedConstructor(Optional.of(1), 2); TypeAdapter<ComposedObjects> adapter = parameterizedCtorFactory.create(gson, TypeToken.get(ComposedObjects.class)); assertEquals( new ComposedObjects(x, y), adapter.fromJson("{\"x\":{\"foo\":0,\"bar\":1},\"y\":{\"foo\":1,\"bar\":2}}")); }
public void testGenericParamsCopiedIn() throws IOException { TypeAdapter<GenericParamsCopiedIn> adapter = parameterizedCtorFactory.create(gson, TypeToken.get(GenericParamsCopiedIn.class)); List<String> inputFoo = Lists.newArrayList(); inputFoo.add("one"); Map<String, String> inputBar = Maps.newHashMap(); inputBar.put("2", "two"); GenericParamsCopiedIn toTest = adapter.fromJson("{ \"foo\":[\"one\"], \"bar\":{ \"2\":\"two\"}}"); assertEquals(inputFoo, toTest.foo); assertNotSame(inputFoo, toTest.foo); assertEquals(inputBar, toTest.bar); }
@Override public void write(JsonWriter out, Quest value) throws IOException { out.beginObject(); out.name(NAME).value(value.getName()); out.name(DESCRIPTION).value(value.getDescription()); out.name(X).value(value.getGuiX()); out.name(Y).value(value.getGuiY()); if (value.useBigIcon()) { out.name(BIG_ICON).value(true); } if (value.getIcon() != null) { MinecraftAdapter.ITEM_STACK.write(out.name(ICON), value.getIcon()); } writeQuestList( out, value.getRequirement(), value.getQuestSet().getQuests(), REQUIREMENTS); writeQuestList(out, value.getOptionLinks(), value.getQuestSet().getQuests(), OPTIONS); if (value.getRepeatInfo().getType() != RepeatType.NONE) { REPEAT_INFO_ADAPTER.write(out.name(REPEAT), value.getRepeatInfo()); } if (value.getTriggerType() != TriggerType.NONE) { out.name(TRIGGER).value(value.getTriggerType().name()); } if (value.getTriggerType().isUseTaskCount()) { out.name(TRIGGER_TASKS).value(value.getTriggerTasks()); } if (value.getUseModifiedParentRequirement()) { out.name(PARENT_REQUIREMENT).value(value.getParentRequirementCount()); } out.name(TASKS).beginArray(); for (QuestTask task : value.getTasks()) { TASK_ADAPTER.write(out, task); } out.endArray(); writeItemStackArray( out, (ItemStack[]) ReflectionHelper.getPrivateValue(Quest.class, value, REWARDS), REWARDS); writeItemStackArray( out, (ItemStack[]) ReflectionHelper.getPrivateValue(Quest.class, value, REWARDS_CHOICE), REWARDS_CHOICE); if (value.getReputationRewards() != null && !value.getReputationRewards().isEmpty()) { out.name(REWARDS_REPUTATION).beginArray(); for (Quest.ReputationReward reward : value.getReputationRewards()) { REPUTATION_REWARD_ADAPTER.write(out, reward); } out.endArray(); } out.endObject(); }
public Map<K, V> read(JsonReader in) throws IOException { Map<K, V> result = Maps.newHashMap(); in.beginObject(); while (in.hasNext()) { JsonReaderInternalAccess.INSTANCE.promoteNameToValue(in); K name = keyAdapter.read(in); V value = valueAdapter.read(in); if (value != null) { // If there are repeated keys, overwrite them to only keep the last one result.put(name, value); } } in.endObject(); return ImmutableMap.copyOf(result); }
@Override public void write(JsonWriter out, Patch<Data> value) throws IOException { JsonTreeWriter treeWriter = new JsonTreeWriter(); treeWriter.setSerializeNulls(true); _dataAdapter.write(treeWriter, value.data()); JsonObject tree = treeWriter.get().getAsJsonObject(); Set<String> presentJsonProperties = new HashSet<>(); for (Field field : value.changedFields()) { SerializedName nameSpecifier = field.getAnnotation(SerializedName.class); String jsonPropertyName = (nameSpecifier != null ? nameSpecifier.value() : field.getName()); presentJsonProperties.add(jsonPropertyName); } for (Map.Entry<String, JsonElement> entry : new ArrayList<>(tree.entrySet())) { if (!presentJsonProperties.contains(entry.getKey())) { tree.remove(entry.getKey()); } } // If a data field changed to null the null should be serialized. // This is the whole point of this adapter. ObjectTargetedJsonWriter patchWriter = new ObjectTargetedJsonWriter(out); patchWriter.setTargetedSerializeNulls(true); _gson.getAdapter(JsonObject.class).write(patchWriter, tree); }
public Object read(JsonReader jsonreader) { if (jsonreader.peek() == JsonToken.NULL) { jsonreader.nextNull(); return null; } else { return a.read(jsonreader); } }
@Override public T fromBody(ResponseBody body) throws IOException { Reader reader = body.charStream(); try { return typeAdapter.fromJson(reader); } finally { closeQuietly(reader); } }
public void write(JsonWriter jsonwriter, Object obj) { if (obj == null) { jsonwriter.nullValue(); return; } else { a.write(jsonwriter, obj); return; } }
@Override public void write(JsonWriter out, QuestTask value) throws IOException { out.beginObject(); TaskType type = TaskType.getType(value.getClass()); out.name(TYPE).value(type.name()); if (!value.getDescription().equals(type.name)) out.name(DESCRIPTION).value(value.getDescription()); if (!value.getLongDescription().equals(type.description)) out.name(LONG_DESCRIPTION).value(value.getLongDescription()); if (value instanceof QuestTaskItems) { out.name(ITEMS).beginArray(); for (QuestTaskItems.ItemRequirement requirement : ((QuestTaskItems) value).getItems()) { ITEM_REQUIREMENT_ADAPTER.write(out, requirement); } out.endArray(); } else if (value instanceof QuestTaskDeath) { out.name(DEATHS).value(((QuestTaskDeath) value).getDeaths()); } else if (value instanceof QuestTaskLocation) { out.name(LOCATIONS).beginArray(); for (QuestTaskLocation.Location requirement : ((QuestTaskLocation) value).locations) { LOCATION_ADAPTER.write(out, requirement); } out.endArray(); } else if (value instanceof QuestTaskMob) { out.name(MOBS).beginArray(); for (QuestTaskMob.Mob requirement : ((QuestTaskMob) value).mobs) { MOB_ADAPTER.write(out, requirement); } out.endArray(); } else if (value instanceof QuestTaskReputation) { out.name(REPUTATION).beginArray(); for (QuestTaskReputation.ReputationSetting requirement : ((QuestTaskReputation) value).getSettings()) { REPUTATION_ADAPTER.write(out, requirement); } out.endArray(); if (value instanceof QuestTaskReputationKill) { out.name(KILLS).value(((QuestTaskReputationKill) value).getKills()); } } out.endObject(); }
@Override public void write(JsonWriter out, QuestSet value) throws IOException { out.beginObject(); out.name(NAME).value(value.getName()); out.name(DESCRIPTION).value(value.getDescription()); out.name(QUESTS).beginArray(); for (Quest quest : value.getQuests()) { QUEST_ADAPTER.write(out, quest); } out.endArray().endObject(); }
public void toJson(Object obj, Type type, JsonWriter jsonWriter) throws JsonIOException { TypeAdapter adapter = getAdapter(TypeToken.get(type)); boolean isLenient = jsonWriter.isLenient(); jsonWriter.setLenient(true); boolean isHtmlSafe = jsonWriter.isHtmlSafe(); jsonWriter.setHtmlSafe(this.htmlSafe); boolean serializeNulls = jsonWriter.getSerializeNulls(); jsonWriter.setSerializeNulls(this.serializeNulls); try { adapter.write(jsonWriter, obj); jsonWriter.setLenient(isLenient); jsonWriter.setHtmlSafe(isHtmlSafe); jsonWriter.setSerializeNulls(serializeNulls); } catch (Throwable e) { throw new JsonIOException(e); } catch (Throwable th) { jsonWriter.setLenient(isLenient); jsonWriter.setHtmlSafe(isHtmlSafe); jsonWriter.setSerializeNulls(serializeNulls); } }
public void write(JsonWriter out, Collection<E> collection) throws IOException { if (collection == null) { out.nullValue(); // TODO: better policy here? return; } out.beginArray(); for (E element : collection) { elementTypeAdapter.write(out, element); } out.endArray(); }
@Override public RequestBody toBody(T value) { Buffer buffer = new Buffer(); Writer writer = new OutputStreamWriter(buffer.outputStream(), Util.UTF_8); try { typeAdapter.toJson(writer, value); writer.flush(); } catch (IOException e) { throw new AssertionError(e); // Writing to Buffer does no I/O. } return RequestBody.create(MEDIA_TYPE, buffer.readByteString()); }
public void write(JsonWriter out, Map<K, V> value) throws IOException { if (value == null) { out.nullValue(); return; } out.beginObject(); for (Map.Entry<K, V> element : value.entrySet()) { out.name(String.valueOf(element.getKey())); valueAdapter.write(out, element.getValue()); } out.endObject(); }
public Collection<E> read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } Collection<E> collection = constructor.construct(); in.beginArray(); while (in.hasNext()) { E instance = elementTypeAdapter.read(in); collection.add(instance); } in.endArray(); return collection; }
public T fromBody(ResponseBody value, Request request) throws IOException { String string = value.string(); System.out.println("网络请求到的字符串:" + string); Reader reader = new InputStreamReader((new ByteArrayInputStream(string.getBytes(UTF8))), Util.UTF_8); try { T t = typeAdapter.fromJson(reader); System.out.println("转换的最终对象:" + t); String mimeType = value.contentType().toString(); parseCache(request, t, string, mimeType); return t; } finally { closeQuietly(reader); } }
@Override public QuestSet read(JsonReader in) throws IOException { String name = null, description = null; requirementMapping.clear(); optionMapping.clear(); List<Quest> quests = new ArrayList<Quest>(); in.beginObject(); while (in.hasNext()) { String next = in.nextName(); if (next.equalsIgnoreCase(NAME)) { name = in.nextString(); } else if (next.equalsIgnoreCase(DESCRIPTION)) { description = in.nextString(); } else if (next.equalsIgnoreCase(QUESTS)) { in.beginArray(); QUEST_ID = Quest.size(); while (in.hasNext()) { Quest quest = QUEST_ADAPTER.read(in); if (quest != null) { quests.add(quest); } } in.endArray(); } } in.endObject(); for (QuestSet set : Quest.getQuestSets()) { if (set.getName().equals(name)) { return removeQuests(quests); } } if (name != null && description != null) { QuestSet set = new QuestSet(name, description); Quest.getQuestSets().add(set); SaveHelper.add(SaveHelper.EditType.SET_CREATE); for (Quest quest : quests) { quest.setQuestSet(set); } for (Map.Entry<Quest, List<Integer>> entry : requirementMapping.entrySet()) { for (int i : entry.getValue()) entry.getKey().addRequirement(i); } for (Map.Entry<Quest, List<Integer>> entry : optionMapping.entrySet()) { for (int i : entry.getValue()) entry.getKey().addOptionLink(i); } return set; } return removeQuests(quests); }
@Override public Patch<Data> read(JsonReader in) throws IOException { final Set<String> receivedJsonProperties = new HashSet<>(); JsonReader watchingReader = new ObjectWatchingJsonReader(in) { @Override protected void onNextName(String foundName) { receivedJsonProperties.add(foundName); } }; Data data = _dataAdapter.read(watchingReader); List<Field> changedFields = new ArrayList<>(receivedJsonProperties.size()); for (Field field : data.getClass().getDeclaredFields()) { SerializedName nameSpecifier = field.getAnnotation(SerializedName.class); String jsonPropertyName = (nameSpecifier != null ? nameSpecifier.value() : field.getName()); if (receivedJsonProperties.contains(jsonPropertyName)) { changedFields.add(field); } } return new Patch<>(data, changedFields); }
@Override public Quest read(JsonReader in) throws IOException { int ID_OFFSET = Quest.size(); QUEST = new Quest(ID_OFFSET, "", "", 0, 0, false); List<Integer> requirement = new ArrayList<>(), options = new ArrayList<>(); in.beginObject(); while (in.hasNext()) { switch (in.nextName()) { case NAME: QUEST.setName(in.nextString()); break; case DESCRIPTION: QUEST.setDescription(in.nextString()); break; case X: ReflectionHelper.setPrivateValue(Quest.class, QUEST, in.nextInt(), X); break; case Y: ReflectionHelper.setPrivateValue(Quest.class, QUEST, in.nextInt(), Y); break; case TRIGGER_TASKS: QUEST.setTriggerTasks(in.nextInt()); break; case PARENT_REQUIREMENT: QUEST.setParentRequirementCount(in.nextInt()); break; case BIG_ICON: QUEST.setBigIcon(in.nextBoolean()); break; case ICON: QUEST.setIcon(MinecraftAdapter.ITEM_STACK.read(in)); break; case REQUIREMENTS: in.beginArray(); while (in.hasNext()) { requirement.add(in.nextInt() + QUEST_ID); } in.endArray(); break; case OPTIONS: in.beginArray(); while (in.hasNext()) { options.add(in.nextInt() + QUEST_ID); } in.endArray(); break; case REPEAT: QUEST.setRepeatInfo(REPEAT_INFO_ADAPTER.read(in)); break; case TRIGGER: QUEST.setTriggerType(TriggerType.valueOf(in.nextString())); break; case TASKS: in.beginArray(); while (in.hasNext()) { QuestTask task = TASK_ADAPTER.read(in); if (task != null) { QUEST.getTasks().add(task); } } in.endArray(); break; case REWARDS: ReflectionHelper.setPrivateValue( Quest.class, QUEST, readItemStackArray(in), REWARDS); break; case REWARDS_CHOICE: ReflectionHelper.setPrivateValue( Quest.class, QUEST, readItemStackArray(in), REWARDS_CHOICE); break; case REWARDS_REPUTATION: in.beginArray(); List<Quest.ReputationReward> reputationRewards = new ArrayList<>(); while (in.hasNext()) { Quest.ReputationReward reward = REPUTATION_REWARD_ADAPTER.read(in); if (reward != null) reputationRewards.add(reward); } QUEST.setReputationRewards(reputationRewards); in.endArray(); break; } } in.endObject(); if (!QUEST.getName().isEmpty()) { requirementMapping.put(QUEST, requirement); optionMapping.put(QUEST, options); return QUEST; } QuestLine.getActiveQuestLine().quests.remove(QUEST.getId()); return null; }
@Override public QuestTask read(JsonReader in) throws IOException { in.beginObject(); if (!in.nextName().equalsIgnoreCase(TYPE)) { throw new IOException("Tasks *MUST* start with the type"); } String task = in.nextString(); TaskType type = TaskType.valueOf(task); if (type == null) { throw new IOException("Invalid Task Type: " + task); } TASK = type.addTask(QUEST); while (in.hasNext()) { String name = in.nextName(); if (name.equalsIgnoreCase(DESCRIPTION)) { TASK.description = in.nextString(); } else if (name.equalsIgnoreCase(LONG_DESCRIPTION)) { TASK.setLongDescription(in.nextString()); } else if (TASK instanceof QuestTaskItems && name.equalsIgnoreCase(ITEMS)) { List<QuestTaskItems.ItemRequirement> list = new ArrayList<>(); in.beginArray(); while (in.hasNext()) { QuestTaskItems.ItemRequirement entry = ITEM_REQUIREMENT_ADAPTER.read(in); if (entry != null) list.add(entry); } in.endArray(); ((QuestTaskItems) TASK) .setItems(list.toArray(new QuestTaskItems.ItemRequirement[list.size()])); } else if (TASK instanceof QuestTaskDeath && name.equalsIgnoreCase(DEATHS)) { int death = in.nextInt(); ((QuestTaskDeath) TASK).setDeaths(death); } else if (TASK instanceof QuestTaskLocation && name.equalsIgnoreCase(LOCATIONS)) { List<QuestTaskLocation.Location> list = new ArrayList<QuestTaskLocation.Location>(); in.beginArray(); while (in.hasNext()) { QuestTaskLocation.Location entry = LOCATION_ADAPTER.read(in); if (entry != null) list.add(entry); } in.endArray(); ((QuestTaskLocation) TASK).locations = list.toArray(new QuestTaskLocation.Location[list.size()]); } else if (TASK instanceof QuestTaskMob && name.equalsIgnoreCase(MOBS)) { List<QuestTaskMob.Mob> list = new ArrayList<QuestTaskMob.Mob>(); in.beginArray(); while (in.hasNext()) { QuestTaskMob.Mob entry = MOB_ADAPTER.read(in); if (entry != null) list.add(entry); } in.endArray(); ((QuestTaskMob) TASK).mobs = list.toArray(new QuestTaskMob.Mob[list.size()]); } else if (TASK instanceof QuestTaskReputation && name.equalsIgnoreCase(REPUTATION)) { List<QuestTaskReputation.ReputationSetting> list = new ArrayList<QuestTaskReputation.ReputationSetting>(); in.beginArray(); while (in.hasNext()) { list.add(REPUTATION_ADAPTER.read(in)); } in.endArray(); ReflectionHelper.setPrivateValue( QuestTaskReputation.class, (QuestTaskReputation) TASK, list.toArray(new QuestTaskReputation.ReputationSetting[list.size()]), "settings"); } else if (name.equalsIgnoreCase(KILLS) && TASK instanceof QuestTaskReputationKill) { ((QuestTaskReputationKill) TASK).setKills(in.nextInt()); } } in.endObject(); type.addTaskData(QUEST); return null; }
@Test(expectedExceptions = NullPointerException.class) public void testPartialObjectStillThrows() throws IOException { TypeAdapter<ComposedObjects> adapter = parameterizedCtorFactory.create(gson, TypeToken.get(ComposedObjects.class)); assertNull(adapter.fromJson("{\"x\":{\"foo\":0,\"bar\":1}}")); }
public void testRenamedFields() throws IOException { TypeAdapter<RenamedFields> adapter = parameterizedCtorFactory.create(gson, TypeToken.get(RenamedFields.class)); assertEquals(new RenamedFields(0, 1), adapter.fromJson("{\"foo\":0,\"_bar\":1}")); assertEquals(adapter.toJson(new RenamedFields(0, 1)), "{\"foo\":0,\"_bar\":1}"); }
@Override public void write(JsonWriter out, T value) throws IOException { // Cannot determine what was annotated, and what was in schedules delegateAdapter.write(out, value); }
@Override public T read(JsonReader in) throws IOException { JsonObject el = Streams.parse(in).getAsJsonObject(); // Strip existing json schedules JsonObject directSchedules = el.has(SCHEDULES_FIELD_NAME) ? el.remove(SCHEDULES_FIELD_NAME).getAsJsonObject() : new JsonObject(); // Strip off @schedule annotations to update schedules attribute // Load annotated schedules JsonObject annotatedSchedules = new JsonObject(); // TODO: make this recursive to have nested schedules with dot notation for (Map.Entry<String, JsonElement> entry : el.entrySet()) { JsonElement entryEl = entry.getValue(); if (entryEl.isJsonObject()) { JsonObject subConfig = entryEl.getAsJsonObject(); if (subConfig.has(SCHEDULE)) { JsonElement scheduleConfig = subConfig.remove(SCHEDULE); annotatedSchedules.add(entry.getKey(), scheduleConfig); } } } T result = delegateAdapter.read(new JsonTreeReader(el)); // If there is a 'schedules' field, inject schedules Field schedulesField = AnnotationUtil.getField(SCHEDULES_FIELD_NAME, result.getClass()); if (schedulesField != null) { ///// Default schedules for every schedulable top level object JsonObject defaultSchedules = new JsonObject(); List<Field> fields = new ArrayList<Field>(); for (Field field : AnnotationUtil.getAllFields(fields, result.getClass())) { DefaultSchedule defaultSchedule = field.getAnnotation(DefaultSchedule.class); if (defaultSchedule == null) { boolean currentAccessibility = field.isAccessible(); try { field.setAccessible(true); Object fieldValue = field.get(result); if (fieldValue != null) { Class<?> fieldRuntimeClass = field.get(result).getClass(); defaultSchedule = fieldRuntimeClass.getAnnotation(DefaultSchedule.class); } } catch (IllegalArgumentException e) { Log.e(LogUtil.TAG, "Bad access of configurable fields!!", e); } catch (IllegalAccessException e) { Log.e(LogUtil.TAG, "Bad access of configurable fields!!", e); } finally { field.setAccessible(currentAccessibility); } } if (defaultSchedule != null) { defaultSchedules.add( field.getName(), gson.toJsonTree(defaultSchedule, DefaultSchedule.class)); } } JsonObject schedulesJson = directSchedules; JsonUtils.deepCopyOnto( defaultSchedules, schedulesJson, false); // Copy in default schedules, but do not replace JsonUtils.deepCopyOnto( annotatedSchedules, schedulesJson, true); // Override with annotations // For each schedule find default schedule, fill in remainder Map<String, Schedule> schedules = gson.fromJson(schedulesJson, new TypeToken<Map<String, Schedule>>() {}.getType()); boolean currentAccessibility = schedulesField.isAccessible(); try { schedulesField.setAccessible(true); schedulesField.set(result, schedules); } catch (IllegalArgumentException e) { Log.e(LogUtil.TAG, "Bad access of configurable fields!!", e); } catch (IllegalAccessException e) { Log.e(LogUtil.TAG, "Bad access of configurable fields!!", e); } finally { schedulesField.setAccessible(currentAccessibility); } } return result; }
public void testEmptyObjectIsNull() throws IOException { TypeAdapter<ComposedObjects> adapter = parameterizedCtorFactory.create(gson, TypeToken.get(ComposedObjects.class)); assertNull(adapter.fromJson("{}")); }