Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Perform minor code clean-up #2544

Merged
merged 5 commits into from
Nov 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,13 @@ public void onCreate(Bundle icicle) {
Cart cart = buildCart();
StringBuilder sb = new StringBuilder();
sb.append("Gson.toJson() example: \n");
sb.append(" Cart Object: ").append(cart).append("\n");
sb.append(" Cart JSON: ").append(gson.toJson(cart)).append("\n");
sb.append(" Cart Object: ").append(cart).append('\n');
eamonnmcmanus marked this conversation as resolved.
Show resolved Hide resolved
sb.append(" Cart JSON: ").append(gson.toJson(cart)).append('\n');
sb.append("\n\nGson.fromJson() example: \n");
String json = "{buyer:'Happy Camper',creditCard:'4111-1111-1111-1111',"
+ "lineItems:[{name:'nails',priceInMicros:100000,quantity:100,currencyCode:'USD'}]}";
sb.append("Cart JSON: ").append(json).append("\n");
sb.append("Cart Object: ").append(gson.fromJson(json, Cart.class)).append("\n");
sb.append("Cart JSON: ").append(json).append('\n');
sb.append("Cart Object: ").append(gson.fromJson(json, Cart.class)).append('\n');
tv.setText(sb.toString());
tv.invalidate();
}
Expand Down
23 changes: 11 additions & 12 deletions gson/src/main/java/com/google/gson/Gson.java
Original file line number Diff line number Diff line change
Expand Up @@ -216,9 +216,9 @@ public final class Gson {
* following settings:
*
* <ul>
* <li>The JSON generated by <code>toJson</code> methods is in compact representation. This
* means that all the unneeded white-space is removed. You can change this behavior with
* {@link GsonBuilder#setPrettyPrinting()}.
* <li>The JSON generated by {@code toJson} methods is in compact representation. This means
* that all the unneeded white-space is removed. You can change this behavior with {@link
* GsonBuilder#setPrettyPrinting()}.
* <li>When the JSON generated contains more than one line, the kind of newline and indent to
* use can be configured with {@link GsonBuilder#setFormattingStyle(FormattingStyle)}.
* <li>The generated JSON omits all the fields that are null. Note that nulls in arrays are kept
Expand All @@ -240,13 +240,12 @@ public final class Gson {
* <li>By default, Gson ignores the {@link com.google.gson.annotations.Since} annotation. You
* can enable Gson to use this annotation through {@link GsonBuilder#setVersion(double)}.
* <li>The default field naming policy for the output JSON is same as in Java. So, a Java class
* field <code>versionNumber</code> will be output as <code>&quot;versionNumber&quot;</code>
* in JSON. The same rules are applied for mapping incoming JSON to the Java classes. You
* can change this policy through {@link
* GsonBuilder#setFieldNamingPolicy(FieldNamingPolicy)}.
* <li>By default, Gson excludes <code>transient</code> or <code>static</code> fields from
* consideration for serialization and deserialization. You can change this behavior through
* {@link GsonBuilder#excludeFieldsWithModifiers(int...)}.
* field {@code versionNumber} will be output as {@code "versionNumber"} in JSON. The same
* rules are applied for mapping incoming JSON to the Java classes. You can change this
* policy through {@link GsonBuilder#setFieldNamingPolicy(FieldNamingPolicy)}.
* <li>By default, Gson excludes {@code transient} or {@code static} fields from consideration
* for serialization and deserialization. You can change this behavior through {@link
* GsonBuilder#excludeFieldsWithModifiers(int...)}.
* <li>No explicit strictness is set. You can change this by calling {@link
* GsonBuilder#setStrictness(Strictness)}.
* </ul>
Expand Down Expand Up @@ -665,8 +664,8 @@ public <T> TypeAdapter<T> getAdapter(TypeToken<T> type) {
* is an example:
*
* <p>Let's say we want to write a type adapter that counts the number of objects being read from
* or written to JSON. We can achieve this by writing a type adapter factory that uses the <code>
* getDelegateAdapter</code> method:
* or written to JSON. We can achieve this by writing a type adapter factory that uses the {@code
* getDelegateAdapter} method:
*
* <pre>{@code
* class StatsTypeAdapterFactory implements TypeAdapterFactory {
Expand Down
38 changes: 20 additions & 18 deletions gson/src/main/java/com/google/gson/GsonBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -227,8 +227,8 @@ public GsonBuilder excludeFieldsWithoutExposeAnnotation() {
}

/**
* Configure Gson to serialize null fields. By default, Gson omits all fields that are null during
* serialization.
* Configures Gson to serialize null fields. By default, Gson omits all fields that are null
* during serialization.
*
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
* @since 1.2
Expand All @@ -240,10 +240,11 @@ public GsonBuilder serializeNulls() {
}

/**
* Enabling this feature will only change the serialized form if the map key is a complex type
* (i.e. non-primitive) in its <strong>serialized</strong> JSON form. The default implementation
* of map serialization uses {@code toString()} on the key; however, when this is called then one
* of the following cases apply:
* Configures Gson to serialize {@code Map} objects with complex keys as JSON arrays. Enabling
* this feature will only change the serialized form if the map key is a complex type (i.e.
* non-primitive) in its <strong>serialized</strong> JSON form. The default implementation of map
* serialization uses {@code toString()} on the key; however, when this is called then one of the
* following cases apply:
*
* <p><b>Maps as JSON objects</b>
*
Expand Down Expand Up @@ -622,23 +623,24 @@ private static int checkDateFormatStyle(int style) {
}

/**
* Configures Gson to serialize {@code Date} objects according to the style value provided. You
* can call this method or {@link #setDateFormat(String)} multiple times, but only the last
* invocation will be used to decide the serialization format.
* Configures Gson to serialize {@code Date} objects according to the date style value provided.
* You can call this method or {@link #setDateFormat(String)} multiple times, but only the last
* invocation will be used to decide the serialization format. This methods leaves the current
* 'time style' unchanged.
*
* <p>Note that this style value should be one of the predefined constants in the {@code
* DateFormat} class. See the documentation in {@link java.text.DateFormat} for more information
* on the valid style constants.
* <p>Note that this style value should be one of the predefined constants in the {@link
* DateFormat} class, such as {@link DateFormat#MEDIUM}. See the documentation of the {@link
* DateFormat} class for more information on the valid style constants.
*
* @param style the predefined date style that date objects will be serialized/deserialized
* @param dateStyle the predefined date style that date objects will be serialized/deserialized
* to/from
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
* @throws IllegalArgumentException if the style is invalid
* @since 1.2
*/
@CanIgnoreReturnValue
public GsonBuilder setDateFormat(int style) {
this.dateStyle = checkDateFormatStyle(style);
public GsonBuilder setDateFormat(int dateStyle) {
this.dateStyle = checkDateFormatStyle(dateStyle);
this.datePattern = null;
return this;
}
Expand All @@ -648,9 +650,9 @@ public GsonBuilder setDateFormat(int style) {
* can call this method or {@link #setDateFormat(String)} multiple times, but only the last
* invocation will be used to decide the serialization format.
*
* <p>Note that this style value should be one of the predefined constants in the {@code
* DateFormat} class. See the documentation in {@link java.text.DateFormat} for more information
* on the valid style constants.
* <p>Note that this style value should be one of the predefined constants in the {@link
* DateFormat} class, such as {@link DateFormat#MEDIUM}. See the documentation of the {@link
* DateFormat} class for more information on the valid style constants.
*
* @param dateStyle the predefined date style that date objects will be serialized/deserialized
* to/from
Expand Down
20 changes: 20 additions & 0 deletions gson/src/main/java/com/google/gson/ReflectionAccessFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,11 @@ public FilterResult check(Class<?> rawClass) {
? FilterResult.BLOCK_INACCESSIBLE
: FilterResult.INDECISIVE;
}

@Override
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you mention these in the PR description?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Have included it now; sorry that I added this in a follow-up commit and not in the original changes of this PR. I just remembered that this change was something I wanted to do for quite some time because the default toString() during debugging makes it difficult to understand which filter is used.

public String toString() {
return "ReflectionAccessFilter#BLOCK_INACCESSIBLE_JAVA";
}
};

/**
Expand All @@ -143,6 +148,11 @@ public FilterResult check(Class<?> rawClass) {
? FilterResult.BLOCK_ALL
: FilterResult.INDECISIVE;
}

@Override
public String toString() {
return "ReflectionAccessFilter#BLOCK_ALL_JAVA";
}
};

/**
Expand All @@ -169,6 +179,11 @@ public FilterResult check(Class<?> rawClass) {
? FilterResult.BLOCK_ALL
: FilterResult.INDECISIVE;
}

@Override
public String toString() {
return "ReflectionAccessFilter#BLOCK_ALL_ANDROID";
}
};

/**
Expand Down Expand Up @@ -196,6 +211,11 @@ public FilterResult check(Class<?> rawClass) {
? FilterResult.BLOCK_ALL
: FilterResult.INDECISIVE;
}

@Override
public String toString() {
return "ReflectionAccessFilter#BLOCK_ALL_PLATFORM";
}
};

/**
Expand Down
10 changes: 5 additions & 5 deletions gson/src/main/java/com/google/gson/TypeAdapter.java
Original file line number Diff line number Diff line change
Expand Up @@ -68,11 +68,11 @@
* #write(JsonWriter,Object) write()} must write exactly one value. For primitive types this is
* means readers should make exactly one call to {@code nextBoolean()}, {@code nextDouble()}, {@code
* nextInt()}, {@code nextLong()}, {@code nextString()} or {@code nextNull()}. Writers should make
* exactly one call to one of <code>value()</code> or <code>nullValue()</code>. For arrays, type
* adapters should start with a call to {@code beginArray()}, convert all elements, and finish with
* a call to {@code endArray()}. For objects, they should start with {@code beginObject()}, convert
* the object, and finish with {@code endObject()}. Failing to convert a value or converting too
* many values may cause the application to crash.
* exactly one call to one of {@code value()} or {@code nullValue()}. For arrays, type adapters
* should start with a call to {@code beginArray()}, convert all elements, and finish with a call to
* {@code endArray()}. For objects, they should start with {@code beginObject()}, convert the
* object, and finish with {@code endObject()}. Failing to convert a value or converting too many
* values may cause the application to crash.
*
* <p>Type adapters should be prepared to read null from the stream and write it to the stream.
* Alternatively, they should use {@link #nullSafe()} method while registering the type adapter with
Expand Down
12 changes: 6 additions & 6 deletions gson/src/main/java/com/google/gson/reflect/TypeToken.java
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ public boolean isAssignableFrom(Type from) {
return rawType.isAssignableFrom($Gson$Types.getRawType(from))
&& isAssignableFrom(from, (GenericArrayType) type);
} else {
throw buildUnexpectedTypeError(
throw buildUnsupportedTypeException(
type, Class.class, ParameterizedType.class, GenericArrayType.class);
}
}
Expand Down Expand Up @@ -309,21 +309,21 @@ private static boolean typeEquals(
return false;
}

private static AssertionError buildUnexpectedTypeError(Type token, Class<?>... expected) {
private static IllegalArgumentException buildUnsupportedTypeException(
Type token, Class<?>... expected) {

// Build exception message
StringBuilder exceptionMessage = new StringBuilder("Unexpected type. Expected one of: ");
StringBuilder exceptionMessage = new StringBuilder("Unsupported type, expected one of: ");
for (Class<?> clazz : expected) {
exceptionMessage.append(clazz.getName()).append(", ");
}
exceptionMessage
.append("but got: ")
.append(token.getClass().getName())
.append(", for type token: ")
.append(token.toString())
.append('.');
.append(token.toString());

return new AssertionError(exceptionMessage.toString());
return new IllegalArgumentException(exceptionMessage.toString());
}

/**
Expand Down
11 changes: 5 additions & 6 deletions gson/src/main/java/com/google/gson/stream/JsonReader.java
Original file line number Diff line number Diff line change
Expand Up @@ -1056,7 +1056,6 @@ public long nextLong() throws IOException {
* consumes the closing quote, but does not include it in the returned string.
*
* @param quote either ' or ".
* @throws NumberFormatException if any unicode escape sequences are malformed.
eamonnmcmanus marked this conversation as resolved.
Show resolved Hide resolved
*/
private String nextQuotedValue(char quote) throws IOException {
// Like nextNonWhitespace, this uses locals 'p' and 'l' to save inner-loop field access.
Expand Down Expand Up @@ -1527,7 +1526,7 @@ private int nextNonWhitespace(boolean throwOnEof) throws IOException {
}
}

private void checkLenient() throws IOException {
private void checkLenient() throws MalformedJsonException {
if (strictness != Strictness.LENIENT) {
throw syntaxError(
"Use JsonReader.setStrictness(Strictness.LENIENT) to accept malformed JSON");
Expand Down Expand Up @@ -1655,7 +1654,7 @@ public String getPath() {
* backslash. The backslash '\' should have already been read. This supports both Unicode escapes
* "u000A" and two-character escapes "\n".
*
* @throws MalformedJsonException if any Unicode escape sequences are malformed.
* @throws MalformedJsonException if the escape sequence is malformed
*/
@SuppressWarnings("fallthrough")
private char readEscapeCharacter() throws IOException {
Expand Down Expand Up @@ -1725,10 +1724,10 @@ private char readEscapeCharacter() throws IOException {
}

/**
* Throws a new IO exception with the given message and a context snippet with this reader's
* content.
* Throws a new {@link MalformedJsonException} with the given message and information about the
* current location.
*/
private IOException syntaxError(String message) throws IOException {
private MalformedJsonException syntaxError(String message) throws MalformedJsonException {
throw new MalformedJsonException(
message + locationString() + "\nSee " + TroubleshootingGuide.createUrl("malformed-json"));
}
Expand Down
15 changes: 6 additions & 9 deletions gson/src/main/java/com/google/gson/stream/JsonScope.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,28 +24,25 @@
*/
final class JsonScope {

/** An array with no elements requires no separators or newlines before it is closed. */
/** An array with no elements requires no separator before the next element. */
static final int EMPTY_ARRAY = 1;

/** An array with at least one value requires a comma and newline before the next element. */
/** An array with at least one value requires a separator before the next element. */
static final int NONEMPTY_ARRAY = 2;

/** An object with no name/value pairs requires no separators or newlines before it is closed. */
/** An object with no name/value pairs requires no separator before the next element. */
static final int EMPTY_OBJECT = 3;

/** An object whose most recent element is a key. The next element must be a value. */
static final int DANGLING_NAME = 4;

/**
* An object with at least one name/value pair requires a comma and newline before the next
* element.
*/
/** An object with at least one name/value pair requires a separator before the next element. */
static final int NONEMPTY_OBJECT = 5;

/** No object or array has been started. */
/** No top-level value has been started yet. */
static final int EMPTY_DOCUMENT = 6;

/** A document with at an array or object. */
/** A top-level value has already been started. */
static final int NONEMPTY_DOCUMENT = 7;

/** A document that's been closed and cannot be accessed. */
Expand Down
6 changes: 3 additions & 3 deletions gson/src/main/java/com/google/gson/stream/JsonWriter.java
Original file line number Diff line number Diff line change
Expand Up @@ -356,9 +356,9 @@ public final Strictness getStrictness() {

/**
* Configures this writer to emit JSON that's safe for direct inclusion in HTML and XML documents.
* This escapes the HTML characters {@code <}, {@code >}, {@code &} and {@code =} before writing
* them to the stream. Without this setting, your XML/HTML encoder should replace these characters
* with the corresponding escape sequences.
* This escapes the HTML characters {@code <}, {@code >}, {@code &}, {@code =} and {@code '}
* before writing them to the stream. Without this setting, your XML/HTML encoder should replace
* these characters with the corresponding escape sequences.
*/
public final void setHtmlSafe(boolean htmlSafe) {
this.htmlSafe = htmlSafe;
Expand Down
2 changes: 1 addition & 1 deletion gson/src/test/java/com/google/gson/JsonPrimitiveTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,7 @@ public void testEqualsAcrossTypes() {
new JsonPrimitive(new BigInteger("0")), new JsonPrimitive(0));
MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(0), new JsonPrimitive(0L));
MoreAsserts.assertEqualsAndHashCode(
new JsonPrimitive(new BigInteger("0")), new JsonPrimitive(0));
new JsonPrimitive(new BigDecimal("0")), new JsonPrimitive(0));
eamonnmcmanus marked this conversation as resolved.
Show resolved Hide resolved
MoreAsserts.assertEqualsAndHashCode(
new JsonPrimitive(Float.NaN), new JsonPrimitive(Double.NaN));
}
Expand Down
8 changes: 3 additions & 5 deletions gson/src/test/java/com/google/gson/MixedStreamTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -74,11 +74,9 @@ public void testReadMixedStreamed() throws IOException {
JsonReader jsonReader = new JsonReader(stringReader);

jsonReader.beginArray();
// actual and expected object are inverted in the test.
// gson.fromJson(jsonReader, Car.class) as arg of assertThat() cause an ambiguous method call
assertThat(BLUE_MUSTANG).isEqualTo(gson.fromJson(jsonReader, Car.class));
assertThat(BLACK_BMW).isEqualTo(gson.fromJson(jsonReader, Car.class));
assertThat(RED_MIATA).isEqualTo(gson.fromJson(jsonReader, Car.class));
assertThat(gson.<Car>fromJson(jsonReader, Car.class)).isEqualTo(BLUE_MUSTANG);
assertThat(gson.<Car>fromJson(jsonReader, Car.class)).isEqualTo(BLACK_BMW);
assertThat(gson.<Car>fromJson(jsonReader, Car.class)).isEqualTo(RED_MIATA);
jsonReader.endArray();
}

Expand Down
42 changes: 0 additions & 42 deletions gson/src/test/java/com/google/gson/MockExclusionStrategy.java

This file was deleted.

Loading