Skip to content

Commit

Permalink
Merge branch 'main' into marcono1234/JsonElement-documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
eamonnmcmanus authored May 18, 2024
2 parents baf3dd1 + 8bfdbb4 commit 50bcefd
Show file tree
Hide file tree
Showing 26 changed files with 215 additions and 80 deletions.
12 changes: 6 additions & 6 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ jobs:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
- uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4.1.4
- name: "Set up JDK ${{ matrix.java }}"
uses: actions/setup-java@9704b39bf258b59bc04b50fa2dd55e9ed76b47a8 # v4.1.0
uses: actions/setup-java@99b8673ff64fbf99d8d325f52d9a5bdedb8483e9 # v4.2.1
with:
distribution: 'temurin'
java-version: ${{ matrix.java }}
Expand All @@ -35,9 +35,9 @@ jobs:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
- uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4.1.4
- name: "Set up GraalVM"
uses: graalvm/setup-graalvm@5393c3d80982e8a7fa61005137824ef53731ff9a # v1.1.8.1
uses: graalvm/setup-graalvm@2f25c0caae5b220866f732832d5e3e29ff493338 # v1.2.1
with:
java-version: '17'
distribution: 'graalvm'
Expand All @@ -54,9 +54,9 @@ jobs:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
- uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4.1.4
- name: "Set up JDK 17"
uses: actions/setup-java@9704b39bf258b59bc04b50fa2dd55e9ed76b47a8 # v4.1.0
uses: actions/setup-java@99b8673ff64fbf99d8d325f52d9a5bdedb8483e9 # v4.2.1
with:
distribution: 'temurin'
java-version: 17
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/check-android-compatibility.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ jobs:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
- uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4.1.4

- name: Set up JDK 11
uses: actions/setup-java@9704b39bf258b59bc04b50fa2dd55e9ed76b47a8 # v4.1.0
uses: actions/setup-java@99b8673ff64fbf99d8d325f52d9a5bdedb8483e9 # v4.2.1
with:
distribution: 'temurin'
java-version: '11'
Expand Down
8 changes: 4 additions & 4 deletions .github/workflows/check-api-compatibility.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@ jobs:

steps:
- name: Checkout old version
uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4.1.4
with:
ref: ${{ github.event.pull_request.base.sha }}
path: 'gson-old-japicmp'

- name: Set up JDK 11
uses: actions/setup-java@9704b39bf258b59bc04b50fa2dd55e9ed76b47a8 # v4.1.0
uses: actions/setup-java@99b8673ff64fbf99d8d325f52d9a5bdedb8483e9 # v4.2.1
with:
distribution: 'temurin'
java-version: '11'
Expand All @@ -31,15 +31,15 @@ jobs:
mvn --batch-mode --no-transfer-progress install -DskipTests
- name: Checkout new version
uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4.1.4

- name: Check API compatibility
id: check-compatibility
run: |
mvn --batch-mode --fail-at-end --no-transfer-progress package japicmp:cmp -DskipTests
- name: Upload API differences artifacts
uses: actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3 # v4.3.1
uses: actions/upload-artifact@65462800fd760344b1a7b4382951275a0abb4808 # v4.3.3
# Run on workflow success (in that case differences report might include added methods and classes)
# or when API compatibility check failed
if: success() || ( failure() && steps.check-compatibility.outcome == 'failure' )
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/cifuzz.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ jobs:
fuzz-seconds: 600
dry-run: false
- name: Upload Crash
uses: actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3 # v4.3.1
uses: actions/upload-artifact@65462800fd760344b1a7b4382951275a0abb4808 # v4.3.3
if: failure() && steps.build.outcome == 'success'
with:
name: artifacts
Expand Down
8 changes: 4 additions & 4 deletions .github/workflows/codeql-analysis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,18 @@ jobs:

steps:
- name: Checkout repository
uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4.1.4

- name: Set up JDK 17
uses: actions/setup-java@9704b39bf258b59bc04b50fa2dd55e9ed76b47a8 # v4.1.0
uses: actions/setup-java@99b8673ff64fbf99d8d325f52d9a5bdedb8483e9 # v4.2.1
with:
distribution: 'temurin'
java-version: '17'
cache: 'maven'

# Initializes the CodeQL tools for scanning
- name: Initialize CodeQL
uses: github/codeql-action/init@8a470fddafa5cbb6266ee11b37ef4d8aae19c571 # v3.24.6
uses: github/codeql-action/init@d39d31e687223d841ef683f52467bd88e9b21c14 # v3.25.3
with:
languages: ${{ matrix.language }}
# Run all security queries and maintainability and reliability queries
Expand All @@ -50,4 +50,4 @@ jobs:
mvn compile --batch-mode --no-transfer-progress
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@8a470fddafa5cbb6266ee11b37ef4d8aae19c571 # v3.24.6
uses: github/codeql-action/analyze@d39d31e687223d841ef683f52467bd88e9b21c14 # v3.25.3
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ There are a few open-source projects that can convert Java objects to JSON. Howe
> [!NOTE]\
> Gson is currently in maintenance mode; existing bugs will be fixed, but large new features will likely not be added. If you want to add a new feature, please first search for existing GitHub issues, or create a new one to discuss the feature and get feedback.
> [!IMPORTANT]\
> Gson's main focus is on Java. Using it with other JVM languages such as Kotlin or Scala might work fine in many cases, but language-specific features such as Kotlin's non-`null` types or constructors with default arguments are not supported. This can lead to confusing and incorrect behavior.\
> When using languages other than Java, prefer a JSON library with explicit support for that language.
### Goals
* Provide simple `toJson()` and `fromJson()` methods to convert Java objects to JSON and vice-versa
* Allow pre-existing unmodifiable objects to be converted to and from JSON
Expand Down
20 changes: 13 additions & 7 deletions Troubleshooting.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@ This guide describes how to troubleshoot common issues when using Gson.

**Symptom:** `ClassCastException` is thrown when accessing an object deserialized by Gson

**Reason:** Your code is most likely not type-safe
**Reason:**

- Your code is most likely not type-safe
- Or, you have not configured code shrinking tools such as ProGuard or R8 correctly

**Solution:** Make sure your code adheres to the following:

Expand All @@ -19,6 +22,8 @@ This guide describes how to troubleshoot common issues when using Gson.
The overloads with `Type` parameter do not provide any type-safety guarantees.
- When using `TypeToken` make sure you don't capture a type variable. For example avoid something like `new TypeToken<List<T>>()` (where `T` is a type variable). Due to Java [type erasure](https://dev.java/learn/generics/type-erasure/) the actual type of `T` is not available at runtime. Refactor your code to pass around `TypeToken` instances or use [`TypeToken.getParameterized(...)`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/reflect/TypeToken.html#getParameterized(java.lang.reflect.Type,java.lang.reflect.Type...)), for example `TypeToken.getParameterized(List.class, elementType)` where `elementType` is a type you have to provide separately.

If you are using a code shrinking tool such as ProGuard or R8 (for example when building an Android app), make sure it is correctly configured to keep generic signatures and to keep Gson's `TypeToken` class. See the [Android example](examples/android-proguard-example/README.md) for more information.

## <a id="reflection-inaccessible"></a> `InaccessibleObjectException`: 'module ... does not "opens ..." to unnamed module'

**Symptom:** An exception with a message in the form 'module ... does not "opens ..." to unnamed module' is thrown
Expand Down Expand Up @@ -197,7 +202,7 @@ Gson then tries to use reflection and expects that the data is a JSON object (he
**Reason:**

- A built-in adapter does not support JSON null values
- You have written a custom `TypeAdapter` which does not properly handle JSON null values
- Or, you have written a custom `TypeAdapter` which does not properly handle JSON null values

**Solution:** If this occurs for a custom adapter you wrote, add code similar to the following at the beginning of its `read` method:

Expand Down Expand Up @@ -245,7 +250,7 @@ If you want to prevent using reflection on third-party classes in the future you

**Reason:** You used `GsonBuilder.excludeFieldsWithModifiers` to overwrite the default excluded modifiers

**Solution:** When calling `GsonBuilder.excludeFieldsWithModifiers` you overwrite the default excluded modifiers. Therefore, you have to explicitly exclude `static` fields if desired. This can be done by adding `Modifier.STATIC` as additional argument.
**Solution:** When calling `GsonBuilder.excludeFieldsWithModifiers` you overwrite the default excluded modifiers. Therefore, you have to explicitly exclude `static` fields if desired. This can be done by adding `Modifier.STATIC` as additional argument to the `excludeFieldsWithModifiers` call.

## <a id="no-such-method-error"></a> `NoSuchMethodError` when calling Gson methods

Expand All @@ -272,12 +277,13 @@ If that fails with a `NullPointerException` you have to try one of the other way
**Reason:**

- The name you have specified with a [`@SerializedName`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/annotations/SerializedName.html) annotation for a field collides with the name of another field
- The [`FieldNamingStrategy`](https://javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/FieldNamingStrategy.html) you have specified produces conflicting field names
- A field of your class has the same name as the field of a superclass
- Or, the [`FieldNamingStrategy`](https://javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/FieldNamingStrategy.html) you have specified produces conflicting field names
- Or, a field of your class has the same name as the field of a superclass
- Or, you are using an obfuscation tool such as ProGuard or R8 and it has renamed the fields; in that case see [this troubleshooting point](#android-app-random-names)

Gson prevents multiple fields with the same name because during deserialization it would be ambiguous for which field the JSON data should be deserialized. For serialization it would cause the same field to appear multiple times in JSON. While the JSON specification permits this, it is likely that the application parsing the JSON data will not handle it correctly.

**Solution:** First identify the fields with conflicting names based on the exception message. Then decide if you want to rename one of them using the [`@SerializedName`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/annotations/SerializedName.html) annotation, or if you want to [exclude](UserGuide.md#excluding-fields-from-serialization-and-deserialization) one of them. When excluding one of the fields you have to include it for both serialization and deserialization (even if your application only performs one of these actions) because the duplicate field check cannot differentiate between these actions.
**Solution:** First identify the fields with conflicting names based on the exception message. Then decide if you want to rename one of them using the [`@SerializedName`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/annotations/SerializedName.html) annotation, or if you want to [exclude](UserGuide.md#excluding-fields-from-serialization-and-deserialization) one of them. When excluding one of the fields you have to apply the exclusion for both serialization and deserialization (even if your application only performs one of these actions) because the duplicate field check cannot differentiate between these actions.

## <a id="java-lang-class-unsupported"></a> `UnsupportedOperationException` when serializing or deserializing `java.lang.Class`

Expand Down Expand Up @@ -325,7 +331,7 @@ For older Gson versions a `RuntimeException` with message 'Missing type paramete
**Reason:**

- You created a `TypeToken` without type argument, for example `new TypeToken() {}` (note the missing `<...>`). You always have to provide the type argument, for example like this: `new TypeToken<List<String>>() {}`. Normally the compiler will also emit a 'raw types' warning when you forget the `<...>`.
- You are using a code shrinking tool such as ProGuard or R8 (Android app builds normally have this enabled by default) but have not configured it correctly for usage with Gson.
- Or, you are using a code shrinking tool such as ProGuard or R8 (Android app builds normally have this enabled by default) but have not configured it correctly for usage with Gson.

**Solution:** When you are using a code shrinking tool such as ProGuard or R8 you have to adjust your configuration to include the following rules:

Expand Down
8 changes: 4 additions & 4 deletions gson/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
<dependency>
<groupId>com.google.errorprone</groupId>
<artifactId>error_prone_annotations</artifactId>
<version>2.25.0</version>
<version>2.27.0</version>
</dependency>

<dependency>
Expand All @@ -66,7 +66,7 @@
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava-testlib</artifactId>
<version>33.0.0-jre</version>
<version>33.1.0-jre</version>
<scope>test</scope>
</dependency>
</dependencies>
Expand Down Expand Up @@ -201,7 +201,7 @@
<dependency>
<groupId>com.guardsquare</groupId>
<artifactId>proguard-core</artifactId>
<version>9.1.1</version>
<version>9.1.3</version>
</dependency>
</dependencies>
<configuration>
Expand Down Expand Up @@ -263,7 +263,7 @@
<plugin>
<groupId>org.moditect</groupId>
<artifactId>moditect-maven-plugin</artifactId>
<version>1.1.0</version>
<version>1.2.1.Final</version>
<executions>
<execution>
<id>add-module-info</id>
Expand Down
3 changes: 3 additions & 0 deletions gson/src/main/java/com/google/gson/JsonArray.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@
* <p>{@code JsonArray} only implements the {@link Iterable} interface but not the {@link List}
* interface. A {@code List} view of it can be obtained with {@link #asList()}.
*
* <p>See the {@link JsonElement} documentation for details on how to convert {@code JsonArray} and
* generally any {@code JsonElement} from and to JSON.
*
* @author Inderjeet Singh
* @author Joel Leitch
*/
Expand Down
44 changes: 39 additions & 5 deletions gson/src/main/java/com/google/gson/JsonElement.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
* A class representing an element of JSON. It could either be a {@link JsonObject}, a {@link
* JsonArray}, a {@link JsonPrimitive} or a {@link JsonNull}.
*
* <p>This class provides multiple {@code getAs...} methods which allow
* <p>This class provides multiple {@code getAs} methods which allow
*
* <ul>
* <li>obtaining the represented primitive value, for example {@link #getAsString()}
Expand All @@ -53,11 +53,11 @@
* </pre>
* </ul>
*
* To convert a {@code JsonElement} to JSON the method {@link Gson#toJson(JsonElement)} and its
* overloads can be used.
* To convert a {@code JsonElement} to JSON either {@link #toString() JsonElement.toString()} or the
* method {@link Gson#toJson(JsonElement)} and its overloads can be used.
*
* <p>It is also possible to obtain the {@link TypeAdapter} for {@code JsonElement} from a {@link
* Gson} instance and then use it for conversion to JSON:
* Gson} instance and then use it for conversion from and to JSON:
*
* <pre>{@code
* TypeAdapter<JsonElement> adapter = gson.getAdapter(JsonElement.class);
Expand Down Expand Up @@ -384,7 +384,41 @@ public short getAsShort() {
throw new UnsupportedOperationException(getClass().getSimpleName());
}

/** Returns a String representation of this element. */
/**
* Converts this element to a JSON string.
*
* <p>For example:
*
* <pre>
* JsonObject object = new JsonObject();
* object.add("a", JsonNull.INSTANCE);
* JsonArray array = new JsonArray();
* array.add(1);
* object.add("b", array);
*
* String json = object.toString();
* // json: {"a":null,"b":[1]}
* </pre>
*
* If this element or any nested elements contain {@link Double#NaN NaN} or {@link
* Double#isInfinite() Infinity} that value is written to JSON, even though the JSON specification
* does not permit these values.
*
* <p>To customize formatting or to directly write to an {@link Appendable} instead of creating an
* intermediate {@code String} first, use {@link Gson#toJson(JsonElement, Appendable)
* Gson.toJson(JsonElement, ...)}.
*
* <p>To get the contained String value (without enclosing {@code "} and without escaping), use
* {@link #getAsString()} instead:
*
* <pre>
* JsonPrimitive jsonPrimitive = new JsonPrimitive("with \" quote");
* String json = jsonPrimitive.toString();
* // json: "with \" quote"
* String value = jsonPrimitive.getAsString();
* // value: with " quote
* </pre>
*/
@Override
public String toString() {
try {
Expand Down
5 changes: 4 additions & 1 deletion gson/src/main/java/com/google/gson/JsonObject.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
import java.util.Set;

/**
* A class representing an object type in Json. An object consists of name-value pairs where names
* A class representing an object type in JSON. An object consists of name-value pairs where names
* are strings, and values are any other type of {@link JsonElement}. This allows for a creating a
* tree of JsonElements. The member elements of this object are maintained in order they were added.
* This class does not support {@code null} values. If {@code null} is provided as value argument to
Expand All @@ -31,6 +31,9 @@
* <p>{@code JsonObject} does not implement the {@link Map} interface, but a {@code Map} view of it
* can be obtained with {@link #asMap()}.
*
* <p>See the {@link JsonElement} documentation for details on how to convert {@code JsonObject} and
* generally any {@code JsonElement} from and to JSON.
*
* @author Inderjeet Singh
* @author Joel Leitch
*/
Expand Down
3 changes: 3 additions & 0 deletions gson/src/main/java/com/google/gson/JsonPrimitive.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@
* A class representing a JSON primitive value. A primitive value is either a String, a Java
* primitive, or a Java primitive wrapper type.
*
* <p>See the {@link JsonElement} documentation for details on how to convert {@code JsonPrimitive}
* and generally any {@code JsonElement} from and to JSON.
*
* @author Inderjeet Singh
* @author Joel Leitch
*/
Expand Down
32 changes: 20 additions & 12 deletions gson/src/main/java/com/google/gson/ToNumberPolicy.java
Original file line number Diff line number Diff line change
Expand Up @@ -68,22 +68,30 @@ public Number readNumber(JsonReader in) throws IOException {
@Override
public Number readNumber(JsonReader in) throws IOException, JsonParseException {
String value = in.nextString();
try {
return Long.parseLong(value);
} catch (NumberFormatException longE) {
if (value.indexOf('.') >= 0) {
return parseAsDouble(value, in);
} else {
try {
Double d = Double.valueOf(value);
if ((d.isInfinite() || d.isNaN()) && !in.isLenient()) {
throw new MalformedJsonException(
"JSON forbids NaN and infinities: " + d + "; at path " + in.getPreviousPath());
}
return d;
} catch (NumberFormatException doubleE) {
throw new JsonParseException(
"Cannot parse " + value + "; at path " + in.getPreviousPath(), doubleE);
return Long.parseLong(value);
} catch (NumberFormatException e) {
return parseAsDouble(value, in);
}
}
}

private Number parseAsDouble(String value, JsonReader in) throws IOException {
try {
Double d = Double.valueOf(value);
if ((d.isInfinite() || d.isNaN()) && !in.isLenient()) {
throw new MalformedJsonException(
"JSON forbids NaN and infinities: " + d + "; at path " + in.getPreviousPath());
}
return d;
} catch (NumberFormatException e) {
throw new JsonParseException(
"Cannot parse " + value + "; at path " + in.getPreviousPath(), e);
}
}
},

/**
Expand Down
Loading

0 comments on commit 50bcefd

Please sign in to comment.