com.squareup.moshi.JsonWriter Java Examples

The following examples show how to use com.squareup.moshi.JsonWriter. 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: WrappedJsonAdapter.java    From moshi-lazy-adapters with Apache License 2.0 6 votes vote down vote up
/**
 * Recursively writes the respective roots forming a json object that resembles the {@code path}
 * wrapping the type of the {@code adapter}.
 */
private static <T> void toJson(JsonAdapter<T> adapter, JsonWriter writer, T value,
    String[] path, int index) throws IOException {
  if (value != null || writer.getSerializeNulls()) {
    if (index == path.length) {
      adapter.toJson(writer, value);
    } else {
      writer.beginObject();
      writer.name(path[index]);
      toJson(adapter, writer, value, path, ++index);
      writer.endObject();
    }
  } else {
    // If we don't propagate the null value the writer will throw.
    writer.nullValue();
  }
}
 
Example #2
Source File: BoundParameterQuery.java    From influxdb-java with MIT License 6 votes vote down vote up
private String createJsonObject(final Map<String, Object> parameterMap) throws IOException {
  Buffer b = new Buffer();
  JsonWriter writer = JsonWriter.of(b);
  writer.beginObject();
  for (Entry<String, Object> pair : parameterMap.entrySet()) {
    String name = pair.getKey();
    Object value = pair.getValue();
    if (value instanceof Number) {
      Number number = (Number) value;
      writer.name(name).value(number);
    } else if (value instanceof String) {
      writer.name(name).value((String) value);
    } else if (value instanceof Boolean) {
      writer.name(name).value((Boolean) value);
    } else {
      writer.name(name).value(String.valueOf(value));
    }
  }
  writer.endObject();
  return b.readString(Charset.forName("utf-8"));
}
 
Example #3
Source File: PolymorphicJsonAdapterFactory.java    From moshi with Apache License 2.0 6 votes vote down vote up
@Override public void toJson(JsonWriter writer, Object value) throws IOException {
  Class<?> type = value.getClass();
  int labelIndex = subtypes.indexOf(type);
  if (labelIndex == -1) {
    throw new IllegalArgumentException("Expected one of "
        + subtypes
        + " but found "
        + value
        + ", a "
        + value.getClass()
        + ". Register this subtype.");
  }
  JsonAdapter<Object> adapter = jsonAdapters.get(labelIndex);
  writer.beginObject();
  writer.name(labelKey).value(labels.get(labelIndex));
  int flattenToken = writer.beginFlatten();
  adapter.toJson(writer, value);
  writer.endFlatten(flattenToken);
  writer.endObject();
}
 
Example #4
Source File: AppDumperPlugin.java    From droidconat-2016 with Apache License 2.0 6 votes vote down vote up
private void displayCurrentSessionData(PrintStream writer) {
    Activity activity = activityProvider.getCurrentActivity();
    if (activity instanceof SessionDetailsActivity) {
        try {
            // Use reflection to access private "session" field
            Field field = SessionDetailsActivity.class.getDeclaredField("session");
            field.setAccessible(true);
            Session session = (Session) field.get(activity);

            // Convert sessions to a human readable json
            Buffer buffer = new Buffer();
            JsonWriter jsonWriter = JsonWriter.of(buffer);
            jsonWriter.setIndent("  ");
            moshi.adapter(Session.class).toJson(jsonWriter, session);
            String sessionJson = buffer.readUtf8();

            writer.println(sessionJson);
        } catch (Exception e) {
            writer.println(e.getMessage());
        }
    } else {
        writer.println("SessionDetailsActivity not visible");
    }
}
 
Example #5
Source File: HasMany.java    From moshi-jsonapi with MIT License 6 votes vote down vote up
@Override
public void toJson(JsonWriter writer, HasMany<T> value) throws IOException {
    writer.beginObject();
    writer.name("data");
    if (!value.hasData) {
        writeNull(writer, true);
    } else {
        writer.beginArray();
        for (ResourceIdentifier resource : value.linkedResources) {
            resourceIdentifierJsonAdapter.toJson(writer, resource);
        }
        writer.endArray();
    }
    writeNullable(writer, jsonBufferJsonAdapter, "meta", value.getMeta());
    writeNullable(writer, jsonBufferJsonAdapter, "links", value.getLinks());
    writer.endObject();
}
 
Example #6
Source File: SerializeOnlyNonEmptyJsonAdapter.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
@Override public void toJson(JsonWriter writer, T value) throws IOException {
  if (isNotEmpty(value)) {
    delegate.toJson(writer, value);
  } else {
    // We'll need to consume this property otherwise we'll get an IllegalArgumentException.
    delegate.toJson(writer, null);
  }
}
 
Example #7
Source File: ResourceIdentifier.java    From moshi-jsonapi with MIT License 5 votes vote down vote up
@Override
public void toJson(JsonWriter writer, ResourceIdentifier value) throws IOException {
    writer.beginObject();
    writer.name("type").value(value.getType());
    writer.name("id").value(value.getId());
    writeNullable(writer, jsonBufferJsonAdapter, "meta", value.getMeta());
    writer.endObject();
}
 
Example #8
Source File: NullSafeJsonAdapter.java    From moshi with Apache License 2.0 5 votes vote down vote up
@Override public void toJson(JsonWriter writer, @Nullable T value) throws IOException {
  if (value == null) {
    writer.nullValue();
  } else {
    delegate.toJson(writer, value);
  }
}
 
Example #9
Source File: NonNullJsonAdapter.java    From moshi with Apache License 2.0 5 votes vote down vote up
@Override
public void toJson(JsonWriter writer, @Nullable T value) throws IOException {
  if (value == null) {
    throw new JsonDataException("Unexpected null at " + writer.getPath());
  } else {
    delegate.toJson(writer, value);
  }
}
 
Example #10
Source File: Rfc3339DateJsonAdapter.java    From moshi with Apache License 2.0 5 votes vote down vote up
@Override public synchronized void toJson(JsonWriter writer, Date value) throws IOException {
  if (value == null) {
    writer.nullValue();
  } else {
    String string = Iso8601Utils.format(value);
    writer.value(string);
  }
}
 
Example #11
Source File: EnumJsonAdapter.java    From moshi with Apache License 2.0 5 votes vote down vote up
@Override public void toJson(JsonWriter writer, T value) throws IOException {
  if (value == null) {
    throw new NullPointerException(
        "value was null! Wrap in .nullSafe() to write nullable values.");
  }
  writer.value(nameStrings[value.ordinal()]);
}
 
Example #12
Source File: CustomAdapterFactory.java    From moshi with Apache License 2.0 5 votes vote down vote up
@Override public void toJson(JsonWriter writer, SortedSet<T> set) throws IOException {
  writer.beginArray();
  for (T element : set) {
    elementAdapter.toJson(writer, element);
  }
  writer.endArray();
}
 
Example #13
Source File: ModelListAdapterTest.java    From android with Apache License 2.0 5 votes vote down vote up
@Test public void testModelListAdapter() throws IOException {
  Buffer buffer = new Buffer();
  JsonWriter jsonWriter = JsonWriter.of(buffer);
  JsonAdapter<List<Nation>> adapter =
      moshi.adapter(Types.newParameterizedType(List.class, Nation.class));
  Nation nation = Nation.create(1, 1, "foo", "bar", "baz");
  List<Nation> nations = Collections.singletonList(nation);
  adapter.toJson(jsonWriter, nations);
  String json = buffer.readUtf8();
  buffer = new Buffer().writeUtf8(json);
  JsonReader jsonReader = JsonReader.of(buffer);
  assertThat(adapter.fromJson(jsonReader)).isEqualTo(nations);
}
 
Example #14
Source File: ModelListAdapter.java    From android with Apache License 2.0 5 votes vote down vote up
@Override public void toJson(JsonWriter writer, List<T> value) throws IOException {
  writer.beginObject();
  writer.name(type.getSimpleName().toLowerCase());
  writer.beginArray();
  JsonAdapter<T> adapter = moshi.adapter(type);
  for (T n : value) {
    adapter.toJson(writer, n);
  }
  writer.endArray();
  writer.endObject();
}
 
Example #15
Source File: TransientJsonAdapter.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
@Override public void toJson(JsonWriter writer, T value) throws IOException {
  if (serialize) {
    delegate.toJson(writer, value);
  } else {
    // We'll need to consume this property otherwise we'll get an IllegalArgumentException.
    delegate.toJson(writer, null);
  }
}
 
Example #16
Source File: MoshiHelper.java    From moshi-jsonapi with MIT License 5 votes vote down vote up
public static <T> void writeNullableValue(JsonWriter writer, JsonAdapter<T> adapter, T value, boolean enforced) throws IOException {
    if (value != null) {
        adapter.toJson(writer, value);
    } else {
        writeNull(writer, enforced);
    }
}
 
Example #17
Source File: MoshiHelper.java    From moshi-jsonapi with MIT License 5 votes vote down vote up
public static void writeNull(JsonWriter writer, boolean enforced) throws IOException {
    if (enforced) {
        boolean serializeFlag = writer.getSerializeNulls();
        try {
            writer.setSerializeNulls(true);
            writer.nullValue();
        } finally {
            writer.setSerializeNulls(serializeFlag);
        }
    } else {
        writer.nullValue();
    }
}
 
Example #18
Source File: HasOne.java    From moshi-jsonapi with MIT License 5 votes vote down vote up
@Override
public void toJson(JsonWriter writer, HasOne<T> value) throws IOException {
    writer.beginObject();
    writeNullable(writer, resourceIdentifierJsonAdapter, "data", value.linkedResource, true);
    writeNullable(writer, jsonBufferJsonAdapter, "meta", value.getMeta());
    writeNullable(writer, jsonBufferJsonAdapter, "links", value.getLinks());
    writer.endObject();
}
 
Example #19
Source File: SerializeNullsJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
@Test public void maintainsPreviousSerializationValue() throws Exception {
  JsonAdapter<Data1> adapter = moshi.adapter(Data1.class);
  Data1 data1 = new Data1();

  JsonWriter writer1 = JsonWriter.of(new Buffer());
  writer1.setSerializeNulls(true);
  adapter.toJson(writer1, data1);
  assertThat(writer1.getSerializeNulls()).isTrue();

  JsonWriter writer2 = JsonWriter.of(new Buffer());
  writer2.setSerializeNulls(false);
  adapter.toJson(writer2, data1);
  assertThat(writer2.getSerializeNulls()).isFalse();
}
 
Example #20
Source File: Error.java    From moshi-jsonapi with MIT License 5 votes vote down vote up
@Override
public void toJson(JsonWriter writer, Error value) throws IOException {
    writer.beginObject();
    writer.name("id").value(value.getId());
    writer.name("status").value(value.getStatus());
    writer.name("code").value(value.getCode());
    writer.name("title").value(value.getTitle());
    writer.name("detail").value(value.getDetail());
    writeNullable(writer, jsonBufferJsonAdapter, "source", value.getSource());
    writeNullable(writer, jsonBufferJsonAdapter, "meta", value.getMeta());
    writeNullable(writer, jsonBufferJsonAdapter, "links", value.getLinks());
    writer.endObject();
}
 
Example #21
Source File: FallbackEnum.java    From moshi with Apache License 2.0 4 votes vote down vote up
@Override public void toJson(JsonWriter writer, T value) throws IOException {
  writer.value(nameStrings[value.ordinal()]);
}
 
Example #22
Source File: MoshiHelper.java    From moshi-jsonapi with MIT License 4 votes vote down vote up
public static void dump(JsonReader reader, JsonWriter writer) throws IOException {
    int nested = 0;
    boolean nullFlag = writer.getSerializeNulls();
    writer.setSerializeNulls(true);
    try {
        while (reader.peek() != JsonReader.Token.END_DOCUMENT) {
            switch (reader.peek()) {
                case BEGIN_ARRAY:
                    nested++;
                    reader.beginArray();
                    writer.beginArray();
                    break;
                case END_ARRAY:
                    reader.endArray();
                    writer.endArray();
                    if (0 == --nested) return;
                    break;
                case BEGIN_OBJECT:
                    nested++;
                    reader.beginObject();
                    writer.beginObject();
                    break;
                case END_OBJECT:
                    reader.endObject();
                    writer.endObject();
                    if (0 == --nested) return;
                    break;
                case NAME:
                    writer.name(reader.nextName());
                    break;
                case NUMBER:
                    Double doubleValue = reader.nextDouble();
                    if (Math.floor(doubleValue) == doubleValue) {
                        writer.value(doubleValue.longValue());
                    } else {
                        writer.value(doubleValue);
                    }
                    break;
                case BOOLEAN:
                    writer.value(reader.nextBoolean());
                    break;
                case STRING:
                    writer.value(reader.nextString());
                    break;
                case NULL:
                    reader.nextNull();
                    writer.nullValue();
                    break;
            }
        }
    } finally {
        writer.setSerializeNulls(nullFlag);
    }
}
 
Example #23
Source File: MoshiHelper.java    From moshi-jsonapi with MIT License 4 votes vote down vote up
public static <T> void writeNullable(JsonWriter writer, JsonAdapter<T> valueAdapter, String name, T value) throws IOException {
    writeNullable(writer, valueAdapter, name, value, false);
}
 
Example #24
Source File: MoshiHelper.java    From moshi-jsonapi with MIT License 4 votes vote down vote up
public static <T> void writeNullable(JsonWriter writer, JsonAdapter<T> valueAdapter, String name, T value, boolean enforced) throws IOException {
    writer.name(name);
    writeNullableValue(writer, valueAdapter, value, enforced);
}
 
Example #25
Source File: ByteStrings.java    From moshi with Apache License 2.0 4 votes vote down vote up
@Override public void toJson(JsonWriter writer, ByteString value) throws IOException {
  String string = value.base64();
  writer.value(string);
}
 
Example #26
Source File: Unwrap.java    From moshi with Apache License 2.0 4 votes vote down vote up
@Override public void toJson(JsonWriter writer, Object value) throws IOException {
  delegate.toJson(writer, new Envelope<>(value));
}
 
Example #27
Source File: DefaultOnDataMismatchAdapter.java    From moshi with Apache License 2.0 4 votes vote down vote up
@Override public void toJson(JsonWriter writer, T value) throws IOException {
  delegate.toJson(writer, value);
}
 
Example #28
Source File: MultipleFormats.java    From moshi with Apache License 2.0 4 votes vote down vote up
@ToJson void toJson(JsonWriter writer, Card value,
    @CardString JsonAdapter<Card> stringAdapter) throws IOException {
  stringAdapter.toJson(writer, value);
}
 
Example #29
Source File: FallbackEnumJsonAdapter.java    From moshi-lazy-adapters with Apache License 2.0 4 votes vote down vote up
@Override public void toJson(JsonWriter writer, T value) throws IOException {
  writer.value(nameStrings[value.ordinal()]);
}
 
Example #30
Source File: MoshiConverterFactoryTest.java    From jus with Apache License 2.0 4 votes vote down vote up
@ToJson
public void write(JsonWriter jsonWriter, AnInterface anInterface) throws IOException {
    jsonWriter.beginObject();
    jsonWriter.name("name").value(anInterface.getName());
    jsonWriter.endObject();
}