Skip to content

Commit

Permalink
Merge pull request #508 from segmentio/support-primitive-arrays
Browse files Browse the repository at this point in the history
Support primitive Arrays
  • Loading branch information
f2prateek authored Feb 21, 2017
2 parents 7a32cc1 + 74291fc commit e26b0d4
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 5 deletions.
15 changes: 10 additions & 5 deletions analytics/src/main/java/com/segment/analytics/Cartographer.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
Expand Down Expand Up @@ -190,11 +191,15 @@ private static void listToWriter(List<?> list, JsonWriter writer) throws IOExcep
writer.endArray();
}

/** Print the json representation of an array to the given writer. */
private static void arrayToWriter(Object[] array, JsonWriter writer) throws IOException {
/**
* Print the json representation of an array to the given writer. Primitive arrays cannot be cast
* to Object[], to this method accepts the raw object and uses {@link Array#getLength(Object)} and
* {@link Array#get(Object, int)} to read the array.
*/
private static void arrayToWriter(Object array, JsonWriter writer) throws IOException {
writer.beginArray();
for (Object value : array) {
writeValue(value, writer);
for (int i = 0, size = Array.getLength(array); i < size; i++) {
writeValue(Array.get(array, i), writer);
}
writer.endArray();
}
Expand All @@ -216,7 +221,7 @@ private static void writeValue(Object value, JsonWriter writer) throws IOExcepti
} else if (value instanceof Map) {
mapToWriter((Map) value, writer);
} else if (value.getClass().isArray()) {
arrayToWriter((Object[]) value, writer);
arrayToWriter(value, writer);
} else {
writer.value(String.valueOf(value));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,17 @@ public void encodesArraysWithArrays() throws IOException {
+ "}");
}

@Test
public void encodesPrimitiveArrays() throws IOException {
// Exercise a bug where primitive arrays would throw an IOException.
// https://github.com/segmentio/analytics-android/issues/507
Map<String, Object> map =
ImmutableMap.<String, Object>builder().put("a", new int[] {1, 2}).build();

assertThat(cartographer.toJson(map))
.isEqualTo("{\n" + " \"a\": [\n" + " 1,\n" + " 2\n" + " ]\n" + "}");
}

@Test
public void decodesArraysWithArraysAsLists() throws IOException {
String json =
Expand Down

0 comments on commit e26b0d4

Please sign in to comment.