Merge remote-tracking branch 'origin/master'
ci/woodpecker/push/woodpecker Pipeline failed
Details
ci/woodpecker/push/woodpecker Pipeline failed
Details
# Conflicts: # .github/ISSUE_TEMPLATE/bug_report.md # .github/workflows/build.yml # extras/pom.xml # extras/src/main/java/com/google/gson/graph/GraphAdapterBuilder.java # extras/src/main/java/com/google/gson/typeadapters/UtcDateTypeAdapter.java # extras/src/test/java/com/google/gson/interceptors/InterceptorTest.java # extras/src/test/java/com/google/gson/typeadapters/PostConstructAdapterFactoryTest.java # extras/src/test/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactoryTest.java # extras/src/test/java/com/google/gson/typeadapters/UtcDateTypeAdapterTest.java # gson/src/test/java/com/google/gson/CommentsTest.java # gson/src/test/java/com/google/gson/ToNumberPolicyTest.java # gson/src/test/java/com/google/gson/functional/EnumWithObfuscatedTest.java # gson/src/test/java/com/google/gson/functional/JsonParserTest.java # gson/src/test/java/com/google/gson/functional/LeniencyTest.java # gson/src/test/java/com/google/gson/functional/MapTest.java # gson/src/test/java/com/google/gson/functional/PrimitiveCharacterTest.java # gson/src/test/java/com/google/gson/functional/ReflectionAccessTest.java # gson/src/test/java/com/google/gson/functional/SecurityTest.java # gson/src/test/java/com/google/gson/stream/JsonReaderTest.java # gson/src/test/resources/testcases-proguard.conf # metrics/pom.xml # metrics/src/main/java/com/google/gson/metrics/BagOfPrimitives.java # proto/pom.xml # proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithAnnotationsTest.java # proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithComplexAndRepeatedFieldsTest.java # proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithPrimitiveTypesTest.java
This commit is contained in:
commit
b6cc63919d
11
README.md
11
README.md
|
@ -45,7 +45,7 @@ There are a few open-source projects that can convert Java objects to JSON. Howe
|
||||||
Gradle:
|
Gradle:
|
||||||
```gradle
|
```gradle
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation 'com.google.code.gson:gson:2.10'
|
implementation 'com.google.code.gson:gson:2.10.1'
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -54,7 +54,7 @@ Maven:
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.google.code.gson</groupId>
|
<groupId>com.google.code.gson</groupId>
|
||||||
<artifactId>gson</artifactId>
|
<artifactId>gson</artifactId>
|
||||||
<version>2.10</version>
|
<version>2.10.1</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -83,9 +83,10 @@ see [`GsonBuilder.disableJdkUnsafe()`](https://javadoc.io/doc/com.google.code.gs
|
||||||
|
|
||||||
### Documentation
|
### Documentation
|
||||||
* [API Javadoc](https://www.javadoc.io/doc/com.google.code.gson/gson): Documentation for the current release
|
* [API Javadoc](https://www.javadoc.io/doc/com.google.code.gson/gson): Documentation for the current release
|
||||||
* [User guide](https://github.com/google/gson/blob/master/UserGuide.md): This guide contains examples on how to use Gson in your code.
|
* [User guide](UserGuide.md): This guide contains examples on how to use Gson in your code
|
||||||
* [Change log](https://github.com/google/gson/blob/master/CHANGELOG.md): Changes in the recent versions
|
* [Troubleshooting guide](Troubleshooting.md): Describes how to solve common issues when using Gson
|
||||||
* [Design document](https://github.com/google/gson/blob/master/GsonDesignDocument.md): This document discusses issues we faced while designing Gson. It also includes a comparison of Gson with other Java libraries that can be used for Json conversion
|
* [Change log](CHANGELOG.md): Changes in the recent versions
|
||||||
|
* [Design document](GsonDesignDocument.md): This document discusses issues we faced while designing Gson. It also includes a comparison of Gson with other Java libraries that can be used for Json conversion
|
||||||
|
|
||||||
Please use the ['gson' tag on StackOverflow](https://stackoverflow.com/questions/tagged/gson) or the [google-gson Google group](https://groups.google.com/group/google-gson) to discuss Gson or to post questions.
|
Please use the ['gson' tag on StackOverflow](https://stackoverflow.com/questions/tagged/gson) or the [google-gson Google group](https://groups.google.com/group/google-gson) to discuss Gson or to post questions.
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,212 @@
|
||||||
|
# Troubleshooting Guide
|
||||||
|
|
||||||
|
This guide describes how to troubleshoot common issues when using Gson.
|
||||||
|
|
||||||
|
## `ClassCastException` when using deserialized object
|
||||||
|
|
||||||
|
**Symptom:** `ClassCastException` is thrown when accessing an object deserialized by Gson
|
||||||
|
|
||||||
|
**Reason:** Your code is most likely not type-safe
|
||||||
|
|
||||||
|
**Solution:** Make sure your code adheres to the following:
|
||||||
|
|
||||||
|
- Avoid raw types: Instead of calling `fromJson(..., List.class)`, create for example a `TypeToken<List<MyClass>>`.
|
||||||
|
See the [user guide](UserGuide.md#collections-examples) for more information.
|
||||||
|
- When using `TypeToken` prefer the `Gson.fromJson` overloads with `TypeToken` parameter such as [`fromJson(Reader, TypeToken)`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/Gson.html#fromJson(java.io.Reader,com.google.gson.reflect.TypeToken)).
|
||||||
|
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 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, elementClass)`.
|
||||||
|
|
||||||
|
## `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
|
||||||
|
|
||||||
|
**Reason:** You use Gson by accident to access internal fields of third-party classes
|
||||||
|
|
||||||
|
**Solution:** Write custom Gson [`TypeAdapter`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/TypeAdapter.html) implementations for the affected classes or change the type of your data. If this occurs for a field in one of your classes which you did not actually want to serialize or deserialize in the first place, you can exclude that field, see the [user guide](UserGuide.md#excluding-fields-from-serialization-and-deserialization).
|
||||||
|
|
||||||
|
**Explanation:**
|
||||||
|
|
||||||
|
When no built-in adapter for a type exists and no custom adapter has been registered, Gson falls back to using reflection to access the fields of a class (including `private` ones). Most likely you are seeing this error because you (by accident) rely on the reflection-based adapter for third-party classes. That should be avoided because you make yourself dependent on the implementation details of these classes which could change at any point. For the JDK it is also not possible anymore to access internal fields using reflection starting with JDK 17, see [JEP 403](https://openjdk.org/jeps/403).
|
||||||
|
|
||||||
|
If you want to prevent using reflection on third-party classes in the future you can write your own [`ReflectionAccessFilter`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/ReflectionAccessFilter.html) or use one of the predefined ones, such as `ReflectionAccessFilter.BLOCK_ALL_PLATFORM`.
|
||||||
|
|
||||||
|
## `InaccessibleObjectException`: 'module ... does not "opens ..." to module com.google.gson'
|
||||||
|
|
||||||
|
**Symptom:** An exception with a message in the form 'module ... does not "opens ..." to module com.google.gson' is thrown
|
||||||
|
|
||||||
|
**Reason:**
|
||||||
|
|
||||||
|
- If the reported package is your own package then you have not configured the module declaration of your project to allow Gson to use reflection on your classes.
|
||||||
|
- If the reported package is from a third party library or the JDK see [this troubleshooting point](#inaccessibleobjectexception-module--does-not-opens--to-unnamed-module).
|
||||||
|
|
||||||
|
**Solution:** Make sure the `module-info.java` file of your project allows Gson to use reflection on your classes, for example:
|
||||||
|
|
||||||
|
```java
|
||||||
|
module mymodule {
|
||||||
|
requires com.google.gson;
|
||||||
|
|
||||||
|
opens mypackage to com.google.gson;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Or in case this occurs for a field in one of your classes which you did not actually want to serialize or deserialize in the first place, you can exclude that field, see the [user guide](UserGuide.md#excluding-fields-from-serialization-and-deserialization).
|
||||||
|
|
||||||
|
## Android app not working in Release mode; random property names
|
||||||
|
|
||||||
|
**Symptom:** Your Android app is working fine in Debug mode but fails in Release mode and the JSON properties have seemingly random names such as `a`, `b`, ...
|
||||||
|
|
||||||
|
**Reason:** You probably have not configured ProGuard / R8 correctly
|
||||||
|
|
||||||
|
**Solution:** Make sure you have configured ProGuard / R8 correctly to preserve the names of your fields. See the [Android example](examples/android-proguard-example/README.md) for more information.
|
||||||
|
|
||||||
|
## Android app unable to parse JSON after app update
|
||||||
|
|
||||||
|
**Symptom:** You released a new version of your Android app and it fails to parse JSON data created by the previous version of your app
|
||||||
|
|
||||||
|
**Reason:** You probably have not configured ProGuard / R8 correctly; probably the fields names are being obfuscated and their naming changed between the versions of your app
|
||||||
|
|
||||||
|
**Solution:** Make sure you have configured ProGuard / R8 correctly to preserve the names of your fields. See the [Android example](examples/android-proguard-example/README.md) for more information.
|
||||||
|
|
||||||
|
If you want to preserve backward compatibility for you app you can use [`@SerializedName`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/annotations/SerializedName.html) on the fields to specify the obfuscated name as alternate, for example: `@SerializedName(value = "myprop", alternate = "a")`
|
||||||
|
|
||||||
|
Normally ProGuard and R8 produce a mapping file, this makes it easier to find out the obfuscated field names instead of having to find them out through trial and error or other means. See the [Android Studio user guide](https://developer.android.com/studio/build/shrink-code.html#retracing) for more information.
|
||||||
|
|
||||||
|
## Default field values not present after deserialization
|
||||||
|
|
||||||
|
**Symptom:** You have assign default values to fields but after deserialization the fields have their standard value (such as `null` or `0`)
|
||||||
|
|
||||||
|
**Reason:** Gson cannot invoke the constructor of your class and falls back to JDK `Unsafe` (or similar means)
|
||||||
|
|
||||||
|
**Solution:** Make sure that the class:
|
||||||
|
|
||||||
|
- is `static` (explicitly or implicitly when it is a top-level class)
|
||||||
|
- has a no-args constructor
|
||||||
|
|
||||||
|
Otherwise Gson will by default try to use JDK `Unsafe` or similar means to create an instance of your class without invoking the constructor and without running any initializers. You can also disable that behavior through [`GsonBuilder.disableJdkUnsafe()`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/GsonBuilder.html#disableJdkUnsafe()) to notice such issues early on.
|
||||||
|
|
||||||
|
## `null` values for anonymous and local classes
|
||||||
|
|
||||||
|
**Symptom:** Objects of a class are always serialized as JSON `null` / always deserialized as Java `null`
|
||||||
|
|
||||||
|
**Reason:** The class you are serializing or deserializing is an anonymous or a local class (or you have specified a custom `ExclusionStrategy`)
|
||||||
|
|
||||||
|
**Solution:** Convert the class to a `static` nested class. If the class is already `static` make sure you have not specified a Gson `ExclusionStrategy` which might exclude the class.
|
||||||
|
|
||||||
|
Notes:
|
||||||
|
|
||||||
|
- "double brace-initialization" also creates anonymous classes
|
||||||
|
- Local record classes (feature added in Java 16) are supported by Gson and are not affected by this
|
||||||
|
|
||||||
|
## Map keys having unexpected format in JSON
|
||||||
|
|
||||||
|
**Symptom:** JSON output for `Map` keys is unexpected / cannot be deserialized again
|
||||||
|
|
||||||
|
**Reason:** The `Map` key type is 'complex' and you have not configured the `GsonBuilder` properly
|
||||||
|
|
||||||
|
**Solution:** Use [`GsonBuilder.enableComplexMapKeySerialization()`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/GsonBuilder.html#enableComplexMapKeySerialization()). See also the [user guide](UserGuide.md#maps-examples) for more information.
|
||||||
|
|
||||||
|
## Parsing JSON fails with `MalformedJsonException`
|
||||||
|
|
||||||
|
**Symptom:** JSON parsing fails with `MalformedJsonException`
|
||||||
|
|
||||||
|
**Reason:** The JSON data is actually malformed
|
||||||
|
|
||||||
|
**Solution:** During debugging log the JSON data right before calling Gson methods or set a breakpoint to inspect the data and make sure it has the expected format. Sometimes APIs might return HTML error pages (instead of JSON data) when reaching rate limits or when other errors occur. Also read the location information of the `MalformedJsonException` exception message, it indicates where exactly in the document the malformed data was detected, including the [JSONPath](https://goessner.net/articles/JsonPath/).
|
||||||
|
|
||||||
|
## Integral JSON number is parsed as `double`
|
||||||
|
|
||||||
|
**Symptom:** JSON data contains an integral number such as `45` but Gson returns it as `double`
|
||||||
|
|
||||||
|
**Reason:** When parsing a JSON number as `Object`, Gson will by default create always return a `double`
|
||||||
|
|
||||||
|
**Solution:** Use [`GsonBuilder.setObjectToNumberStrategy`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/GsonBuilder.html#setObjectToNumberStrategy(com.google.gson.ToNumberStrategy)) to specify what type of number should be returned
|
||||||
|
|
||||||
|
## Malformed JSON not rejected
|
||||||
|
|
||||||
|
**Symptom:** Gson parses malformed JSON without throwing any exceptions
|
||||||
|
|
||||||
|
**Reason:** Due to legacy reasons Gson performs parsing by default in lenient mode
|
||||||
|
|
||||||
|
**Solution:** See [`Gson` class documentation](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/Gson.html) section "Lenient JSON handling"
|
||||||
|
|
||||||
|
Note: Even in non-lenient mode Gson deviates slightly from the JSON specification, see [`JsonReader.setLenient`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/stream/JsonReader.html#setLenient(boolean)) for more details.
|
||||||
|
|
||||||
|
## `IllegalStateException`: "Expected ... but was ..."
|
||||||
|
|
||||||
|
**Symptom:** An `IllegalStateException` with a message in the form "Expected ... but was ..." is thrown
|
||||||
|
|
||||||
|
**Reason:** The JSON data does not have the correct format
|
||||||
|
|
||||||
|
**Solution:** Make sure that your classes correctly model the JSON data. Also during debugging log the JSON data right before calling Gson methods or set a breakpoint to inspect the data and make sure it has the expected format. Read the location information of the exception message, it indicates where exactly in the document the error occurred, including the [JSONPath](https://goessner.net/articles/JsonPath/).
|
||||||
|
|
||||||
|
## `IllegalStateException`: "Expected ... but was NULL"
|
||||||
|
|
||||||
|
**Symptom:** An `IllegalStateException` with a message in the form "Expected ... but was NULL" is thrown
|
||||||
|
|
||||||
|
**Reason:** You have written a custom `TypeAdapter` which does not properly handle a JSON null value
|
||||||
|
|
||||||
|
**Solution:** Add code similar to the following at the beginning of the `read` method of your adapter:
|
||||||
|
|
||||||
|
```java
|
||||||
|
@Override
|
||||||
|
public MyClass read(JsonReader in) throws IOException {
|
||||||
|
if (in.peek() == JsonToken.NULL) {
|
||||||
|
in.nextNull();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Alternatively you can call [`nullSafe()`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/TypeAdapter.html#nullSafe()) on the adapter instance you created.
|
||||||
|
|
||||||
|
## Properties missing in JSON
|
||||||
|
|
||||||
|
**Symptom:** Properties are missing in the JSON output
|
||||||
|
|
||||||
|
**Reason:** Gson by default omits JSON null from the output (or: ProGuard / R8 is not configured correctly and removed unused fields)
|
||||||
|
|
||||||
|
**Solution:** Use [`GsonBuilder.serializeNulls()`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/GsonBuilder.html#serializeNulls())
|
||||||
|
|
||||||
|
Note: Gson does not support anonymous and local classes and will serialize them as JSON null, see the [related troubleshooting point](#null-values-for-anonymous-and-local-classes).
|
||||||
|
|
||||||
|
## JSON output changes for newer Android versions
|
||||||
|
|
||||||
|
**Symptom:** The JSON output differs when running on newer Android versions
|
||||||
|
|
||||||
|
**Reason:** You use Gson by accident to access internal fields of Android classes
|
||||||
|
|
||||||
|
**Solution:** Write custom Gson [`TypeAdapter`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/TypeAdapter.html) implementations for the affected classes or change the type of your data
|
||||||
|
|
||||||
|
**Explanation:**
|
||||||
|
|
||||||
|
When no built-in adapter for a type exists and no custom adapter has been registered, Gson falls back to using reflection to access the fields of a class (including `private` ones). Most likely you are experiencing this issue because you (by accident) rely on the reflection-based adapter for Android classes. That should be avoided because you make yourself dependent on the implementation details of these classes which could change at any point.
|
||||||
|
|
||||||
|
If you want to prevent using reflection on third-party classes in the future you can write your own [`ReflectionAccessFilter`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/ReflectionAccessFilter.html) or use one of the predefined ones, such as `ReflectionAccessFilter.BLOCK_ALL_PLATFORM`.
|
||||||
|
|
||||||
|
## JSON output contains values of `static` fields
|
||||||
|
|
||||||
|
**Symptom:** The JSON output contains values of `static` fields
|
||||||
|
|
||||||
|
**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.
|
||||||
|
|
||||||
|
## `NoSuchMethodError` when calling Gson methods
|
||||||
|
|
||||||
|
**Symptom:** A `java.lang.NoSuchMethodError` is thrown when trying to call certain Gson methods
|
||||||
|
|
||||||
|
**Reason:**
|
||||||
|
|
||||||
|
- You have multiple versions of Gson on your classpath
|
||||||
|
- Or, the Gson version you compiled against is different from the one on your classpath
|
||||||
|
- Or, you are using a code shrinking tool such as ProGuard or R8 which removed methods from Gson
|
||||||
|
|
||||||
|
**Solution:** First disable any code shrinking tools such as ProGuard or R8 and check if the issue persists. If not, you have to tweak the configuration of that tool to not modify Gson classes. Otherwise verify that the Gson JAR on your classpath is the same you are compiling against, and that there is only one Gson JAR on your classpath. See [this Stack Overflow question](https://stackoverflow.com/q/227486) to find out where a class is loaded from. For example, for debugging you could include the following code:
|
||||||
|
|
||||||
|
```java
|
||||||
|
System.out.println(Gson.class.getProtectionDomain().getCodeSource().getLocation());
|
||||||
|
```
|
||||||
|
|
||||||
|
If that fails with a `NullPointerException` you have to try one of the other ways to find out where a class is loaded from.
|
162
UserGuide.md
162
UserGuide.md
|
@ -1,48 +1,48 @@
|
||||||
# Gson User Guide
|
# Gson User Guide
|
||||||
|
|
||||||
1. [Overview](#TOC-Overview)
|
1. [Overview](#overview)
|
||||||
2. [Goals for Gson](#TOC-Goals-for-Gson)
|
2. [Goals for Gson](#goals-for-gson)
|
||||||
3. [Gson Performance and Scalability](#TOC-Gson-Performance-and-Scalability)
|
3. [Gson Performance and Scalability](#gson-performance-and-scalability)
|
||||||
4. [Gson Users](#TOC-Gson-Users)
|
4. [Gson Users](#gson-users)
|
||||||
5. [Using Gson](#TOC-Using-Gson)
|
5. [Using Gson](#using-gson)
|
||||||
* [Using Gson with Gradle/Android](#TOC-Gson-With-Gradle)
|
* [Using Gson with Gradle/Android](#using-gson-with-gradleandroid)
|
||||||
* [Using Gson with Maven](#TOC-Gson-With-Maven)
|
* [Using Gson with Maven](#using-gson-with-maven)
|
||||||
* [Primitives Examples](#TOC-Primitives-Examples)
|
* [Primitives Examples](#primitives-examples)
|
||||||
* [Object Examples](#TOC-Object-Examples)
|
* [Object Examples](#object-examples)
|
||||||
* [Finer Points with Objects](#TOC-Finer-Points-with-Objects)
|
* [Finer Points with Objects](#finer-points-with-objects)
|
||||||
* [Nested Classes (including Inner Classes)](#TOC-Nested-Classes-including-Inner-Classes-)
|
* [Nested Classes (including Inner Classes)](#nested-classes-including-inner-classes)
|
||||||
* [Array Examples](#TOC-Array-Examples)
|
* [Array Examples](#array-examples)
|
||||||
* [Collections Examples](#TOC-Collections-Examples)
|
* [Collections Examples](#collections-examples)
|
||||||
* [Collections Limitations](#TOC-Collections-Limitations)
|
* [Collections Limitations](#collections-limitations)
|
||||||
* [Maps Examples](#TOC-Maps-Examples)
|
* [Maps Examples](#maps-examples)
|
||||||
* [Serializing and Deserializing Generic Types](#TOC-Serializing-and-Deserializing-Generic-Types)
|
* [Serializing and Deserializing Generic Types](#serializing-and-deserializing-generic-types)
|
||||||
* [Serializing and Deserializing Collection with Objects of Arbitrary Types](#TOC-Serializing-and-Deserializing-Collection-with-Objects-of-Arbitrary-Types)
|
* [Serializing and Deserializing Collection with Objects of Arbitrary Types](#serializing-and-deserializing-collection-with-objects-of-arbitrary-types)
|
||||||
* [Built-in Serializers and Deserializers](#TOC-Built-in-Serializers-and-Deserializers)
|
* [Built-in Serializers and Deserializers](#built-in-serializers-and-deserializers)
|
||||||
* [Custom Serialization and Deserialization](#TOC-Custom-Serialization-and-Deserialization)
|
* [Custom Serialization and Deserialization](#custom-serialization-and-deserialization)
|
||||||
* [Writing a Serializer](#TOC-Writing-a-Serializer)
|
* [Writing a Serializer](#writing-a-serializer)
|
||||||
* [Writing a Deserializer](#TOC-Writing-a-Deserializer)
|
* [Writing a Deserializer](#writing-a-deserializer)
|
||||||
* [Writing an Instance Creator](#TOC-Writing-an-Instance-Creator)
|
* [Writing an Instance Creator](#writing-an-instance-creator)
|
||||||
* [InstanceCreator for a Parameterized Type](#TOC-InstanceCreator-for-a-Parameterized-Type)
|
* [InstanceCreator for a Parameterized Type](#instancecreator-for-a-parameterized-type)
|
||||||
* [Compact Vs. Pretty Printing for JSON Output Format](#TOC-Compact-Vs.-Pretty-Printing-for-JSON-Output-Format)
|
* [Compact Vs. Pretty Printing for JSON Output Format](#compact-vs-pretty-printing-for-json-output-format)
|
||||||
* [Null Object Support](#TOC-Null-Object-Support)
|
* [Null Object Support](#null-object-support)
|
||||||
* [Versioning Support](#TOC-Versioning-Support)
|
* [Versioning Support](#versioning-support)
|
||||||
* [Excluding Fields From Serialization and Deserialization](#TOC-Excluding-Fields-From-Serialization-and-Deserialization)
|
* [Excluding Fields From Serialization and Deserialization](#excluding-fields-from-serialization-and-deserialization)
|
||||||
* [Java Modifier Exclusion](#TOC-Java-Modifier-Exclusion)
|
* [Java Modifier Exclusion](#java-modifier-exclusion)
|
||||||
* [Gson's `@Expose`](#TOC-Gson-s-Expose)
|
* [Gson's `@Expose`](#gsons-expose)
|
||||||
* [User Defined Exclusion Strategies](#TOC-User-Defined-Exclusion-Strategies)
|
* [User Defined Exclusion Strategies](#user-defined-exclusion-strategies)
|
||||||
* [JSON Field Naming Support](#TOC-JSON-Field-Naming-Support)
|
* [JSON Field Naming Support](#json-field-naming-support)
|
||||||
* [Sharing State Across Custom Serializers and Deserializers](#TOC-Sharing-State-Across-Custom-Serializers-and-Deserializers)
|
* [Sharing State Across Custom Serializers and Deserializers](#sharing-state-across-custom-serializers-and-deserializers)
|
||||||
* [Streaming](#TOC-Streaming)
|
* [Streaming](#streaming)
|
||||||
6. [Issues in Designing Gson](#TOC-Issues-in-Designing-Gson)
|
6. [Issues in Designing Gson](#issues-in-designing-gson)
|
||||||
7. [Future Enhancements to Gson](#TOC-Future-Enhancements-to-Gson)
|
7. [Future Enhancements to Gson](#future-enhancements-to-gson)
|
||||||
|
|
||||||
## <a name="TOC-Overview"></a>Overview
|
## Overview
|
||||||
|
|
||||||
Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.
|
Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.
|
||||||
|
|
||||||
Gson can work with arbitrary Java objects including pre-existing objects that you do not have source code of.
|
Gson can work with arbitrary Java objects including pre-existing objects that you do not have source code of.
|
||||||
|
|
||||||
## <a name="TOC-Goals-for-Gson"></a>Goals for Gson
|
## Goals for Gson
|
||||||
|
|
||||||
* Provide easy to use mechanisms like `toString()` and constructor (factory method) to convert Java to JSON and vice-versa
|
* Provide easy to use mechanisms like `toString()` and constructor (factory method) to convert Java to JSON and vice-versa
|
||||||
* Allow pre-existing unmodifiable objects to be converted to and from JSON
|
* Allow pre-existing unmodifiable objects to be converted to and from JSON
|
||||||
|
@ -50,7 +50,7 @@ Gson can work with arbitrary Java objects including pre-existing objects that yo
|
||||||
* Support arbitrarily complex objects
|
* Support arbitrarily complex objects
|
||||||
* Generate compact and readable JSON output
|
* Generate compact and readable JSON output
|
||||||
|
|
||||||
## <a name="TOC-Gson-Performance-and-Scalability"></a>Gson Performance and Scalability
|
## Gson Performance and Scalability
|
||||||
|
|
||||||
Here are some metrics that we obtained on a desktop (dual opteron, 8GB RAM, 64-bit Ubuntu) running lots of other things along-with the tests. You can rerun these tests by using the class [`PerformanceTest`](gson/src/test/java/com/google/gson/metrics/PerformanceTest.java).
|
Here are some metrics that we obtained on a desktop (dual opteron, 8GB RAM, 64-bit Ubuntu) running lots of other things along-with the tests. You can rerun these tests by using the class [`PerformanceTest`](gson/src/test/java/com/google/gson/metrics/PerformanceTest.java).
|
||||||
|
|
||||||
|
@ -62,25 +62,25 @@ Here are some metrics that we obtained on a desktop (dual opteron, 8GB RAM, 64-b
|
||||||
|
|
||||||
Note: Delete the `disabled_` prefix to run these tests. We use this prefix to prevent running these tests every time we run JUnit tests.
|
Note: Delete the `disabled_` prefix to run these tests. We use this prefix to prevent running these tests every time we run JUnit tests.
|
||||||
|
|
||||||
## <a name="TOC-Gson-Users"></a>Gson Users
|
## Gson Users
|
||||||
|
|
||||||
Gson was originally created for use inside Google where it is currently used in a number of projects. It is now used by a number of public projects and companies.
|
Gson was originally created for use inside Google where it is currently used in a number of projects. It is now used by a number of public projects and companies.
|
||||||
|
|
||||||
## <a name="TOC-Using-Gson"></a>Using Gson
|
## Using Gson
|
||||||
|
|
||||||
The primary class to use is [`Gson`](gson/src/main/java/com/google/gson/Gson.java) which you can just create by calling `new Gson()`. There is also a class [`GsonBuilder`](gson/src/main/java/com/google/gson/GsonBuilder.java) available that can be used to create a Gson instance with various settings like version control and so on.
|
The primary class to use is [`Gson`](gson/src/main/java/com/google/gson/Gson.java) which you can just create by calling `new Gson()`. There is also a class [`GsonBuilder`](gson/src/main/java/com/google/gson/GsonBuilder.java) available that can be used to create a Gson instance with various settings like version control and so on.
|
||||||
|
|
||||||
The Gson instance does not maintain any state while invoking JSON operations. So, you are free to reuse the same object for multiple JSON serialization and deserialization operations.
|
The Gson instance does not maintain any state while invoking JSON operations. So, you are free to reuse the same object for multiple JSON serialization and deserialization operations.
|
||||||
|
|
||||||
## <a name="TOC-Gson-With-Gradle"></a>Using Gson with Gradle/Android
|
## Using Gson with Gradle/Android
|
||||||
|
|
||||||
```gradle
|
```gradle
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation 'com.google.code.gson:gson:2.10'
|
implementation 'com.google.code.gson:gson:2.10.1'
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## <a name="TOC-Gson-With-Maven"></a>Using Gson with Maven
|
## Using Gson with Maven
|
||||||
|
|
||||||
To use Gson with Maven2/3, you can use the Gson version available in Maven Central by adding the following dependency:
|
To use Gson with Maven2/3, you can use the Gson version available in Maven Central by adding the following dependency:
|
||||||
|
|
||||||
|
@ -90,7 +90,7 @@ To use Gson with Maven2/3, you can use the Gson version available in Maven Centr
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.google.code.gson</groupId>
|
<groupId>com.google.code.gson</groupId>
|
||||||
<artifactId>gson</artifactId>
|
<artifactId>gson</artifactId>
|
||||||
<version>2.10</version>
|
<version>2.10.1</version>
|
||||||
<scope>compile</scope>
|
<scope>compile</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
@ -98,7 +98,7 @@ To use Gson with Maven2/3, you can use the Gson version available in Maven Centr
|
||||||
|
|
||||||
That is it, now your Maven project is Gson enabled.
|
That is it, now your Maven project is Gson enabled.
|
||||||
|
|
||||||
### <a name="TOC-Primitives-Examples"></a>Primitives Examples
|
### Primitives Examples
|
||||||
|
|
||||||
```java
|
```java
|
||||||
// Serialization
|
// Serialization
|
||||||
|
@ -110,15 +110,15 @@ int[] values = { 1 };
|
||||||
gson.toJson(values); // ==> [1]
|
gson.toJson(values); // ==> [1]
|
||||||
|
|
||||||
// Deserialization
|
// Deserialization
|
||||||
int one = gson.fromJson("1", int.class);
|
int i = gson.fromJson("1", int.class);
|
||||||
Integer one = gson.fromJson("1", Integer.class);
|
Integer intObj = gson.fromJson("1", Integer.class);
|
||||||
Long one = gson.fromJson("1", Long.class);
|
Long longObj = gson.fromJson("1", Long.class);
|
||||||
Boolean false = gson.fromJson("false", Boolean.class);
|
Boolean boolObj = gson.fromJson("false", Boolean.class);
|
||||||
String str = gson.fromJson("\"abc\"", String.class);
|
String str = gson.fromJson("\"abc\"", String.class);
|
||||||
String[] anotherStr = gson.fromJson("[\"abc\"]", String[].class);
|
String[] strArray = gson.fromJson("[\"abc\"]", String[].class);
|
||||||
```
|
```
|
||||||
|
|
||||||
### <a name="TOC-Object-Examples"></a>Object Examples
|
### Object Examples
|
||||||
|
|
||||||
```java
|
```java
|
||||||
class BagOfPrimitives {
|
class BagOfPrimitives {
|
||||||
|
@ -146,7 +146,7 @@ BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
|
||||||
// ==> obj2 is just like obj
|
// ==> obj2 is just like obj
|
||||||
```
|
```
|
||||||
|
|
||||||
#### <a name="TOC-Finer-Points-with-Objects"></a>**Finer Points with Objects**
|
#### **Finer Points with Objects**
|
||||||
|
|
||||||
* It is perfectly fine (and recommended) to use private fields.
|
* It is perfectly fine (and recommended) to use private fields.
|
||||||
* There is no need to use any annotations to indicate a field is to be included for serialization and deserialization. All fields in the current class (and from all super classes) are included by default.
|
* There is no need to use any annotations to indicate a field is to be included for serialization and deserialization. All fields in the current class (and from all super classes) are included by default.
|
||||||
|
@ -158,7 +158,7 @@ BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
|
||||||
* Fields corresponding to the outer classes in inner classes are ignored and not included in serialization or deserialization.
|
* Fields corresponding to the outer classes in inner classes are ignored and not included in serialization or deserialization.
|
||||||
* Anonymous and local classes are excluded. They will be serialized as JSON `null` and when deserialized their JSON value is ignored and `null` is returned. Convert the classes to `static` nested classes to enable serialization and deserialization for them.
|
* Anonymous and local classes are excluded. They will be serialized as JSON `null` and when deserialized their JSON value is ignored and `null` is returned. Convert the classes to `static` nested classes to enable serialization and deserialization for them.
|
||||||
|
|
||||||
### <a name="TOC-Nested-Classes-including-Inner-Classes-"></a>Nested Classes (including Inner Classes)
|
### Nested Classes (including Inner Classes)
|
||||||
|
|
||||||
Gson can serialize static nested classes quite easily.
|
Gson can serialize static nested classes quite easily.
|
||||||
|
|
||||||
|
@ -197,7 +197,7 @@ public class InstanceCreatorForB implements InstanceCreator<A.B> {
|
||||||
|
|
||||||
The above is possible, but not recommended.
|
The above is possible, but not recommended.
|
||||||
|
|
||||||
### <a name="TOC-Array-Examples"></a>Array Examples
|
### Array Examples
|
||||||
|
|
||||||
```java
|
```java
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
|
@ -215,7 +215,7 @@ int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class);
|
||||||
|
|
||||||
We also support multi-dimensional arrays, with arbitrarily complex element types.
|
We also support multi-dimensional arrays, with arbitrarily complex element types.
|
||||||
|
|
||||||
### <a name="TOC-Collections-Examples"></a>Collections Examples
|
### Collections Examples
|
||||||
|
|
||||||
```java
|
```java
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
|
@ -235,12 +235,12 @@ Collection<Integer> ints2 = gson.fromJson(json, collectionType);
|
||||||
Fairly hideous: note how we define the type of collection.
|
Fairly hideous: note how we define the type of collection.
|
||||||
Unfortunately, there is no way to get around this in Java.
|
Unfortunately, there is no way to get around this in Java.
|
||||||
|
|
||||||
#### <a name="TOC-Collections-Limitations"></a>Collections Limitations
|
#### Collections Limitations
|
||||||
|
|
||||||
Gson can serialize collection of arbitrary objects but can not deserialize from it, because there is no way for the user to indicate the type of the resulting object. Instead, while deserializing, the Collection must be of a specific, generic type.
|
Gson can serialize collection of arbitrary objects but can not deserialize from it, because there is no way for the user to indicate the type of the resulting object. Instead, while deserializing, the Collection must be of a specific, generic type.
|
||||||
This makes sense, and is rarely a problem when following good Java coding practices.
|
This makes sense, and is rarely a problem when following good Java coding practices.
|
||||||
|
|
||||||
### <a name="TOC-Maps-Examples"></a>Maps Examples
|
### Maps Examples
|
||||||
|
|
||||||
Gson by default serializes any `java.util.Map` implementation as a JSON object. Because JSON objects only support strings as member names, Gson converts the Map keys to strings by calling `toString()` on them, and using `"null"` for `null` keys:
|
Gson by default serializes any `java.util.Map` implementation as a JSON object. Because JSON objects only support strings as member names, Gson converts the Map keys to strings by calling `toString()` on them, and using `"null"` for `null` keys:
|
||||||
|
|
||||||
|
@ -309,7 +309,7 @@ String json = gson.toJson(stringMap); // json is {"key":"value"}
|
||||||
|
|
||||||
Note that when deserializing enums as Map keys, if Gson is unable to find an enum constant with a matching `name()` value respectively `@SerializedName` annotation, it falls back to looking up the enum constant by its `toString()` value. This is to work around the issue described above, but only applies to enum constants.
|
Note that when deserializing enums as Map keys, if Gson is unable to find an enum constant with a matching `name()` value respectively `@SerializedName` annotation, it falls back to looking up the enum constant by its `toString()` value. This is to work around the issue described above, but only applies to enum constants.
|
||||||
|
|
||||||
### <a name="TOC-Serializing-and-Deserializing-Generic-Types"></a>Serializing and Deserializing Generic Types
|
### Serializing and Deserializing Generic Types
|
||||||
|
|
||||||
When you call `toJson(obj)`, Gson calls `obj.getClass()` to get information on the fields to serialize. Similarly, you can typically pass `MyClass.class` object in the `fromJson(json, MyClass.class)` method. This works fine if the object is a non-generic type. However, if the object is of a generic type, then the Generic type information is lost because of Java Type Erasure. Here is an example illustrating the point:
|
When you call `toJson(obj)`, Gson calls `obj.getClass()` to get information on the fields to serialize. Similarly, you can typically pass `MyClass.class` object in the `fromJson(json, MyClass.class)` method. This works fine if the object is a non-generic type. However, if the object is of a generic type, then the Generic type information is lost because of Java Type Erasure. Here is an example illustrating the point:
|
||||||
|
|
||||||
|
@ -337,7 +337,7 @@ gson.fromJson(json, fooType);
|
||||||
|
|
||||||
The idiom used to get `fooType` actually defines an anonymous local inner class containing a method `getType()` that returns the fully parameterized type.
|
The idiom used to get `fooType` actually defines an anonymous local inner class containing a method `getType()` that returns the fully parameterized type.
|
||||||
|
|
||||||
### <a name="TOC-Serializing-and-Deserializing-Collection-with-Objects-of-Arbitrary-Types"></a>Serializing and Deserializing Collection with Objects of Arbitrary Types
|
### Serializing and Deserializing Collection with Objects of Arbitrary Types
|
||||||
|
|
||||||
Sometimes you are dealing with JSON array that contains mixed types. For example:
|
Sometimes you are dealing with JSON array that contains mixed types. For example:
|
||||||
`['hello',5,{name:'GREETINGS',source:'guest'}]`
|
`['hello',5,{name:'GREETINGS',source:'guest'}]`
|
||||||
|
@ -376,7 +376,7 @@ However, deserialization with `fromJson(json, Collection.class)` will not work s
|
||||||
|
|
||||||
This approach is practical only if the array appears as a top-level element or if you can change the field type holding the collection to be of type `Collection<MyCollectionMemberType>`.
|
This approach is practical only if the array appears as a top-level element or if you can change the field type holding the collection to be of type `Collection<MyCollectionMemberType>`.
|
||||||
|
|
||||||
### <a name="TOC-Built-in-Serializers-and-Deserializers"></a>Built-in Serializers and Deserializers
|
### Built-in Serializers and Deserializers
|
||||||
|
|
||||||
Gson has built-in serializers and deserializers for commonly used classes whose default representation may be inappropriate, for instance
|
Gson has built-in serializers and deserializers for commonly used classes whose default representation may be inappropriate, for instance
|
||||||
|
|
||||||
|
@ -387,7 +387,7 @@ For many more, see the internal class [`TypeAdapters`](gson/src/main/java/com/go
|
||||||
|
|
||||||
You can also find source code for some commonly used classes such as JodaTime at [this page](https://sites.google.com/site/gson/gson-type-adapters-for-common-classes-1).
|
You can also find source code for some commonly used classes such as JodaTime at [this page](https://sites.google.com/site/gson/gson-type-adapters-for-common-classes-1).
|
||||||
|
|
||||||
### <a name="TOC-Custom-Serialization-and-Deserialization"></a>Custom Serialization and Deserialization
|
### Custom Serialization and Deserialization
|
||||||
|
|
||||||
Sometimes default representation is not what you want. This is often the case when dealing with library classes (DateTime, etc).
|
Sometimes default representation is not what you want. This is often the case when dealing with library classes (DateTime, etc).
|
||||||
Gson allows you to register your own custom serializers and deserializers. This is done by defining two parts:
|
Gson allows you to register your own custom serializers and deserializers. This is done by defining two parts:
|
||||||
|
@ -407,7 +407,7 @@ gson.registerTypeAdapter(MyType.class, new MyInstanceCreator());
|
||||||
|
|
||||||
`registerTypeAdapter` call checks if the type adapter implements more than one of these interfaces and register it for all of them.
|
`registerTypeAdapter` call checks if the type adapter implements more than one of these interfaces and register it for all of them.
|
||||||
|
|
||||||
#### <a name="TOC-Writing-a-Serializer"></a>Writing a Serializer
|
#### Writing a Serializer
|
||||||
|
|
||||||
Here is an example of how to write a custom serializer for JodaTime `DateTime` class.
|
Here is an example of how to write a custom serializer for JodaTime `DateTime` class.
|
||||||
|
|
||||||
|
@ -421,7 +421,7 @@ private class DateTimeSerializer implements JsonSerializer<DateTime> {
|
||||||
|
|
||||||
Gson calls `serialize()` when it runs into a `DateTime` object during serialization.
|
Gson calls `serialize()` when it runs into a `DateTime` object during serialization.
|
||||||
|
|
||||||
#### <a name="TOC-Writing-a-Deserializer"></a>Writing a Deserializer
|
#### Writing a Deserializer
|
||||||
|
|
||||||
Here is an example of how to write a custom deserializer for JodaTime DateTime class.
|
Here is an example of how to write a custom deserializer for JodaTime DateTime class.
|
||||||
|
|
||||||
|
@ -449,7 +449,7 @@ Often you want to register a single handler for all generic types corresponding
|
||||||
Gson supports registering a single handler for this. You can also register a specific handler for a specific generic type (say `Id<RequiresSpecialHandling>` needed special handling).
|
Gson supports registering a single handler for this. You can also register a specific handler for a specific generic type (say `Id<RequiresSpecialHandling>` needed special handling).
|
||||||
The `Type` parameter for the `toJson()` and `fromJson()` contains the generic type information to help you write a single handler for all generic types corresponding to the same raw type.
|
The `Type` parameter for the `toJson()` and `fromJson()` contains the generic type information to help you write a single handler for all generic types corresponding to the same raw type.
|
||||||
|
|
||||||
### <a name="TOC-Writing-an-Instance-Creator"></a>Writing an Instance Creator
|
### Writing an Instance Creator
|
||||||
|
|
||||||
While deserializing an Object, Gson needs to create a default instance of the class.
|
While deserializing an Object, Gson needs to create a default instance of the class.
|
||||||
Well-behaved classes that are meant for serialization and deserialization should have a no-argument constructor.
|
Well-behaved classes that are meant for serialization and deserialization should have a no-argument constructor.
|
||||||
|
@ -473,7 +473,7 @@ Type could be of a corresponding generic type
|
||||||
* Very useful to invoke constructors which need specific generic type information
|
* Very useful to invoke constructors which need specific generic type information
|
||||||
* For example, if the `Id` class stores the class for which the Id is being created
|
* For example, if the `Id` class stores the class for which the Id is being created
|
||||||
|
|
||||||
#### <a name="TOC-InstanceCreator-for-a-Parameterized-Type"></a>InstanceCreator for a Parameterized Type
|
#### InstanceCreator for a Parameterized Type
|
||||||
|
|
||||||
Sometimes the type that you are trying to instantiate is a parameterized type. Generally, this is not a problem since the actual instance is of raw type. Here is an example:
|
Sometimes the type that you are trying to instantiate is a parameterized type. Generally, this is not a problem since the actual instance is of raw type. Here is an example:
|
||||||
|
|
||||||
|
@ -513,9 +513,9 @@ class IdInstanceCreator implements InstanceCreator<Id<?>> {
|
||||||
|
|
||||||
In the above example, an instance of the Id class can not be created without actually passing in the actual type for the parameterized type. We solve this problem by using the passed method parameter, `type`. The `type` object in this case is the Java parameterized type representation of `Id<Foo>` where the actual instance should be bound to `Id<Foo>`. Since `Id` class has just one parameterized type parameter, `T`, we use the zeroth element of the type array returned by `getActualTypeArgument()` which will hold `Foo.class` in this case.
|
In the above example, an instance of the Id class can not be created without actually passing in the actual type for the parameterized type. We solve this problem by using the passed method parameter, `type`. The `type` object in this case is the Java parameterized type representation of `Id<Foo>` where the actual instance should be bound to `Id<Foo>`. Since `Id` class has just one parameterized type parameter, `T`, we use the zeroth element of the type array returned by `getActualTypeArgument()` which will hold `Foo.class` in this case.
|
||||||
|
|
||||||
### <a name="TOC-Compact-Vs.-Pretty-Printing-for-JSON-Output-Format"></a>Compact Vs. Pretty Printing for JSON Output Format
|
### Compact Vs. Pretty Printing for JSON Output Format
|
||||||
|
|
||||||
The default JSON output that is provided by Gson is a compact JSON format. This means that there will not be any whitespace in the output JSON structure. Therefore, there will be no whitespace between field names and its value, object fields, and objects within arrays in the JSON output. As well, "null" fields will be ignored in the output (NOTE: null values will still be included in collections/arrays of objects). See the [Null Object Support](#TOC-Null-Object-Support) section for information on configure Gson to output all null values.
|
The default JSON output that is provided by Gson is a compact JSON format. This means that there will not be any whitespace in the output JSON structure. Therefore, there will be no whitespace between field names and its value, object fields, and objects within arrays in the JSON output. As well, "null" fields will be ignored in the output (NOTE: null values will still be included in collections/arrays of objects). See the [Null Object Support](#null-object-support) section for information on configure Gson to output all null values.
|
||||||
|
|
||||||
If you would like to use the Pretty Print feature, you must configure your `Gson` instance using the `GsonBuilder`. The `JsonFormatter` is not exposed through our public API, so the client is unable to configure the default print settings/margins for the JSON output. For now, we only provide a default `JsonPrintFormatter` that has default line length of 80 character, 2 character indentation, and 4 character right margin.
|
If you would like to use the Pretty Print feature, you must configure your `Gson` instance using the `GsonBuilder`. The `JsonFormatter` is not exposed through our public API, so the client is unable to configure the default print settings/margins for the JSON output. For now, we only provide a default `JsonPrintFormatter` that has default line length of 80 character, 2 character indentation, and 4 character right margin.
|
||||||
|
|
||||||
|
@ -526,7 +526,7 @@ Gson gson = new GsonBuilder().setPrettyPrinting().create();
|
||||||
String jsonOutput = gson.toJson(someObject);
|
String jsonOutput = gson.toJson(someObject);
|
||||||
```
|
```
|
||||||
|
|
||||||
### <a name="TOC-Null-Object-Support"></a>Null Object Support
|
### Null Object Support
|
||||||
|
|
||||||
The default behaviour that is implemented in Gson is that `null` object fields are ignored. This allows for a more compact output format; however, the client must define a default value for these fields as the JSON format is converted back into its Java form.
|
The default behaviour that is implemented in Gson is that `null` object fields are ignored. This allows for a more compact output format; however, the client must define a default value for these fields as the JSON format is converted back into its Java form.
|
||||||
|
|
||||||
|
@ -566,12 +566,12 @@ System.out.println(json);
|
||||||
|
|
||||||
The output is:
|
The output is:
|
||||||
|
|
||||||
```
|
```json
|
||||||
{"s":null,"i":5}
|
{"s":null,"i":5}
|
||||||
null
|
null
|
||||||
```
|
```
|
||||||
|
|
||||||
### <a name="TOC-Versioning-Support"></a>Versioning Support
|
### Versioning Support
|
||||||
|
|
||||||
Multiple versions of the same object can be maintained by using [@Since](gson/src/main/java/com/google/gson/annotations/Since.java) annotation. This annotation can be used on Classes, Fields and, in a future release, Methods. In order to leverage this feature, you must configure your `Gson` instance to ignore any field/object that is greater than some version number. If no version is set on the `Gson` instance then it will serialize and deserialize all fields and classes regardless of the version.
|
Multiple versions of the same object can be maintained by using [@Since](gson/src/main/java/com/google/gson/annotations/Since.java) annotation. This annotation can be used on Classes, Fields and, in a future release, Methods. In order to leverage this feature, you must configure your `Gson` instance to ignore any field/object that is greater than some version number. If no version is set on the `Gson` instance then it will serialize and deserialize all fields and classes regardless of the version.
|
||||||
|
|
||||||
|
@ -601,17 +601,17 @@ System.out.println(jsonOutput);
|
||||||
|
|
||||||
The output is:
|
The output is:
|
||||||
|
|
||||||
```
|
```json
|
||||||
{"newField":"new","field":"old"}
|
{"newField":"new","field":"old"}
|
||||||
|
|
||||||
{"newerField":"newer","newField":"new","field":"old"}
|
{"newerField":"newer","newField":"new","field":"old"}
|
||||||
```
|
```
|
||||||
|
|
||||||
### <a name="TOC-Excluding-Fields-From-Serialization-and-Deserialization"></a>Excluding Fields From Serialization and Deserialization
|
### Excluding Fields From Serialization and Deserialization
|
||||||
|
|
||||||
Gson supports numerous mechanisms for excluding top-level classes, fields and field types. Below are pluggable mechanisms that allow field and class exclusion. If none of the below mechanisms satisfy your needs then you can always use [custom serializers and deserializers](#TOC-Custom-Serialization-and-Deserialization).
|
Gson supports numerous mechanisms for excluding top-level classes, fields and field types. Below are pluggable mechanisms that allow field and class exclusion. If none of the below mechanisms satisfy your needs then you can always use [custom serializers and deserializers](#custom-serialization-and-deserialization).
|
||||||
|
|
||||||
#### <a name="TOC-Java-Modifier-Exclusion"></a>Java Modifier Exclusion
|
#### Java Modifier Exclusion
|
||||||
|
|
||||||
By default, if you mark a field as `transient`, it will be excluded. As well, if a field is marked as `static` then by default it will be excluded. If you want to include some transient fields then you can do the following:
|
By default, if you mark a field as `transient`, it will be excluded. As well, if a field is marked as `static` then by default it will be excluded. If you want to include some transient fields then you can do the following:
|
||||||
|
|
||||||
|
@ -630,11 +630,11 @@ Gson gson = new GsonBuilder()
|
||||||
.create();
|
.create();
|
||||||
```
|
```
|
||||||
|
|
||||||
#### <a name="TOC-Gson-s-Expose"></a>Gson's `@Expose`
|
#### Gson's `@Expose`
|
||||||
|
|
||||||
This feature provides a way where you can mark certain fields of your objects to be excluded for consideration for serialization and deserialization to JSON. To use this annotation, you must create Gson by using `new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()`. The Gson instance created will exclude all fields in a class that are not marked with `@Expose` annotation.
|
This feature provides a way where you can mark certain fields of your objects to be excluded for consideration for serialization and deserialization to JSON. To use this annotation, you must create Gson by using `new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()`. The Gson instance created will exclude all fields in a class that are not marked with `@Expose` annotation.
|
||||||
|
|
||||||
#### <a name="TOC-User-Defined-Exclusion-Strategies"></a>User Defined Exclusion Strategies
|
#### User Defined Exclusion Strategies
|
||||||
|
|
||||||
If the above mechanisms for excluding fields and class type do not work for you then you can always write your own exclusion strategy and plug it into Gson. See the [`ExclusionStrategy`](https://javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/ExclusionStrategy.html) JavaDoc for more information.
|
If the above mechanisms for excluding fields and class type do not work for you then you can always write your own exclusion strategy and plug it into Gson. See the [`ExclusionStrategy`](https://javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/ExclusionStrategy.html) JavaDoc for more information.
|
||||||
|
|
||||||
|
@ -693,7 +693,7 @@ The output is:
|
||||||
{"longField":1234}
|
{"longField":1234}
|
||||||
```
|
```
|
||||||
|
|
||||||
### <a name="TOC-JSON-Field-Naming-Support"></a>JSON Field Naming Support
|
### JSON Field Naming Support
|
||||||
|
|
||||||
Gson supports some pre-defined field naming policies to convert the standard Java field names (i.e., camel cased names starting with lower case --- `sampleFieldNameInJava`) to a JSON field name (i.e., `sample_field_name_in_java` or `SampleFieldNameInJava`). See the [FieldNamingPolicy](https://javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/FieldNamingPolicy.html) class for information on the pre-defined naming policies.
|
Gson supports some pre-defined field naming policies to convert the standard Java field names (i.e., camel cased names starting with lower case --- `sampleFieldNameInJava`) to a JSON field name (i.e., `sample_field_name_in_java` or `SampleFieldNameInJava`). See the [FieldNamingPolicy](https://javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/FieldNamingPolicy.html) class for information on the pre-defined naming policies.
|
||||||
|
|
||||||
|
@ -726,7 +726,7 @@ The output is:
|
||||||
|
|
||||||
If you have a need for custom naming policy ([see this discussion](https://groups.google.com/group/google-gson/browse_thread/thread/cb441a2d717f6892)), you can use the [@SerializedName](https://javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/annotations/SerializedName.html) annotation.
|
If you have a need for custom naming policy ([see this discussion](https://groups.google.com/group/google-gson/browse_thread/thread/cb441a2d717f6892)), you can use the [@SerializedName](https://javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/annotations/SerializedName.html) annotation.
|
||||||
|
|
||||||
### <a name="TOC-Sharing-State-Across-Custom-Serializers-and-Deserializers"></a>Sharing State Across Custom Serializers and Deserializers
|
### Sharing State Across Custom Serializers and Deserializers
|
||||||
|
|
||||||
Sometimes you need to share state across custom serializers/deserializers ([see this discussion](https://groups.google.com/group/google-gson/browse_thread/thread/2850010691ea09fb)). You can use the following three strategies to accomplish this:
|
Sometimes you need to share state across custom serializers/deserializers ([see this discussion](https://groups.google.com/group/google-gson/browse_thread/thread/2850010691ea09fb)). You can use the following three strategies to accomplish this:
|
||||||
|
|
||||||
|
@ -736,14 +736,14 @@ Sometimes you need to share state across custom serializers/deserializers ([see
|
||||||
|
|
||||||
1 and 2 are not thread-safe options, but 3 is.
|
1 and 2 are not thread-safe options, but 3 is.
|
||||||
|
|
||||||
### <a name="TOC-Streaming"></a>Streaming
|
### Streaming
|
||||||
|
|
||||||
In addition Gson's object model and data binding, you can use Gson to read from and write to a [stream](https://sites.google.com/site/gson/streaming). You can also combine streaming and object model access to get the best of both approaches.
|
In addition Gson's object model and data binding, you can use Gson to read from and write to a [stream](https://sites.google.com/site/gson/streaming). You can also combine streaming and object model access to get the best of both approaches.
|
||||||
|
|
||||||
## <a name="TOC-Issues-in-Designing-Gson"></a>Issues in Designing Gson
|
## Issues in Designing Gson
|
||||||
|
|
||||||
See the [Gson design document](GsonDesignDocument.md "Gson design document") for a discussion of issues we faced while designing Gson. It also include a comparison of Gson with other Java libraries that can be used for JSON conversion.
|
See the [Gson design document](GsonDesignDocument.md "Gson design document") for a discussion of issues we faced while designing Gson. It also include a comparison of Gson with other Java libraries that can be used for JSON conversion.
|
||||||
|
|
||||||
## <a name="TOC-Future-Enhancements-to-Gson"></a>Future Enhancements to Gson
|
## Future Enhancements to Gson
|
||||||
|
|
||||||
For the latest list of proposed enhancements or if you'd like to suggest new ones, see the [Issues section](https://github.com/google/gson/issues) under the project website.
|
For the latest list of proposed enhancements or if you'd like to suggest new ones, see the [Issues section](https://github.com/google/gson/issues) under the project website.
|
||||||
|
|
12
gson/pom.xml
12
gson/pom.xml
|
@ -4,7 +4,7 @@
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>io.gitlab.jfronny</groupId>
|
<groupId>io.gitlab.jfronny</groupId>
|
||||||
<artifactId>gson-parent</artifactId>
|
<artifactId>gson-parent</artifactId>
|
||||||
<version>2.11.0-SNAPSHOT</version>
|
<version>2.10.2-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<artifactId>gson</artifactId>
|
<artifactId>gson</artifactId>
|
||||||
|
@ -23,6 +23,12 @@
|
||||||
<artifactId>junit</artifactId>
|
<artifactId>junit</artifactId>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.google.truth</groupId>
|
||||||
|
<artifactId>truth</artifactId>
|
||||||
|
<version>1.1.3</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
@ -81,7 +87,7 @@
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>biz.aQute.bnd</groupId>
|
<groupId>biz.aQute.bnd</groupId>
|
||||||
<artifactId>bnd-maven-plugin</artifactId>
|
<artifactId>bnd-maven-plugin</artifactId>
|
||||||
<version>6.3.1</version>
|
<version>6.4.0</version>
|
||||||
<executions>
|
<executions>
|
||||||
<execution>
|
<execution>
|
||||||
<goals>
|
<goals>
|
||||||
|
@ -97,7 +103,7 @@
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-surefire-plugin</artifactId>
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
<version>3.0.0-M7</version>
|
<version>3.0.0-M8</version>
|
||||||
<configuration>
|
<configuration>
|
||||||
<!-- Deny illegal access, this is required for ReflectionAccessTest -->
|
<!-- Deny illegal access, this is required for ReflectionAccessTest -->
|
||||||
<!-- Requires Java >= 9; Important: In case future Java versions
|
<!-- Requires Java >= 9; Important: In case future Java versions
|
||||||
|
|
|
@ -135,14 +135,18 @@ import java.util.concurrent.atomic.AtomicLongArray;
|
||||||
*/
|
*/
|
||||||
public final class Gson {
|
public final class Gson {
|
||||||
/**
|
/**
|
||||||
* This thread local guards against reentrant calls to getAdapter(). In
|
* This thread local guards against reentrant calls to {@link #getAdapter(TypeToken)}.
|
||||||
* certain object graphs, creating an adapter for a type may recursively
|
* In certain object graphs, creating an adapter for a type may recursively
|
||||||
* require an adapter for the same type! Without intervention, the recursive
|
* require an adapter for the same type! Without intervention, the recursive
|
||||||
* lookup would stack overflow. We cheat by returning a proxy type adapter.
|
* lookup would stack overflow. We cheat by returning a proxy type adapter,
|
||||||
* The proxy is wired up once the initial adapter has been created.
|
* {@link FutureTypeAdapter}, which is wired up once the initial adapter has
|
||||||
|
* been created.
|
||||||
|
*
|
||||||
|
* <p>The map stores the type adapters for ongoing {@code getAdapter} calls,
|
||||||
|
* with the type token provided to {@code getAdapter} as key and either
|
||||||
|
* {@code FutureTypeAdapter} or a regular {@code TypeAdapter} as value.
|
||||||
*/
|
*/
|
||||||
private final ThreadLocal<Map<TypeToken<?>, FutureTypeAdapter<?>>> calls
|
private final ThreadLocal<Map<TypeToken<?>, TypeAdapter<?>>> threadLocalAdapterResults = new ThreadLocal<>();
|
||||||
= new ThreadLocal<>();
|
|
||||||
|
|
||||||
private final ConcurrentMap<TypeToken<?>, TypeAdapter<?>> typeTokenCache = new ConcurrentHashMap<>();
|
private final ConcurrentMap<TypeToken<?>, TypeAdapter<?>> typeTokenCache = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
@ -484,9 +488,14 @@ public final class Gson {
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the type adapter for {@code} type.
|
* Returns the type adapter for {@code type}.
|
||||||
*
|
*
|
||||||
* @throws IllegalArgumentException if this GSON cannot serialize and
|
* <p>When calling this method concurrently from multiple threads and requesting
|
||||||
|
* an adapter for the same type this method may return different {@code TypeAdapter}
|
||||||
|
* instances. However, that should normally not be an issue because {@code TypeAdapter}
|
||||||
|
* implementations are supposed to be stateless.
|
||||||
|
*
|
||||||
|
* @throws IllegalArgumentException if this Gson instance cannot serialize and
|
||||||
* deserialize {@code type}.
|
* deserialize {@code type}.
|
||||||
*/
|
*/
|
||||||
public <T> TypeAdapter<T> getAdapter(TypeToken<T> type) {
|
public <T> TypeAdapter<T> getAdapter(TypeToken<T> type) {
|
||||||
|
@ -498,47 +507,55 @@ public final class Gson {
|
||||||
return adapter;
|
return adapter;
|
||||||
}
|
}
|
||||||
|
|
||||||
Map<TypeToken<?>, FutureTypeAdapter<?>> threadCalls = calls.get();
|
Map<TypeToken<?>, TypeAdapter<?>> threadCalls = threadLocalAdapterResults.get();
|
||||||
boolean requiresThreadLocalCleanup = false;
|
boolean isInitialAdapterRequest = false;
|
||||||
if (threadCalls == null) {
|
if (threadCalls == null) {
|
||||||
threadCalls = new HashMap<>();
|
threadCalls = new HashMap<>();
|
||||||
calls.set(threadCalls);
|
threadLocalAdapterResults.set(threadCalls);
|
||||||
requiresThreadLocalCleanup = true;
|
isInitialAdapterRequest = true;
|
||||||
}
|
} else {
|
||||||
|
|
||||||
// the key and value type parameters always agree
|
// the key and value type parameters always agree
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
FutureTypeAdapter<T> ongoingCall = (FutureTypeAdapter<T>) threadCalls.get(type);
|
TypeAdapter<T> ongoingCall = (TypeAdapter<T>) threadCalls.get(type);
|
||||||
if (ongoingCall != null) {
|
if (ongoingCall != null) {
|
||||||
return ongoingCall;
|
return ongoingCall;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
TypeAdapter<T> candidate = null;
|
||||||
try {
|
try {
|
||||||
FutureTypeAdapter<T> call = new FutureTypeAdapter<>();
|
FutureTypeAdapter<T> call = new FutureTypeAdapter<>();
|
||||||
threadCalls.put(type, call);
|
threadCalls.put(type, call);
|
||||||
|
|
||||||
for (TypeAdapterFactory factory : factories) {
|
for (TypeAdapterFactory factory : factories) {
|
||||||
TypeAdapter<T> candidate = factory.create(this, type);
|
candidate = factory.create(this, type);
|
||||||
if (candidate != null) {
|
if (candidate != null) {
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
TypeAdapter<T> existingAdapter = (TypeAdapter<T>) typeTokenCache.putIfAbsent(type, candidate);
|
|
||||||
// If other thread concurrently added adapter prefer that one instead
|
|
||||||
if (existingAdapter != null) {
|
|
||||||
candidate = existingAdapter;
|
|
||||||
}
|
|
||||||
|
|
||||||
call.setDelegate(candidate);
|
call.setDelegate(candidate);
|
||||||
return candidate;
|
// Replace future adapter with actual adapter
|
||||||
|
threadCalls.put(type, candidate);
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
throw new IllegalArgumentException("GSON (" + GsonBuildConfig.VERSION + ") cannot handle " + type);
|
|
||||||
} finally {
|
} finally {
|
||||||
threadCalls.remove(type);
|
if (isInitialAdapterRequest) {
|
||||||
|
threadLocalAdapterResults.remove();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (requiresThreadLocalCleanup) {
|
if (candidate == null) {
|
||||||
calls.remove();
|
throw new IllegalArgumentException("GSON (" + GsonBuildConfig.VERSION + ") cannot handle " + type);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (isInitialAdapterRequest) {
|
||||||
|
/*
|
||||||
|
* Publish resolved adapters to all threads
|
||||||
|
* Can only do this for the initial request because cyclic dependency TypeA -> TypeB -> TypeA
|
||||||
|
* would otherwise publish adapter for TypeB which uses not yet resolved adapter for TypeA
|
||||||
|
* See https://github.com/google/gson/issues/625
|
||||||
|
*/
|
||||||
|
typeTokenCache.putAll(threadCalls);
|
||||||
}
|
}
|
||||||
|
return candidate;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -616,9 +633,9 @@ public final class Gson {
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the type adapter for {@code} type.
|
* Returns the type adapter for {@code type}.
|
||||||
*
|
*
|
||||||
* @throws IllegalArgumentException if this GSON cannot serialize and
|
* @throws IllegalArgumentException if this Gson instance cannot serialize and
|
||||||
* deserialize {@code type}.
|
* deserialize {@code type}.
|
||||||
*/
|
*/
|
||||||
public <T> TypeAdapter<T> getAdapter(Class<T> type) {
|
public <T> TypeAdapter<T> getAdapter(Class<T> type) {
|
||||||
|
@ -803,9 +820,7 @@ public final class Gson {
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
throw new JsonIOException(e);
|
throw new JsonIOException(e);
|
||||||
} catch (AssertionError e) {
|
} catch (AssertionError e) {
|
||||||
AssertionError error = new AssertionError("AssertionError (GSON " + GsonBuildConfig.VERSION + "): " + e.getMessage());
|
throw new AssertionError("AssertionError (GSON " + GsonBuildConfig.VERSION + "): " + e.getMessage(), e);
|
||||||
error.initCause(e);
|
|
||||||
throw error;
|
|
||||||
} finally {
|
} finally {
|
||||||
writer.setLenient(oldLenient);
|
writer.setLenient(oldLenient);
|
||||||
writer.setOmitQuotes(oldOmitQuotes);
|
writer.setOmitQuotes(oldOmitQuotes);
|
||||||
|
@ -915,9 +930,7 @@ public final class Gson {
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
throw new JsonIOException(e);
|
throw new JsonIOException(e);
|
||||||
} catch (AssertionError e) {
|
} catch (AssertionError e) {
|
||||||
AssertionError error = new AssertionError("AssertionError (GSON " + GsonBuildConfig.VERSION + "): " + e.getMessage());
|
throw new AssertionError("AssertionError (GSON " + GsonBuildConfig.VERSION + "): " + e.getMessage(), e);
|
||||||
error.initCause(e);
|
|
||||||
throw error;
|
|
||||||
} finally {
|
} finally {
|
||||||
writer.setLenient(oldLenient);
|
writer.setLenient(oldLenient);
|
||||||
writer.setOmitQuotes(oldOmitQuotes);
|
writer.setOmitQuotes(oldOmitQuotes);
|
||||||
|
@ -1196,8 +1209,7 @@ public final class Gson {
|
||||||
reader.peek();
|
reader.peek();
|
||||||
isEmpty = false;
|
isEmpty = false;
|
||||||
TypeAdapter<T> typeAdapter = getAdapter(typeOfT);
|
TypeAdapter<T> typeAdapter = getAdapter(typeOfT);
|
||||||
T object = typeAdapter.read(reader);
|
return typeAdapter.read(reader);
|
||||||
return object;
|
|
||||||
} catch (EOFException e) {
|
} catch (EOFException e) {
|
||||||
/*
|
/*
|
||||||
* For compatibility with JSON 1.5 and earlier, we return null for empty
|
* For compatibility with JSON 1.5 and earlier, we return null for empty
|
||||||
|
@ -1213,9 +1225,7 @@ public final class Gson {
|
||||||
// TODO(inder): Figure out whether it is indeed right to rethrow this as JsonSyntaxException
|
// TODO(inder): Figure out whether it is indeed right to rethrow this as JsonSyntaxException
|
||||||
throw new JsonSyntaxException(e);
|
throw new JsonSyntaxException(e);
|
||||||
} catch (AssertionError e) {
|
} catch (AssertionError e) {
|
||||||
AssertionError error = new AssertionError("AssertionError (GSON " + GsonBuildConfig.VERSION + "): " + e.getMessage());
|
throw new AssertionError("AssertionError (GSON " + GsonBuildConfig.VERSION + "): " + e.getMessage(), e);
|
||||||
error.initCause(e);
|
|
||||||
throw error;
|
|
||||||
} finally {
|
} finally {
|
||||||
reader.setLenient(oldLenient);
|
reader.setLenient(oldLenient);
|
||||||
}
|
}
|
||||||
|
@ -1304,19 +1314,32 @@ public final class Gson {
|
||||||
return fromJson(new JsonTreeReader(json), typeOfT);
|
return fromJson(new JsonTreeReader(json), typeOfT);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Proxy type adapter for cyclic type graphs.
|
||||||
|
*
|
||||||
|
* <p><b>Important:</b> Setting the delegate adapter is not thread-safe; instances of
|
||||||
|
* {@code FutureTypeAdapter} must only be published to other threads after the delegate
|
||||||
|
* has been set.
|
||||||
|
*
|
||||||
|
* @see Gson#threadLocalAdapterResults
|
||||||
|
*/
|
||||||
static class FutureTypeAdapter<T> extends SerializationDelegatingTypeAdapter<T> {
|
static class FutureTypeAdapter<T> extends SerializationDelegatingTypeAdapter<T> {
|
||||||
private TypeAdapter<T> delegate;
|
private TypeAdapter<T> delegate = null;
|
||||||
|
|
||||||
public void setDelegate(TypeAdapter<T> typeAdapter) {
|
public void setDelegate(TypeAdapter<T> typeAdapter) {
|
||||||
if (delegate != null) {
|
if (delegate != null) {
|
||||||
throw new AssertionError();
|
throw new AssertionError("Delegate is already set");
|
||||||
}
|
}
|
||||||
delegate = typeAdapter;
|
delegate = typeAdapter;
|
||||||
}
|
}
|
||||||
|
|
||||||
private TypeAdapter<T> delegate() {
|
private TypeAdapter<T> delegate() {
|
||||||
|
TypeAdapter<T> delegate = this.delegate;
|
||||||
if (delegate == null) {
|
if (delegate == null) {
|
||||||
throw new IllegalStateException("Delegate has not been set yet");
|
// Can occur when adapter is leaked to other thread or when adapter is used for (de-)serialization
|
||||||
|
// directly within the TypeAdapterFactory which requested it
|
||||||
|
throw new IllegalStateException("Adapter for type with cyclic dependency has been used"
|
||||||
|
+ " before dependency has been resolved");
|
||||||
}
|
}
|
||||||
return delegate;
|
return delegate;
|
||||||
}
|
}
|
||||||
|
@ -1336,11 +1359,9 @@ public final class Gson {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return new StringBuilder("{serializeNulls:")
|
return "{serializeNulls:" + serializeNulls
|
||||||
.append(serializeNulls)
|
+ ",factories:" + factories
|
||||||
.append(",factories:").append(factories)
|
+ ",instanceCreators:" + constructorConstructor
|
||||||
.append(",instanceCreators:").append(constructorConstructor)
|
+ "}";
|
||||||
.append("}")
|
|
||||||
.toString();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -63,6 +63,9 @@ import java.lang.reflect.Type;
|
||||||
* Gson gson = new GsonBuilder().registerTypeAdapter(Id.class, new IdDeserializer()).create();
|
* Gson gson = new GsonBuilder().registerTypeAdapter(Id.class, new IdDeserializer()).create();
|
||||||
* </pre>
|
* </pre>
|
||||||
*
|
*
|
||||||
|
* <p>Deserializers should be stateless and thread-safe, otherwise the thread-safety
|
||||||
|
* guarantees of {@link Gson} might not apply.
|
||||||
|
*
|
||||||
* <p>New applications should prefer {@link TypeAdapter}, whose streaming API
|
* <p>New applications should prefer {@link TypeAdapter}, whose streaming API
|
||||||
* is more efficient than this interface's tree API.
|
* is more efficient than this interface's tree API.
|
||||||
*
|
*
|
||||||
|
@ -80,7 +83,7 @@ public interface JsonDeserializer<T> {
|
||||||
* <p>In the implementation of this call-back method, you should consider invoking
|
* <p>In the implementation of this call-back method, you should consider invoking
|
||||||
* {@link JsonDeserializationContext#deserialize(JsonElement, Type)} method to create objects
|
* {@link JsonDeserializationContext#deserialize(JsonElement, Type)} method to create objects
|
||||||
* for any non-trivial field of the returned object. However, you should never invoke it on the
|
* for any non-trivial field of the returned object. However, you should never invoke it on the
|
||||||
* the same type passing {@code json} since that will cause an infinite loop (Gson will call your
|
* same type passing {@code json} since that will cause an infinite loop (Gson will call your
|
||||||
* call-back method again).
|
* call-back method again).
|
||||||
*
|
*
|
||||||
* @param json The Json data being deserialized
|
* @param json The Json data being deserialized
|
||||||
|
|
|
@ -64,6 +64,6 @@ public final class JsonNull extends JsonElement {
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public boolean equals(Object other) {
|
public boolean equals(Object other) {
|
||||||
return this == other || other instanceof JsonNull;
|
return other instanceof JsonNull;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -159,7 +159,7 @@ public final class JsonObject extends JsonElement {
|
||||||
* Returns true if the number of key/value pairs in the object is zero.
|
* Returns true if the number of key/value pairs in the object is zero.
|
||||||
*
|
*
|
||||||
* @return true if the number of key/value pairs in the object is zero.
|
* @return true if the number of key/value pairs in the object is zero.
|
||||||
* @since $next-version$
|
* @since 2.10.1
|
||||||
*/
|
*/
|
||||||
public boolean isEmpty() {
|
public boolean isEmpty() {
|
||||||
return members.size() == 0;
|
return members.size() == 0;
|
||||||
|
|
|
@ -104,7 +104,7 @@ public final class JsonPrimitive extends JsonElement {
|
||||||
@Override
|
@Override
|
||||||
public boolean getAsBoolean() {
|
public boolean getAsBoolean() {
|
||||||
if (isBoolean()) {
|
if (isBoolean()) {
|
||||||
return ((Boolean) value).booleanValue();
|
return (Boolean) value;
|
||||||
}
|
}
|
||||||
// Check to see if the value as a String is "true" in any case.
|
// Check to see if the value as a String is "true" in any case.
|
||||||
return Boolean.parseBoolean(getAsString());
|
return Boolean.parseBoolean(getAsString());
|
||||||
|
|
|
@ -60,6 +60,9 @@ import java.lang.reflect.Type;
|
||||||
* Gson gson = new GsonBuilder().registerTypeAdapter(Id.class, new IdSerializer()).create();
|
* Gson gson = new GsonBuilder().registerTypeAdapter(Id.class, new IdSerializer()).create();
|
||||||
* </pre>
|
* </pre>
|
||||||
*
|
*
|
||||||
|
* <p>Serializers should be stateless and thread-safe, otherwise the thread-safety
|
||||||
|
* guarantees of {@link Gson} might not apply.
|
||||||
|
*
|
||||||
* <p>New applications should prefer {@link TypeAdapter}, whose streaming API
|
* <p>New applications should prefer {@link TypeAdapter}, whose streaming API
|
||||||
* is more efficient than this interface's tree API.
|
* is more efficient than this interface's tree API.
|
||||||
*
|
*
|
||||||
|
|
|
@ -15,18 +15,16 @@
|
||||||
*/
|
*/
|
||||||
package com.google.gson;
|
package com.google.gson;
|
||||||
|
|
||||||
import java.io.EOFException;
|
import com.google.gson.internal.Streams;
|
||||||
|
import com.google.gson.stream.JsonReader;
|
||||||
|
import com.google.gson.stream.JsonToken;
|
||||||
|
import com.google.gson.stream.MalformedJsonException;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.Reader;
|
import java.io.Reader;
|
||||||
import java.io.StringReader;
|
import java.io.StringReader;
|
||||||
import java.util.Iterator;
|
import java.util.Iterator;
|
||||||
import java.util.NoSuchElementException;
|
import java.util.NoSuchElementException;
|
||||||
|
|
||||||
import com.google.gson.internal.Streams;
|
|
||||||
import com.google.gson.stream.JsonReader;
|
|
||||||
import com.google.gson.stream.JsonToken;
|
|
||||||
import com.google.gson.stream.MalformedJsonException;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A streaming parser that allows reading of multiple {@link JsonElement}s from the specified reader
|
* A streaming parser that allows reading of multiple {@link JsonElement}s from the specified reader
|
||||||
* asynchronously. The JSON data is parsed in lenient mode, see also
|
* asynchronously. The JSON data is parsed in lenient mode, see also
|
||||||
|
@ -77,7 +75,7 @@ public final class JsonStreamParser implements Iterator<JsonElement> {
|
||||||
* {@link NoSuchElementException} if no element is available.
|
* {@link NoSuchElementException} if no element is available.
|
||||||
*
|
*
|
||||||
* @return the next available {@code JsonElement} on the reader.
|
* @return the next available {@code JsonElement} on the reader.
|
||||||
* @throws JsonSyntaxException if the incoming stream is malformed JSON.
|
* @throws JsonParseException if the incoming stream is malformed JSON.
|
||||||
* @throws NoSuchElementException if no {@code JsonElement} is available.
|
* @throws NoSuchElementException if no {@code JsonElement} is available.
|
||||||
* @since 1.4
|
* @since 1.4
|
||||||
*/
|
*/
|
||||||
|
@ -93,15 +91,13 @@ public final class JsonStreamParser implements Iterator<JsonElement> {
|
||||||
throw new JsonParseException("Failed parsing JSON source to Json", e);
|
throw new JsonParseException("Failed parsing JSON source to Json", e);
|
||||||
} catch (OutOfMemoryError e) {
|
} catch (OutOfMemoryError e) {
|
||||||
throw new JsonParseException("Failed parsing JSON source to Json", e);
|
throw new JsonParseException("Failed parsing JSON source to Json", e);
|
||||||
} catch (JsonParseException e) {
|
|
||||||
throw e.getCause() instanceof EOFException ? new NoSuchElementException() : e;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns true if a {@link JsonElement} is available on the input for consumption
|
* Returns true if a {@link JsonElement} is available on the input for consumption
|
||||||
* @return true if a {@link JsonElement} is available on the input, false otherwise
|
* @return true if a {@link JsonElement} is available on the input, false otherwise
|
||||||
* @throws JsonSyntaxException if the incoming stream is malformed JSON.
|
* @throws JsonParseException if the incoming stream is malformed JSON.
|
||||||
* @since 1.4
|
* @since 1.4
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
|
|
|
@ -81,6 +81,9 @@ import java.io.Writer;
|
||||||
* when writing to a JSON object) will be omitted automatically. In either case
|
* when writing to a JSON object) will be omitted automatically. In either case
|
||||||
* your type adapter must handle null.
|
* your type adapter must handle null.
|
||||||
*
|
*
|
||||||
|
* <p>Type adapters should be stateless and thread-safe, otherwise the thread-safety
|
||||||
|
* guarantees of {@link Gson} might not apply.
|
||||||
|
*
|
||||||
* <p>To use a custom type adapter with Gson, you must <i>register</i> it with a
|
* <p>To use a custom type adapter with Gson, you must <i>register</i> it with a
|
||||||
* {@link GsonBuilder}: <pre> {@code
|
* {@link GsonBuilder}: <pre> {@code
|
||||||
*
|
*
|
||||||
|
|
|
@ -34,6 +34,7 @@ import java.util.HashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.NoSuchElementException;
|
import java.util.NoSuchElementException;
|
||||||
import java.util.Properties;
|
import java.util.Properties;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Static methods for working with types.
|
* Static methods for working with types.
|
||||||
|
@ -167,7 +168,7 @@ public final class $Gson$Types {
|
||||||
}
|
}
|
||||||
|
|
||||||
private static boolean equal(Object a, Object b) {
|
private static boolean equal(Object a, Object b) {
|
||||||
return a == b || (a != null && a.equals(b));
|
return Objects.equals(a, b);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
@ -198,11 +198,7 @@ public final class Excluder implements TypeAdapterFactory, Cloneable {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isAnonymousOrNonStaticLocal(clazz)) {
|
return isAnonymousOrNonStaticLocal(clazz);
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean excludeClass(Class<?> clazz, boolean serialize) {
|
public boolean excludeClass(Class<?> clazz, boolean serialize) {
|
||||||
|
|
|
@ -30,6 +30,7 @@ import java.util.Iterator;
|
||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.NoSuchElementException;
|
import java.util.NoSuchElementException;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A map of comparable keys to values. Unlike {@code TreeMap}, this class uses
|
* A map of comparable keys to values. Unlike {@code TreeMap}, this class uses
|
||||||
|
@ -227,7 +228,7 @@ public final class LinkedTreeMap<K, V> extends AbstractMap<K, V> implements Seri
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean equal(Object a, Object b) {
|
private boolean equal(Object a, Object b) {
|
||||||
return a == b || (a != null && a.equals(b));
|
return Objects.equals(a, b);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
@ -62,7 +62,7 @@ public final class DefaultDateTypeAdapter<T extends Date> extends TypeAdapter<T>
|
||||||
|
|
||||||
protected abstract T deserialize(Date date);
|
protected abstract T deserialize(Date date);
|
||||||
|
|
||||||
private final TypeAdapterFactory createFactory(DefaultDateTypeAdapter<T> adapter) {
|
private TypeAdapterFactory createFactory(DefaultDateTypeAdapter<T> adapter) {
|
||||||
return TypeAdapters.newFactory(dateClass, adapter);
|
return TypeAdapters.newFactory(dateClass, adapter);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -38,10 +38,10 @@ import java.util.Map;
|
||||||
*/
|
*/
|
||||||
public final class JsonTreeReader extends JsonReader {
|
public final class JsonTreeReader extends JsonReader {
|
||||||
private static final Reader UNREADABLE_READER = new Reader() {
|
private static final Reader UNREADABLE_READER = new Reader() {
|
||||||
@Override public int read(char[] buffer, int offset, int count) throws IOException {
|
@Override public int read(char[] buffer, int offset, int count) {
|
||||||
throw new AssertionError();
|
throw new AssertionError();
|
||||||
}
|
}
|
||||||
@Override public void close() throws IOException {
|
@Override public void close() {
|
||||||
throw new AssertionError();
|
throw new AssertionError();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
|
@ -36,10 +36,10 @@ public final class JsonTreeWriter extends JsonWriter {
|
||||||
@Override public void write(char[] buffer, int offset, int counter) {
|
@Override public void write(char[] buffer, int offset, int counter) {
|
||||||
throw new AssertionError();
|
throw new AssertionError();
|
||||||
}
|
}
|
||||||
@Override public void flush() throws IOException {
|
@Override public void flush() {
|
||||||
throw new AssertionError();
|
throw new AssertionError();
|
||||||
}
|
}
|
||||||
@Override public void close() throws IOException {
|
@Override public void close() {
|
||||||
throw new AssertionError();
|
throw new AssertionError();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
|
@ -139,7 +139,7 @@ public final class ReflectiveTypeAdapterFactory implements TypeAdapterFactory {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private ReflectiveTypeAdapterFactory.BoundField createBoundField(
|
private BoundField createBoundField(
|
||||||
final Gson context, final Field field, final Method accessor, final String name,
|
final Gson context, final Field field, final Method accessor, final String name,
|
||||||
final TypeToken<?> fieldType, boolean serialize, boolean deserialize,
|
final TypeToken<?> fieldType, boolean serialize, boolean deserialize,
|
||||||
final boolean blockInaccessible) {
|
final boolean blockInaccessible) {
|
||||||
|
@ -161,7 +161,7 @@ public final class ReflectiveTypeAdapterFactory implements TypeAdapterFactory {
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
final TypeAdapter<Object> typeAdapter = (TypeAdapter<Object>) mapped;
|
final TypeAdapter<Object> typeAdapter = (TypeAdapter<Object>) mapped;
|
||||||
return new ReflectiveTypeAdapterFactory.BoundField(name, field.getName(), serialize, deserialize) {
|
return new BoundField(name, field, serialize, deserialize) {
|
||||||
@Override void write(JsonWriter writer, Object source)
|
@Override void write(JsonWriter writer, Object source)
|
||||||
throws IOException, IllegalAccessException {
|
throws IOException, IllegalAccessException {
|
||||||
if (!serialized) return;
|
if (!serialized) return;
|
||||||
|
@ -232,7 +232,6 @@ public final class ReflectiveTypeAdapterFactory implements TypeAdapterFactory {
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
Type declaredType = type.getType();
|
|
||||||
Class<?> originalRaw = raw;
|
Class<?> originalRaw = raw;
|
||||||
while (raw != Object.class) {
|
while (raw != Object.class) {
|
||||||
Field[] fields = raw.getDeclaredFields();
|
Field[] fields = raw.getDeclaredFields();
|
||||||
|
@ -298,8 +297,9 @@ public final class ReflectiveTypeAdapterFactory implements TypeAdapterFactory {
|
||||||
if (previous == null) previous = replaced;
|
if (previous == null) previous = replaced;
|
||||||
}
|
}
|
||||||
if (previous != null) {
|
if (previous != null) {
|
||||||
throw new IllegalArgumentException(declaredType
|
throw new IllegalArgumentException("Class " + originalRaw.getName()
|
||||||
+ " declares multiple JSON fields named " + previous.name);
|
+ " declares multiple JSON fields named '" + previous.name + "'; conflict is caused"
|
||||||
|
+ " by fields " + ReflectionHelper.fieldToString(previous.field) + " and " + ReflectionHelper.fieldToString(field));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
type = TypeToken.get($Gson$Types.resolve(type.getType(), raw, raw.getGenericSuperclass()));
|
type = TypeToken.get($Gson$Types.resolve(type.getType(), raw, raw.getGenericSuperclass()));
|
||||||
|
@ -310,14 +310,16 @@ public final class ReflectiveTypeAdapterFactory implements TypeAdapterFactory {
|
||||||
|
|
||||||
static abstract class BoundField {
|
static abstract class BoundField {
|
||||||
final String name;
|
final String name;
|
||||||
|
final Field field;
|
||||||
/** Name of the underlying field */
|
/** Name of the underlying field */
|
||||||
final String fieldName;
|
final String fieldName;
|
||||||
final boolean serialized;
|
final boolean serialized;
|
||||||
final boolean deserialized;
|
final boolean deserialized;
|
||||||
|
|
||||||
protected BoundField(String name, String fieldName, boolean serialized, boolean deserialized) {
|
protected BoundField(String name, Field field, boolean serialized, boolean deserialized) {
|
||||||
this.name = name;
|
this.name = name;
|
||||||
this.fieldName = fieldName;
|
this.field = field;
|
||||||
|
this.fieldName = field.getName();
|
||||||
this.serialized = serialized;
|
this.serialized = serialized;
|
||||||
this.deserialized = deserialized;
|
this.deserialized = deserialized;
|
||||||
}
|
}
|
||||||
|
|
|
@ -176,7 +176,7 @@ public final class TreeTypeAdapter<T> extends SerializationDelegatingTypeAdapter
|
||||||
}
|
}
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
@Override public <R> R deserialize(JsonElement json, Type typeOfT) throws JsonParseException {
|
@Override public <R> R deserialize(JsonElement json, Type typeOfT) throws JsonParseException {
|
||||||
return (R) gson.fromJson(json, typeOfT);
|
return gson.fromJson(json, typeOfT);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -53,8 +53,7 @@ public class ReflectionHelper {
|
||||||
String description;
|
String description;
|
||||||
|
|
||||||
if (object instanceof Field) {
|
if (object instanceof Field) {
|
||||||
Field field = (Field) object;
|
description = "field '" + fieldToString((Field) object) + "'";
|
||||||
description = "field '" + field.getDeclaringClass().getName() + "#" + field.getName() + "'";
|
|
||||||
} else if (object instanceof Method) {
|
} else if (object instanceof Method) {
|
||||||
Method method = (Method) object;
|
Method method = (Method) object;
|
||||||
|
|
||||||
|
@ -75,6 +74,14 @@ public class ReflectionHelper {
|
||||||
return description;
|
return description;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a string representation for a field, omitting modifiers and
|
||||||
|
* the field type.
|
||||||
|
*/
|
||||||
|
public static String fieldToString(Field field) {
|
||||||
|
return field.getDeclaringClass().getName() + "#" + field.getName();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a string representation for a constructor.
|
* Creates a string representation for a constructor.
|
||||||
* E.g.: {@code java.lang.String(char[], int, int)}
|
* E.g.: {@code java.lang.String(char[], int, int)}
|
||||||
|
|
|
@ -759,7 +759,9 @@ public class JsonReader implements Closeable {
|
||||||
}
|
}
|
||||||
|
|
||||||
// We've read a complete number. Decide if it's a PEEKED_LONG or a PEEKED_NUMBER.
|
// We've read a complete number. Decide if it's a PEEKED_LONG or a PEEKED_NUMBER.
|
||||||
if (last == NUMBER_CHAR_DIGIT && fitsInLong && (value != Long.MIN_VALUE || negative) && (value!=0 || false==negative)) {
|
// Don't store -0 as long; user might want to read it as double -0.0
|
||||||
|
// Don't try to convert Long.MIN_VALUE to positive long; it would overflow MAX_VALUE
|
||||||
|
if (last == NUMBER_CHAR_DIGIT && fitsInLong && (value != Long.MIN_VALUE || negative) && (value!=0 || !negative)) {
|
||||||
peekedLong = negative ? value : -value;
|
peekedLong = negative ? value : -value;
|
||||||
pos += i;
|
pos += i;
|
||||||
return peeked = PEEKED_LONG;
|
return peeked = PEEKED_LONG;
|
||||||
|
@ -1571,7 +1573,7 @@ public class JsonReader implements Closeable {
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns a <a href="https://goessner.net/articles/JsonPath/">JsonPath</a>
|
* Returns a <a href="https://goessner.net/articles/JsonPath/">JSONPath</a>
|
||||||
* in <i>dot-notation</i> to the previous (or current) location in the JSON document:
|
* in <i>dot-notation</i> to the previous (or current) location in the JSON document:
|
||||||
* <ul>
|
* <ul>
|
||||||
* <li>For JSON arrays the path points to the index of the previous element.<br>
|
* <li>For JSON arrays the path points to the index of the previous element.<br>
|
||||||
|
@ -1588,7 +1590,7 @@ public class JsonReader implements Closeable {
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns a <a href="https://goessner.net/articles/JsonPath/">JsonPath</a>
|
* Returns a <a href="https://goessner.net/articles/JsonPath/">JSONPath</a>
|
||||||
* in <i>dot-notation</i> to the next (or current) location in the JSON document:
|
* in <i>dot-notation</i> to the next (or current) location in the JSON document:
|
||||||
* <ul>
|
* <ul>
|
||||||
* <li>For JSON arrays the path points to the index of the next element (even
|
* <li>For JSON arrays the path points to the index of the next element (even
|
||||||
|
|
|
@ -16,30 +16,32 @@
|
||||||
|
|
||||||
package com.google.gson;
|
package com.google.gson;
|
||||||
|
|
||||||
import java.net.InetAddress;
|
import static com.google.common.truth.Truth.assertThat;
|
||||||
|
|
||||||
import junit.framework.TestCase;
|
import java.net.InetAddress;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Unit tests for the default serializer/deserializer for the {@code InetAddress} type.
|
* Unit tests for the default serializer/deserializer for the {@code InetAddress} type.
|
||||||
*
|
*
|
||||||
* @author Joel Leitch
|
* @author Joel Leitch
|
||||||
*/
|
*/
|
||||||
public class DefaultInetAddressTypeAdapterTest extends TestCase {
|
public class DefaultInetAddressTypeAdapterTest {
|
||||||
private Gson gson;
|
private Gson gson;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
gson = new Gson();
|
gson = new Gson();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testInetAddressSerializationAndDeserialization() throws Exception {
|
public void testInetAddressSerializationAndDeserialization() throws Exception {
|
||||||
InetAddress address = InetAddress.getByName("8.8.8.8");
|
InetAddress address = InetAddress.getByName("8.8.8.8");
|
||||||
String jsonAddress = gson.toJson(address);
|
String jsonAddress = gson.toJson(address);
|
||||||
assertEquals("\"8.8.8.8\"", jsonAddress);
|
assertThat(jsonAddress).isEqualTo("\"8.8.8.8\"");
|
||||||
|
|
||||||
InetAddress value = gson.fromJson(jsonAddress, InetAddress.class);
|
InetAddress value = gson.fromJson(jsonAddress, InetAddress.class);
|
||||||
assertEquals(value, address);
|
assertThat(address).isEqualTo(value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -16,11 +16,13 @@
|
||||||
|
|
||||||
package com.google.gson;
|
package com.google.gson;
|
||||||
|
|
||||||
|
import static com.google.common.truth.Truth.assertThat;
|
||||||
|
|
||||||
import com.google.gson.reflect.TypeToken;
|
import com.google.gson.reflect.TypeToken;
|
||||||
import java.lang.reflect.Type;
|
import java.lang.reflect.Type;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import junit.framework.TestCase;
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Unit test for the default JSON map serialization object located in the
|
* Unit test for the default JSON map serialization object located in the
|
||||||
|
@ -28,27 +30,30 @@ import junit.framework.TestCase;
|
||||||
*
|
*
|
||||||
* @author Joel Leitch
|
* @author Joel Leitch
|
||||||
*/
|
*/
|
||||||
public class DefaultMapJsonSerializerTest extends TestCase {
|
public class DefaultMapJsonSerializerTest {
|
||||||
private Gson gson = new Gson();
|
private Gson gson = new Gson();
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testEmptyMapNoTypeSerialization() {
|
public void testEmptyMapNoTypeSerialization() {
|
||||||
Map<String, String> emptyMap = new HashMap<>();
|
Map<String, String> emptyMap = new HashMap<>();
|
||||||
JsonElement element = gson.toJsonTree(emptyMap, emptyMap.getClass());
|
JsonElement element = gson.toJsonTree(emptyMap, emptyMap.getClass());
|
||||||
assertTrue(element instanceof JsonObject);
|
assertThat(element).isInstanceOf(JsonObject.class);
|
||||||
JsonObject emptyMapJsonObject = (JsonObject) element;
|
JsonObject emptyMapJsonObject = (JsonObject) element;
|
||||||
assertTrue(emptyMapJsonObject.entrySet().isEmpty());
|
assertThat(emptyMapJsonObject.entrySet()).isEmpty();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testEmptyMapSerialization() {
|
public void testEmptyMapSerialization() {
|
||||||
Type mapType = new TypeToken<Map<String, String>>() { }.getType();
|
Type mapType = new TypeToken<Map<String, String>>() { }.getType();
|
||||||
Map<String, String> emptyMap = new HashMap<>();
|
Map<String, String> emptyMap = new HashMap<>();
|
||||||
JsonElement element = gson.toJsonTree(emptyMap, mapType);
|
JsonElement element = gson.toJsonTree(emptyMap, mapType);
|
||||||
|
|
||||||
assertTrue(element instanceof JsonObject);
|
assertThat(element).isInstanceOf(JsonObject.class);
|
||||||
JsonObject emptyMapJsonObject = (JsonObject) element;
|
JsonObject emptyMapJsonObject = (JsonObject) element;
|
||||||
assertTrue(emptyMapJsonObject.entrySet().isEmpty());
|
assertThat(emptyMapJsonObject.entrySet()).isEmpty();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNonEmptyMapSerialization() {
|
public void testNonEmptyMapSerialization() {
|
||||||
Type mapType = new TypeToken<Map<String, String>>() { }.getType();
|
Type mapType = new TypeToken<Map<String, String>>() { }.getType();
|
||||||
Map<String, String> myMap = new HashMap<>();
|
Map<String, String> myMap = new HashMap<>();
|
||||||
|
@ -57,8 +62,8 @@ public class DefaultMapJsonSerializerTest extends TestCase {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
JsonElement element = gson.toJsonTree(myMap, mapType);
|
JsonElement element = gson.toJsonTree(myMap, mapType);
|
||||||
|
|
||||||
assertTrue(element.isJsonObject());
|
assertThat(element.isJsonObject()).isTrue();
|
||||||
JsonObject mapJsonObject = element.getAsJsonObject();
|
JsonObject mapJsonObject = element.getAsJsonObject();
|
||||||
assertTrue(mapJsonObject.has(key));
|
assertThat(mapJsonObject.has(key)).isTrue();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -16,54 +16,60 @@
|
||||||
|
|
||||||
package com.google.gson;
|
package com.google.gson;
|
||||||
|
|
||||||
|
import static com.google.common.truth.Truth.assertThat;
|
||||||
|
|
||||||
import com.google.gson.annotations.Expose;
|
import com.google.gson.annotations.Expose;
|
||||||
|
|
||||||
import com.google.gson.internal.Excluder;
|
import com.google.gson.internal.Excluder;
|
||||||
import junit.framework.TestCase;
|
|
||||||
|
|
||||||
import java.lang.reflect.Field;
|
import java.lang.reflect.Field;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Unit tests for GsonBuilder.REQUIRE_EXPOSE_DESERIALIZE.
|
* Unit tests for GsonBuilder.REQUIRE_EXPOSE_DESERIALIZE.
|
||||||
*
|
*
|
||||||
* @author Joel Leitch
|
* @author Joel Leitch
|
||||||
*/
|
*/
|
||||||
public class ExposeAnnotationExclusionStrategyTest extends TestCase {
|
public class ExposeAnnotationExclusionStrategyTest {
|
||||||
private Excluder excluder = Excluder.DEFAULT.excludeFieldsWithoutExposeAnnotation();
|
private Excluder excluder = Excluder.DEFAULT.excludeFieldsWithoutExposeAnnotation();
|
||||||
|
|
||||||
public void testNeverSkipClasses() throws Exception {
|
@Test
|
||||||
assertFalse(excluder.excludeClass(MockObject.class, true));
|
public void testNeverSkipClasses() {
|
||||||
assertFalse(excluder.excludeClass(MockObject.class, false));
|
assertThat(excluder.excludeClass(MockObject.class, true)).isFalse();
|
||||||
|
assertThat(excluder.excludeClass(MockObject.class, false)).isFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSkipNonAnnotatedFields() throws Exception {
|
public void testSkipNonAnnotatedFields() throws Exception {
|
||||||
Field f = createFieldAttributes("hiddenField");
|
Field f = createFieldAttributes("hiddenField");
|
||||||
assertTrue(excluder.excludeField(f, true));
|
assertThat(excluder.excludeField(f, true)).isTrue();
|
||||||
assertTrue(excluder.excludeField(f, false));
|
assertThat(excluder.excludeField(f, false)).isTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSkipExplicitlySkippedFields() throws Exception {
|
public void testSkipExplicitlySkippedFields() throws Exception {
|
||||||
Field f = createFieldAttributes("explicitlyHiddenField");
|
Field f = createFieldAttributes("explicitlyHiddenField");
|
||||||
assertTrue(excluder.excludeField(f, true));
|
assertThat(excluder.excludeField(f, true)).isTrue();
|
||||||
assertTrue(excluder.excludeField(f, false));
|
assertThat(excluder.excludeField(f, false)).isTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNeverSkipExposedAnnotatedFields() throws Exception {
|
public void testNeverSkipExposedAnnotatedFields() throws Exception {
|
||||||
Field f = createFieldAttributes("exposedField");
|
Field f = createFieldAttributes("exposedField");
|
||||||
assertFalse(excluder.excludeField(f, true));
|
assertThat(excluder.excludeField(f, true)).isFalse();
|
||||||
assertFalse(excluder.excludeField(f, false));
|
assertThat(excluder.excludeField(f, false)).isFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNeverSkipExplicitlyExposedAnnotatedFields() throws Exception {
|
public void testNeverSkipExplicitlyExposedAnnotatedFields() throws Exception {
|
||||||
Field f = createFieldAttributes("explicitlyExposedField");
|
Field f = createFieldAttributes("explicitlyExposedField");
|
||||||
assertFalse(excluder.excludeField(f, true));
|
assertThat(excluder.excludeField(f, true)).isFalse();
|
||||||
assertFalse(excluder.excludeField(f, false));
|
assertThat(excluder.excludeField(f, false)).isFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDifferentSerializeAndDeserializeField() throws Exception {
|
public void testDifferentSerializeAndDeserializeField() throws Exception {
|
||||||
Field f = createFieldAttributes("explicitlyDifferentModeField");
|
Field f = createFieldAttributes("explicitlyDifferentModeField");
|
||||||
assertFalse(excluder.excludeField(f, true));
|
assertThat(excluder.excludeField(f, true)).isFalse();
|
||||||
assertTrue(excluder.excludeField(f, false));
|
assertThat(excluder.excludeField(f, false)).isTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static Field createFieldAttributes(String fieldName) throws Exception {
|
private static Field createFieldAttributes(String fieldName) throws Exception {
|
||||||
|
|
|
@ -16,11 +16,15 @@
|
||||||
|
|
||||||
package com.google.gson;
|
package com.google.gson;
|
||||||
|
|
||||||
|
import static com.google.common.truth.Truth.assertThat;
|
||||||
|
import static org.junit.Assert.fail;
|
||||||
|
|
||||||
import com.google.gson.reflect.TypeToken;
|
import com.google.gson.reflect.TypeToken;
|
||||||
import java.lang.reflect.Modifier;
|
import java.lang.reflect.Modifier;
|
||||||
import java.lang.reflect.Type;
|
import java.lang.reflect.Type;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import junit.framework.TestCase;
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Unit tests for the {@link FieldAttributes} class.
|
* Unit tests for the {@link FieldAttributes} class.
|
||||||
|
@ -28,46 +32,50 @@ import junit.framework.TestCase;
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
* @author Joel Leitch
|
* @author Joel Leitch
|
||||||
*/
|
*/
|
||||||
public class FieldAttributesTest extends TestCase {
|
public class FieldAttributesTest {
|
||||||
private FieldAttributes fieldAttributes;
|
private FieldAttributes fieldAttributes;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
fieldAttributes = new FieldAttributes(Foo.class.getField("bar"));
|
fieldAttributes = new FieldAttributes(Foo.class.getField("bar"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings("unused")
|
@SuppressWarnings("unused")
|
||||||
public void testNullField() throws Exception {
|
@Test
|
||||||
|
public void testNullField() {
|
||||||
try {
|
try {
|
||||||
new FieldAttributes(null);
|
new FieldAttributes(null);
|
||||||
fail("Field parameter can not be null");
|
fail("Field parameter can not be null");
|
||||||
} catch (NullPointerException expected) { }
|
} catch (NullPointerException expected) { }
|
||||||
}
|
}
|
||||||
|
|
||||||
public void testDeclaringClass() throws Exception {
|
@Test
|
||||||
assertEquals(Foo.class, fieldAttributes.getDeclaringClass());
|
public void testDeclaringClass() {
|
||||||
|
assertThat(fieldAttributes.getDeclaringClass()).isAssignableTo(Foo.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void testModifiers() throws Exception {
|
@Test
|
||||||
assertFalse(fieldAttributes.hasModifier(Modifier.STATIC));
|
public void testModifiers() {
|
||||||
assertFalse(fieldAttributes.hasModifier(Modifier.FINAL));
|
assertThat(fieldAttributes.hasModifier(Modifier.STATIC)).isFalse();
|
||||||
assertFalse(fieldAttributes.hasModifier(Modifier.ABSTRACT));
|
assertThat(fieldAttributes.hasModifier(Modifier.FINAL)).isFalse();
|
||||||
assertFalse(fieldAttributes.hasModifier(Modifier.VOLATILE));
|
assertThat(fieldAttributes.hasModifier(Modifier.ABSTRACT)).isFalse();
|
||||||
assertFalse(fieldAttributes.hasModifier(Modifier.PROTECTED));
|
assertThat(fieldAttributes.hasModifier(Modifier.VOLATILE)).isFalse();
|
||||||
|
assertThat(fieldAttributes.hasModifier(Modifier.PROTECTED)).isFalse();
|
||||||
|
|
||||||
assertTrue(fieldAttributes.hasModifier(Modifier.PUBLIC));
|
assertThat(fieldAttributes.hasModifier(Modifier.PUBLIC)).isTrue();
|
||||||
assertTrue(fieldAttributes.hasModifier(Modifier.TRANSIENT));
|
assertThat(fieldAttributes.hasModifier(Modifier.TRANSIENT)).isTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void testName() throws Exception {
|
@Test
|
||||||
assertEquals("bar", fieldAttributes.getName());
|
public void testName() {
|
||||||
|
assertThat(fieldAttributes.getName()).isEqualTo("bar");
|
||||||
}
|
}
|
||||||
|
|
||||||
public void testDeclaredTypeAndClass() throws Exception {
|
@Test
|
||||||
|
public void testDeclaredTypeAndClass() {
|
||||||
Type expectedType = new TypeToken<List<String>>() {}.getType();
|
Type expectedType = new TypeToken<List<String>>() {}.getType();
|
||||||
assertEquals(expectedType, fieldAttributes.getDeclaredType());
|
assertThat(fieldAttributes.getDeclaredType()).isEqualTo(expectedType);
|
||||||
assertEquals(List.class, fieldAttributes.getDeclaredClass());
|
assertThat(fieldAttributes.getDeclaredClass()).isAssignableTo(List.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static class Foo {
|
private static class Foo {
|
||||||
|
|
|
@ -1,7 +1,8 @@
|
||||||
package com.google.gson;
|
package com.google.gson;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static com.google.common.truth.Truth.assertThat;
|
||||||
import static org.junit.Assert.assertNotEquals;
|
import static com.google.common.truth.Truth.assertWithMessage;
|
||||||
|
|
||||||
import java.lang.reflect.Field;
|
import java.lang.reflect.Field;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
@ -28,7 +29,7 @@ public class FieldNamingPolicyTest {
|
||||||
};
|
};
|
||||||
|
|
||||||
for (String[] pair : argumentPairs) {
|
for (String[] pair : argumentPairs) {
|
||||||
assertEquals(pair[1], FieldNamingPolicy.separateCamelCase(pair[0], '_'));
|
assertThat(FieldNamingPolicy.separateCamelCase(pair[0], '_')).isEqualTo(pair[1]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -51,12 +52,12 @@ public class FieldNamingPolicyTest {
|
||||||
};
|
};
|
||||||
|
|
||||||
for (String[] pair : argumentPairs) {
|
for (String[] pair : argumentPairs) {
|
||||||
assertEquals(pair[1], FieldNamingPolicy.upperCaseFirstLetter(pair[0]));
|
assertThat(FieldNamingPolicy.upperCaseFirstLetter(pair[0])).isEqualTo(pair[1]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Upper casing policies should be unaffected by default Locale.
|
* Upper-casing policies should be unaffected by default Locale.
|
||||||
*/
|
*/
|
||||||
@Test
|
@Test
|
||||||
public void testUpperCasingLocaleIndependent() throws Exception {
|
public void testUpperCasingLocaleIndependent() throws Exception {
|
||||||
|
@ -81,11 +82,13 @@ public class FieldNamingPolicyTest {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Verify that default Locale has different case conversion rules
|
// Verify that default Locale has different case conversion rules
|
||||||
assertNotEquals("Test setup is broken", expected, name.toUpperCase());
|
assertWithMessage("Test setup is broken")
|
||||||
|
.that(name.toUpperCase()).doesNotMatch(expected);
|
||||||
|
|
||||||
for (FieldNamingPolicy policy : policies) {
|
for (FieldNamingPolicy policy : policies) {
|
||||||
// Should ignore default Locale
|
// Should ignore default Locale
|
||||||
assertEquals("Unexpected conversion for " + policy, expected, policy.translateName(field));
|
assertWithMessage("Unexpected conversion for %s", policy)
|
||||||
|
.that(policy.translateName(field)).matches(expected);
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
Locale.setDefault(oldLocale);
|
Locale.setDefault(oldLocale);
|
||||||
|
@ -118,11 +121,13 @@ public class FieldNamingPolicyTest {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Verify that default Locale has different case conversion rules
|
// Verify that default Locale has different case conversion rules
|
||||||
assertNotEquals("Test setup is broken", expected, name.toLowerCase());
|
assertWithMessage("Test setup is broken")
|
||||||
|
.that(name.toLowerCase()).doesNotMatch(expected);
|
||||||
|
|
||||||
for (FieldNamingPolicy policy : policies) {
|
for (FieldNamingPolicy policy : policies) {
|
||||||
// Should ignore default Locale
|
// Should ignore default Locale
|
||||||
assertEquals("Unexpected conversion for " + policy, expected, policy.translateName(field));
|
assertWithMessage("Unexpected conversion for %s", policy)
|
||||||
|
.that(policy.translateName(field)).matches(expected);
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
Locale.setDefault(oldLocale);
|
Locale.setDefault(oldLocale);
|
||||||
|
|
|
@ -16,14 +16,15 @@
|
||||||
|
|
||||||
package com.google.gson;
|
package com.google.gson;
|
||||||
|
|
||||||
|
import static com.google.common.truth.Truth.assertThat;
|
||||||
|
|
||||||
import com.google.gson.internal.$Gson$Types;
|
import com.google.gson.internal.$Gson$Types;
|
||||||
import com.google.gson.reflect.TypeToken;
|
import com.google.gson.reflect.TypeToken;
|
||||||
|
|
||||||
import junit.framework.TestCase;
|
|
||||||
|
|
||||||
import java.lang.reflect.GenericArrayType;
|
import java.lang.reflect.GenericArrayType;
|
||||||
import java.lang.reflect.Type;
|
import java.lang.reflect.Type;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Unit tests for the {@code GenericArrayType}s created by the {@link $Gson$Types} class.
|
* Unit tests for the {@code GenericArrayType}s created by the {@link $Gson$Types} class.
|
||||||
|
@ -31,27 +32,28 @@ import java.util.List;
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
* @author Joel Leitch
|
* @author Joel Leitch
|
||||||
*/
|
*/
|
||||||
public class GenericArrayTypeTest extends TestCase {
|
public class GenericArrayTypeTest {
|
||||||
private GenericArrayType ourType;
|
private GenericArrayType ourType;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
ourType = $Gson$Types.arrayOf($Gson$Types.newParameterizedTypeWithOwner(null, List.class, String.class));
|
ourType = $Gson$Types.arrayOf($Gson$Types.newParameterizedTypeWithOwner(null, List.class, String.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testOurTypeFunctionality() throws Exception {
|
public void testOurTypeFunctionality() throws Exception {
|
||||||
Type parameterizedType = new TypeToken<List<String>>() {}.getType();
|
Type parameterizedType = new TypeToken<List<String>>() {}.getType();
|
||||||
Type genericArrayType = new TypeToken<List<String>[]>() {}.getType();
|
Type genericArrayType = new TypeToken<List<String>[]>() {}.getType();
|
||||||
|
|
||||||
assertEquals(parameterizedType, ourType.getGenericComponentType());
|
assertThat(ourType.getGenericComponentType()).isEqualTo(parameterizedType);
|
||||||
assertEquals(genericArrayType, ourType);
|
assertThat(ourType).isEqualTo(genericArrayType);
|
||||||
assertEquals(genericArrayType.hashCode(), ourType.hashCode());
|
assertThat(ourType.hashCode()).isEqualTo(genericArrayType.hashCode());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNotEquals() throws Exception {
|
public void testNotEquals() throws Exception {
|
||||||
Type differentGenericArrayType = new TypeToken<List<String>[][]>() {}.getType();
|
Type differentGenericArrayType = new TypeToken<List<String>[][]>() {}.getType();
|
||||||
assertFalse(differentGenericArrayType.equals(ourType));
|
assertThat(differentGenericArrayType.equals(ourType)).isFalse();
|
||||||
assertFalse(ourType.equals(differentGenericArrayType));
|
assertThat(ourType.equals(differentGenericArrayType)).isFalse();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -16,9 +16,7 @@
|
||||||
|
|
||||||
package com.google.gson;
|
package com.google.gson;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static com.google.common.truth.Truth.assertThat;
|
||||||
import static org.junit.Assert.assertNotNull;
|
|
||||||
import static org.junit.Assert.assertNotSame;
|
|
||||||
import static org.junit.Assert.fail;
|
import static org.junit.Assert.fail;
|
||||||
|
|
||||||
import com.google.gson.stream.JsonReader;
|
import com.google.gson.stream.JsonReader;
|
||||||
|
@ -48,8 +46,8 @@ public class GsonBuilderTest {
|
||||||
public void testCreatingMoreThanOnce() {
|
public void testCreatingMoreThanOnce() {
|
||||||
GsonBuilder builder = new GsonBuilder();
|
GsonBuilder builder = new GsonBuilder();
|
||||||
Gson gson = builder.create();
|
Gson gson = builder.create();
|
||||||
assertNotNull(gson);
|
assertThat(gson).isNotNull();
|
||||||
assertNotNull(builder.create());
|
assertThat(builder.create()).isNotNull();
|
||||||
|
|
||||||
builder.setFieldNamingStrategy(new FieldNamingStrategy() {
|
builder.setFieldNamingStrategy(new FieldNamingStrategy() {
|
||||||
@Override public String translateName(Field f) {
|
@Override public String translateName(Field f) {
|
||||||
|
@ -58,9 +56,9 @@ public class GsonBuilderTest {
|
||||||
});
|
});
|
||||||
|
|
||||||
Gson otherGson = builder.create();
|
Gson otherGson = builder.create();
|
||||||
assertNotNull(otherGson);
|
assertThat(otherGson).isNotNull();
|
||||||
// Should be different instances because builder has been modified in the meantime
|
// Should be different instances because builder has been modified in the meantime
|
||||||
assertNotSame(gson, otherGson);
|
assertThat(gson).isNotSameInstanceAs(otherGson);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -74,7 +72,7 @@ public class GsonBuilderTest {
|
||||||
|
|
||||||
// Modifications of `gsonBuilder` should not affect `gson` object
|
// Modifications of `gsonBuilder` should not affect `gson` object
|
||||||
gsonBuilder.registerTypeAdapter(CustomClass1.class, new TypeAdapter<CustomClass1>() {
|
gsonBuilder.registerTypeAdapter(CustomClass1.class, new TypeAdapter<CustomClass1>() {
|
||||||
@Override public CustomClass1 read(JsonReader in) throws IOException {
|
@Override public CustomClass1 read(JsonReader in) {
|
||||||
throw new UnsupportedOperationException();
|
throw new UnsupportedOperationException();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -93,6 +91,7 @@ public class GsonBuilderTest {
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
assertDefaultGson(gson);
|
assertDefaultGson(gson);
|
||||||
// New GsonBuilder created from `gson` should not have been affected by changes
|
// New GsonBuilder created from `gson` should not have been affected by changes
|
||||||
// to `gsonBuilder` either
|
// to `gsonBuilder` either
|
||||||
|
@ -105,26 +104,26 @@ public class GsonBuilderTest {
|
||||||
private static void assertDefaultGson(Gson gson) {
|
private static void assertDefaultGson(Gson gson) {
|
||||||
// Should use default reflective adapter
|
// Should use default reflective adapter
|
||||||
String json1 = gson.toJson(new CustomClass1());
|
String json1 = gson.toJson(new CustomClass1());
|
||||||
assertEquals("{}", json1);
|
assertThat(json1).isEqualTo("{}");
|
||||||
|
|
||||||
// Should use default reflective adapter
|
// Should use default reflective adapter
|
||||||
String json2 = gson.toJson(new CustomClass2());
|
String json2 = gson.toJson(new CustomClass2());
|
||||||
assertEquals("{}", json2);
|
assertThat(json2).isEqualTo("{}");
|
||||||
|
|
||||||
// Should use default instance creator
|
// Should use default instance creator
|
||||||
CustomClass3 customClass3 = gson.fromJson("{}", CustomClass3.class);
|
CustomClass3 customClass3 = gson.fromJson("{}", CustomClass3.class);
|
||||||
assertEquals(CustomClass3.NO_ARG_CONSTRUCTOR_VALUE, customClass3.s);
|
assertThat(customClass3.s).isEqualTo(CustomClass3.NO_ARG_CONSTRUCTOR_VALUE);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void assertCustomGson(Gson gson) {
|
private static void assertCustomGson(Gson gson) {
|
||||||
String json1 = gson.toJson(new CustomClass1());
|
String json1 = gson.toJson(new CustomClass1());
|
||||||
assertEquals("\"custom-adapter\"", json1);
|
assertThat(json1).isEqualTo("\"custom-adapter\"");
|
||||||
|
|
||||||
String json2 = gson.toJson(new CustomClass2());
|
String json2 = gson.toJson(new CustomClass2());
|
||||||
assertEquals("\"custom-hierarchy-adapter\"", json2);
|
assertThat(json2).isEqualTo("\"custom-hierarchy-adapter\"");
|
||||||
|
|
||||||
CustomClass3 customClass3 = gson.fromJson("{}", CustomClass3.class);
|
CustomClass3 customClass3 = gson.fromJson("{}", CustomClass3.class);
|
||||||
assertEquals("custom-instance", customClass3.s);
|
assertThat(customClass3.s).isEqualTo("custom-instance");
|
||||||
}
|
}
|
||||||
|
|
||||||
static class CustomClass1 { }
|
static class CustomClass1 { }
|
||||||
|
@ -148,7 +147,7 @@ public class GsonBuilderTest {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.excludeFieldsWithModifiers(Modifier.VOLATILE, Modifier.PRIVATE)
|
.excludeFieldsWithModifiers(Modifier.VOLATILE, Modifier.PRIVATE)
|
||||||
.create();
|
.create();
|
||||||
assertEquals("{\"d\":\"d\"}", gson.toJson(new HasModifiers()));
|
assertThat(gson.toJson(new HasModifiers())).isEqualTo("{\"d\":\"d\"}");
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings("unused")
|
@SuppressWarnings("unused")
|
||||||
|
@ -164,7 +163,7 @@ public class GsonBuilderTest {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.excludeFieldsWithModifiers()
|
.excludeFieldsWithModifiers()
|
||||||
.create();
|
.create();
|
||||||
assertEquals("{\"a\":\"a\"}", gson.toJson(new HasTransients()));
|
assertThat(gson.toJson(new HasTransients())).isEqualTo("{\"a\":\"a\"}");
|
||||||
}
|
}
|
||||||
|
|
||||||
static class HasTransients {
|
static class HasTransients {
|
||||||
|
@ -195,12 +194,10 @@ public class GsonBuilderTest {
|
||||||
gson.fromJson("{}", ClassWithoutNoArgsConstructor.class);
|
gson.fromJson("{}", ClassWithoutNoArgsConstructor.class);
|
||||||
fail("Expected exception");
|
fail("Expected exception");
|
||||||
} catch (JsonIOException expected) {
|
} catch (JsonIOException expected) {
|
||||||
assertEquals(
|
assertThat(expected).hasMessageThat().isEqualTo(
|
||||||
"Unable to create instance of class com.google.gson.GsonBuilderTest$ClassWithoutNoArgsConstructor; "
|
"Unable to create instance of class com.google.gson.GsonBuilderTest$ClassWithoutNoArgsConstructor; "
|
||||||
+ "usage of JDK Unsafe is disabled. Registering an InstanceCreator or a TypeAdapter for this type, "
|
+ "usage of JDK Unsafe is disabled. Registering an InstanceCreator or a TypeAdapter for this type, "
|
||||||
+ "adding a no-args constructor, or enabling usage of JDK Unsafe may fix this problem.",
|
+ "adding a no-args constructor, or enabling usage of JDK Unsafe may fix this problem.");
|
||||||
expected.getMessage()
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -217,14 +214,14 @@ public class GsonBuilderTest {
|
||||||
builder.setVersion(Double.NaN);
|
builder.setVersion(Double.NaN);
|
||||||
fail();
|
fail();
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
assertEquals("Invalid version: NaN", e.getMessage());
|
assertThat(e).hasMessageThat().isEqualTo("Invalid version: NaN");
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
builder.setVersion(-0.1);
|
builder.setVersion(-0.1);
|
||||||
fail();
|
fail();
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
assertEquals("Invalid version: -0.1", e.getMessage());
|
assertThat(e).hasMessageThat().isEqualTo("Invalid version: -0.1");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -16,6 +16,10 @@
|
||||||
|
|
||||||
package com.google.gson;
|
package com.google.gson;
|
||||||
|
|
||||||
|
import static com.google.common.truth.Truth.assertThat;
|
||||||
|
import static org.junit.Assert.fail;
|
||||||
|
|
||||||
|
import com.google.gson.Gson.FutureTypeAdapter;
|
||||||
import com.google.gson.internal.Excluder;
|
import com.google.gson.internal.Excluder;
|
||||||
import com.google.gson.reflect.TypeToken;
|
import com.google.gson.reflect.TypeToken;
|
||||||
import com.google.gson.stream.JsonReader;
|
import com.google.gson.stream.JsonReader;
|
||||||
|
@ -30,16 +34,17 @@ import java.text.DateFormat;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
|
import java.util.concurrent.CountDownLatch;
|
||||||
import java.util.concurrent.atomic.AtomicInteger;
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
import java.util.concurrent.atomic.AtomicReference;
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
import junit.framework.TestCase;
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Unit tests for {@link Gson}.
|
* Unit tests for {@link Gson}.
|
||||||
*
|
*
|
||||||
* @author Ryan Harter
|
* @author Ryan Harter
|
||||||
*/
|
*/
|
||||||
public final class GsonTest extends TestCase {
|
public final class GsonTest {
|
||||||
|
|
||||||
private static final Excluder CUSTOM_EXCLUDER = Excluder.DEFAULT
|
private static final Excluder CUSTOM_EXCLUDER = Excluder.DEFAULT
|
||||||
.excludeFieldsWithoutExposeAnnotation()
|
.excludeFieldsWithoutExposeAnnotation()
|
||||||
|
@ -54,6 +59,7 @@ public final class GsonTest extends TestCase {
|
||||||
private static final ToNumberStrategy CUSTOM_OBJECT_TO_NUMBER_STRATEGY = ToNumberPolicy.DOUBLE;
|
private static final ToNumberStrategy CUSTOM_OBJECT_TO_NUMBER_STRATEGY = ToNumberPolicy.DOUBLE;
|
||||||
private static final ToNumberStrategy CUSTOM_NUMBER_TO_NUMBER_STRATEGY = ToNumberPolicy.LAZILY_PARSED_NUMBER;
|
private static final ToNumberStrategy CUSTOM_NUMBER_TO_NUMBER_STRATEGY = ToNumberPolicy.LAZILY_PARSED_NUMBER;
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testOverridesDefaultExcluder() {
|
public void testOverridesDefaultExcluder() {
|
||||||
Gson gson = new Gson(CUSTOM_EXCLUDER, CUSTOM_FIELD_NAMING_STRATEGY,
|
Gson gson = new Gson(CUSTOM_EXCLUDER, CUSTOM_FIELD_NAMING_STRATEGY,
|
||||||
new HashMap<Type, InstanceCreator<?>>(), true, false, false, true, false,
|
new HashMap<Type, InstanceCreator<?>>(), true, false, false, true, false,
|
||||||
|
@ -63,12 +69,13 @@ public final class GsonTest extends TestCase {
|
||||||
CUSTOM_OBJECT_TO_NUMBER_STRATEGY, CUSTOM_NUMBER_TO_NUMBER_STRATEGY,
|
CUSTOM_OBJECT_TO_NUMBER_STRATEGY, CUSTOM_NUMBER_TO_NUMBER_STRATEGY,
|
||||||
Collections.<ReflectionAccessFilter>emptyList());
|
Collections.<ReflectionAccessFilter>emptyList());
|
||||||
|
|
||||||
assertEquals(CUSTOM_EXCLUDER, gson.excluder);
|
assertThat(gson.excluder).isEqualTo(CUSTOM_EXCLUDER);
|
||||||
assertEquals(CUSTOM_FIELD_NAMING_STRATEGY, gson.fieldNamingStrategy());
|
assertThat(gson.fieldNamingStrategy()).isEqualTo(CUSTOM_FIELD_NAMING_STRATEGY);
|
||||||
assertEquals(true, gson.serializeNulls());
|
assertThat(gson.serializeNulls()).isTrue();
|
||||||
assertEquals(false, gson.htmlSafe());
|
assertThat(gson.htmlSafe()).isFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testClonedTypeAdapterFactoryListsAreIndependent() {
|
public void testClonedTypeAdapterFactoryListsAreIndependent() {
|
||||||
Gson original = new Gson(CUSTOM_EXCLUDER, CUSTOM_FIELD_NAMING_STRATEGY,
|
Gson original = new Gson(CUSTOM_EXCLUDER, CUSTOM_FIELD_NAMING_STRATEGY,
|
||||||
new HashMap<Type, InstanceCreator<?>>(), true, false, false, true, false,
|
new HashMap<Type, InstanceCreator<?>>(), true, false, false, true, false,
|
||||||
|
@ -82,34 +89,36 @@ public final class GsonTest extends TestCase {
|
||||||
.registerTypeAdapter(Object.class, new TestTypeAdapter())
|
.registerTypeAdapter(Object.class, new TestTypeAdapter())
|
||||||
.create();
|
.create();
|
||||||
|
|
||||||
assertEquals(original.factories.size() + 1, clone.factories.size());
|
assertThat(clone.factories).hasSize(original.factories.size() + 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static final class TestTypeAdapter extends TypeAdapter<Object> {
|
private static final class TestTypeAdapter extends TypeAdapter<Object> {
|
||||||
@Override public void write(JsonWriter out, Object value) throws IOException {
|
@Override public void write(JsonWriter out, Object value) {
|
||||||
// Test stub.
|
// Test stub.
|
||||||
}
|
}
|
||||||
@Override public Object read(JsonReader in) throws IOException { return null; }
|
@Override public Object read(JsonReader in) { return null; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testGetAdapter_Null() {
|
public void testGetAdapter_Null() {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
try {
|
try {
|
||||||
gson.getAdapter((TypeToken<?>) null);
|
gson.getAdapter((TypeToken<?>) null);
|
||||||
fail();
|
fail();
|
||||||
} catch (NullPointerException e) {
|
} catch (NullPointerException e) {
|
||||||
assertEquals("type must not be null", e.getMessage());
|
assertThat(e).hasMessageThat().isEqualTo("type must not be null");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testGetAdapter_Concurrency() {
|
public void testGetAdapter_Concurrency() {
|
||||||
class DummyAdapter<T> extends TypeAdapter<T> {
|
class DummyAdapter<T> extends TypeAdapter<T> {
|
||||||
@Override public void write(JsonWriter out, T value) throws IOException {
|
@Override public void write(JsonWriter out, T value) throws IOException {
|
||||||
throw new AssertionError("not needed for test");
|
throw new AssertionError("not needed for this test");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override public T read(JsonReader in) throws IOException {
|
@Override public T read(JsonReader in) throws IOException {
|
||||||
throw new AssertionError("not needed for test");
|
throw new AssertionError("not needed for this test");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -149,12 +158,118 @@ public final class GsonTest extends TestCase {
|
||||||
.create();
|
.create();
|
||||||
|
|
||||||
TypeAdapter<?> adapter = gson.getAdapter(requestedType);
|
TypeAdapter<?> adapter = gson.getAdapter(requestedType);
|
||||||
assertTrue(adapter instanceof DummyAdapter);
|
assertThat(adapterInstancesCreated.get()).isEqualTo(2);
|
||||||
assertEquals(2, adapterInstancesCreated.get());
|
assertThat(adapter).isInstanceOf(DummyAdapter.class);
|
||||||
// Should be the same adapter instance the concurrent thread received
|
assertThat(threadAdapter.get()).isInstanceOf(DummyAdapter.class);
|
||||||
assertSame(threadAdapter.get(), adapter);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verifies that two threads calling {@link Gson#getAdapter(TypeToken)} do not see the
|
||||||
|
* same unresolved {@link FutureTypeAdapter} instance, since that would not be thread-safe.
|
||||||
|
*
|
||||||
|
* This test constructs the cyclic dependency {@literal CustomClass1 -> CustomClass2 -> CustomClass1}
|
||||||
|
* and lets one thread wait after the adapter for CustomClass2 has been obtained (which still
|
||||||
|
* refers to the nested unresolved FutureTypeAdapter for CustomClass1).
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
public void testGetAdapter_FutureAdapterConcurrency() throws Exception {
|
||||||
|
/**
|
||||||
|
* Adapter which wraps another adapter. Can be imagined as a simplified version of the
|
||||||
|
* {@code ReflectiveTypeAdapterFactory$Adapter}.
|
||||||
|
*/
|
||||||
|
class WrappingAdapter<T> extends TypeAdapter<T> {
|
||||||
|
final TypeAdapter<?> wrapped;
|
||||||
|
boolean isFirstCall = true;
|
||||||
|
|
||||||
|
WrappingAdapter(TypeAdapter<?> wrapped) {
|
||||||
|
this.wrapped = wrapped;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override public void write(JsonWriter out, T value) throws IOException {
|
||||||
|
// Due to how this test is set up there is infinite recursion, therefore
|
||||||
|
// need to track how deeply nested this call is
|
||||||
|
if (isFirstCall) {
|
||||||
|
isFirstCall = false;
|
||||||
|
out.beginArray();
|
||||||
|
wrapped.write(out, null);
|
||||||
|
out.endArray();
|
||||||
|
isFirstCall = true;
|
||||||
|
} else {
|
||||||
|
out.value("wrapped-nested");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override public T read(JsonReader in) throws IOException {
|
||||||
|
throw new AssertionError("not needed for this test");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final CountDownLatch isThreadWaiting = new CountDownLatch(1);
|
||||||
|
final CountDownLatch canThreadProceed = new CountDownLatch(1);
|
||||||
|
|
||||||
|
final Gson gson = new GsonBuilder()
|
||||||
|
.registerTypeAdapterFactory(new TypeAdapterFactory() {
|
||||||
|
// volatile instead of AtomicBoolean is safe here because CountDownLatch prevents
|
||||||
|
// "true" concurrency
|
||||||
|
volatile boolean isFirstCaller = true;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
|
||||||
|
Class<?> raw = type.getRawType();
|
||||||
|
|
||||||
|
if (raw == CustomClass1.class) {
|
||||||
|
// Retrieves a WrappingAdapter containing a nested FutureAdapter for CustomClass1
|
||||||
|
TypeAdapter<?> adapter = gson.getAdapter(CustomClass2.class);
|
||||||
|
|
||||||
|
// Let thread wait so the FutureAdapter for CustomClass1 nested in the adapter
|
||||||
|
// for CustomClass2 is not resolved yet
|
||||||
|
if (isFirstCaller) {
|
||||||
|
isFirstCaller = false;
|
||||||
|
isThreadWaiting.countDown();
|
||||||
|
|
||||||
|
try {
|
||||||
|
canThreadProceed.await();
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return new WrappingAdapter<>(adapter);
|
||||||
|
}
|
||||||
|
else if (raw == CustomClass2.class) {
|
||||||
|
TypeAdapter<?> adapter = gson.getAdapter(CustomClass1.class);
|
||||||
|
assertThat(adapter).isInstanceOf(FutureTypeAdapter.class);
|
||||||
|
return new WrappingAdapter<>(adapter);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
throw new AssertionError("Adapter for unexpected type requested: " + raw);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.create();
|
||||||
|
|
||||||
|
final AtomicReference<TypeAdapter<?>> otherThreadAdapter = new AtomicReference<>();
|
||||||
|
Thread thread = new Thread() {
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
otherThreadAdapter.set(gson.getAdapter(CustomClass1.class));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
thread.start();
|
||||||
|
|
||||||
|
// Wait until other thread has obtained FutureAdapter
|
||||||
|
isThreadWaiting.await();
|
||||||
|
TypeAdapter<?> adapter = gson.getAdapter(CustomClass1.class);
|
||||||
|
// Should not fail due to referring to unresolved FutureTypeAdapter
|
||||||
|
assertThat(adapter.toJson(null)).isEqualTo("[[\"wrapped-nested\"]]");
|
||||||
|
|
||||||
|
// Let other thread proceed and have it resolve its FutureTypeAdapter
|
||||||
|
canThreadProceed.countDown();
|
||||||
|
thread.join();
|
||||||
|
assertThat(otherThreadAdapter.get().toJson(null)).isEqualTo("[[\"wrapped-nested\"]]");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNewJsonWriter_Default() throws IOException {
|
public void testNewJsonWriter_Default() throws IOException {
|
||||||
StringWriter writer = new StringWriter();
|
StringWriter writer = new StringWriter();
|
||||||
JsonWriter jsonWriter = new GsonBuilder().create().newJsonWriter(writer);
|
JsonWriter jsonWriter = new GsonBuilder().create().newJsonWriter(writer);
|
||||||
|
@ -170,13 +285,14 @@ public final class GsonTest extends TestCase {
|
||||||
jsonWriter.value(1);
|
jsonWriter.value(1);
|
||||||
fail();
|
fail();
|
||||||
} catch (IllegalStateException expected) {
|
} catch (IllegalStateException expected) {
|
||||||
assertEquals("JSON must have only one top-level value.", expected.getMessage());
|
assertThat(expected).hasMessageThat().isEqualTo("JSON must have only one top-level value.");
|
||||||
}
|
}
|
||||||
|
|
||||||
jsonWriter.close();
|
jsonWriter.close();
|
||||||
assertEquals("{\"\\u003ctest2\":true}", writer.toString());
|
assertThat(writer.toString()).isEqualTo("{\"\\u003ctest2\":true}");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNewJsonWriter_Custom() throws IOException {
|
public void testNewJsonWriter_Custom() throws IOException {
|
||||||
StringWriter writer = new StringWriter();
|
StringWriter writer = new StringWriter();
|
||||||
JsonWriter jsonWriter = new GsonBuilder()
|
JsonWriter jsonWriter = new GsonBuilder()
|
||||||
|
@ -198,9 +314,10 @@ public final class GsonTest extends TestCase {
|
||||||
jsonWriter.value(1);
|
jsonWriter.value(1);
|
||||||
|
|
||||||
jsonWriter.close();
|
jsonWriter.close();
|
||||||
assertEquals(")]}'\n{\n \"test\": null,\n \"<test2\": true\n}1", writer.toString());
|
assertThat(writer.toString()).isEqualTo(")]}'\n{\n \"test\": null,\n \"<test2\": true\n}1");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNewJsonReader_Default() throws IOException {
|
public void testNewJsonReader_Default() throws IOException {
|
||||||
String json = "test"; // String without quotes
|
String json = "test"; // String without quotes
|
||||||
JsonReader jsonReader = new GsonBuilder().create().newJsonReader(new StringReader(json));
|
JsonReader jsonReader = new GsonBuilder().create().newJsonReader(new StringReader(json));
|
||||||
|
@ -212,13 +329,14 @@ public final class GsonTest extends TestCase {
|
||||||
jsonReader.close();
|
jsonReader.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNewJsonReader_Custom() throws IOException {
|
public void testNewJsonReader_Custom() throws IOException {
|
||||||
String json = "test"; // String without quotes
|
String json = "test"; // String without quotes
|
||||||
JsonReader jsonReader = new GsonBuilder()
|
JsonReader jsonReader = new GsonBuilder()
|
||||||
.setLenient()
|
.setLenient()
|
||||||
.create()
|
.create()
|
||||||
.newJsonReader(new StringReader(json));
|
.newJsonReader(new StringReader(json));
|
||||||
assertEquals("test", jsonReader.nextString());
|
assertThat(jsonReader.nextString()).isEqualTo("test");
|
||||||
jsonReader.close();
|
jsonReader.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -226,6 +344,7 @@ public final class GsonTest extends TestCase {
|
||||||
* Modifying a GsonBuilder obtained from {@link Gson#newBuilder()} of a
|
* Modifying a GsonBuilder obtained from {@link Gson#newBuilder()} of a
|
||||||
* {@code new Gson()} should not affect the Gson instance it came from.
|
* {@code new Gson()} should not affect the Gson instance it came from.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testDefaultGsonNewBuilderModification() {
|
public void testDefaultGsonNewBuilderModification() {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
GsonBuilder gsonBuilder = gson.newBuilder();
|
GsonBuilder gsonBuilder = gson.newBuilder();
|
||||||
|
@ -262,15 +381,15 @@ public final class GsonTest extends TestCase {
|
||||||
private static void assertDefaultGson(Gson gson) {
|
private static void assertDefaultGson(Gson gson) {
|
||||||
// Should use default reflective adapter
|
// Should use default reflective adapter
|
||||||
String json1 = gson.toJson(new CustomClass1());
|
String json1 = gson.toJson(new CustomClass1());
|
||||||
assertEquals("{}", json1);
|
assertThat(json1).isEqualTo("{}");
|
||||||
|
|
||||||
// Should use default reflective adapter
|
// Should use default reflective adapter
|
||||||
String json2 = gson.toJson(new CustomClass2());
|
String json2 = gson.toJson(new CustomClass2());
|
||||||
assertEquals("{}", json2);
|
assertThat(json2).isEqualTo("{}");
|
||||||
|
|
||||||
// Should use default instance creator
|
// Should use default instance creator
|
||||||
CustomClass3 customClass3 = gson.fromJson("{}", CustomClass3.class);
|
CustomClass3 customClass3 = gson.fromJson("{}", CustomClass3.class);
|
||||||
assertEquals(CustomClass3.NO_ARG_CONSTRUCTOR_VALUE, customClass3.s);
|
assertThat(customClass3.s).isEqualTo(CustomClass3.NO_ARG_CONSTRUCTOR_VALUE);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -278,6 +397,7 @@ public final class GsonTest extends TestCase {
|
||||||
* Gson instance (created using a GsonBuilder) should not affect the Gson instance
|
* Gson instance (created using a GsonBuilder) should not affect the Gson instance
|
||||||
* it came from.
|
* it came from.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testNewBuilderModification() {
|
public void testNewBuilderModification() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.registerTypeAdapter(CustomClass1.class, new TypeAdapter<CustomClass1>() {
|
.registerTypeAdapter(CustomClass1.class, new TypeAdapter<CustomClass1>() {
|
||||||
|
@ -333,29 +453,29 @@ public final class GsonTest extends TestCase {
|
||||||
// But new Gson instance from `gsonBuilder` should be affected by changes
|
// But new Gson instance from `gsonBuilder` should be affected by changes
|
||||||
Gson otherGson = gsonBuilder.create();
|
Gson otherGson = gsonBuilder.create();
|
||||||
String json1 = otherGson.toJson(new CustomClass1());
|
String json1 = otherGson.toJson(new CustomClass1());
|
||||||
assertEquals("\"overwritten custom-adapter\"", json1);
|
assertThat(json1).isEqualTo("\"overwritten custom-adapter\"");
|
||||||
|
|
||||||
String json2 = otherGson.toJson(new CustomClass2());
|
String json2 = otherGson.toJson(new CustomClass2());
|
||||||
assertEquals("\"overwritten custom-hierarchy-adapter\"", json2);
|
assertThat(json2).isEqualTo("\"overwritten custom-hierarchy-adapter\"");
|
||||||
|
|
||||||
CustomClass3 customClass3 = otherGson.fromJson("{}", CustomClass3.class);
|
CustomClass3 customClass3 = otherGson.fromJson("{}", CustomClass3.class);
|
||||||
assertEquals("overwritten custom-instance", customClass3.s);
|
assertThat(customClass3.s).isEqualTo("overwritten custom-instance");
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void assertCustomGson(Gson gson) {
|
private static void assertCustomGson(Gson gson) {
|
||||||
String json1 = gson.toJson(new CustomClass1());
|
String json1 = gson.toJson(new CustomClass1());
|
||||||
assertEquals("\"custom-adapter\"", json1);
|
assertThat(json1).isEqualTo("\"custom-adapter\"");
|
||||||
|
|
||||||
String json2 = gson.toJson(new CustomClass2());
|
String json2 = gson.toJson(new CustomClass2());
|
||||||
assertEquals("\"custom-hierarchy-adapter\"", json2);
|
assertThat(json2).isEqualTo("\"custom-hierarchy-adapter\"");
|
||||||
|
|
||||||
CustomClass3 customClass3 = gson.fromJson("{}", CustomClass3.class);
|
CustomClass3 customClass3 = gson.fromJson("{}", CustomClass3.class);
|
||||||
assertEquals("custom-instance", customClass3.s);
|
assertThat(customClass3.s).isEqualTo("custom-instance");
|
||||||
}
|
}
|
||||||
|
|
||||||
static class CustomClass1 { }
|
private static class CustomClass1 { }
|
||||||
static class CustomClass2 { }
|
private static class CustomClass2 { }
|
||||||
static class CustomClass3 {
|
private static class CustomClass3 {
|
||||||
static final String NO_ARG_CONSTRUCTOR_VALUE = "default instance";
|
static final String NO_ARG_CONSTRUCTOR_VALUE = "default instance";
|
||||||
|
|
||||||
final String s;
|
final String s;
|
||||||
|
@ -364,6 +484,7 @@ public final class GsonTest extends TestCase {
|
||||||
this.s = s;
|
this.s = s;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unused") // called by Gson
|
||||||
public CustomClass3() {
|
public CustomClass3() {
|
||||||
this(NO_ARG_CONSTRUCTOR_VALUE);
|
this(NO_ARG_CONSTRUCTOR_VALUE);
|
||||||
}
|
}
|
||||||
|
|
|
@ -16,11 +16,15 @@
|
||||||
|
|
||||||
package com.google.gson;
|
package com.google.gson;
|
||||||
|
|
||||||
|
import static com.google.common.truth.Truth.assertThat;
|
||||||
|
import static org.junit.Assert.fail;
|
||||||
|
|
||||||
import java.lang.reflect.Type;
|
import java.lang.reflect.Type;
|
||||||
import java.math.BigInteger;
|
import java.math.BigInteger;
|
||||||
import java.util.concurrent.atomic.AtomicInteger;
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
import java.util.concurrent.atomic.AtomicLong;
|
import java.util.concurrent.atomic.AtomicLong;
|
||||||
import junit.framework.TestCase;
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Contains numerous tests involving registered type converters with a Gson instance.
|
* Contains numerous tests involving registered type converters with a Gson instance.
|
||||||
|
@ -28,18 +32,18 @@ import junit.framework.TestCase;
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
* @author Joel Leitch
|
* @author Joel Leitch
|
||||||
*/
|
*/
|
||||||
public class GsonTypeAdapterTest extends TestCase {
|
public class GsonTypeAdapterTest {
|
||||||
private Gson gson;
|
private Gson gson;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
gson = new GsonBuilder()
|
gson = new GsonBuilder()
|
||||||
.registerTypeAdapter(AtomicLong.class, new ExceptionTypeAdapter())
|
.registerTypeAdapter(AtomicLong.class, new ExceptionTypeAdapter())
|
||||||
.registerTypeAdapter(AtomicInteger.class, new AtomicIntegerTypeAdapter())
|
.registerTypeAdapter(AtomicInteger.class, new AtomicIntegerTypeAdapter())
|
||||||
.create();
|
.create();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDefaultTypeAdapterThrowsParseException() throws Exception {
|
public void testDefaultTypeAdapterThrowsParseException() throws Exception {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("{\"abc\":123}", BigInteger.class);
|
gson.fromJson("{\"abc\":123}", BigInteger.class);
|
||||||
|
@ -47,6 +51,7 @@ public class GsonTypeAdapterTest extends TestCase {
|
||||||
} catch (JsonParseException expected) { }
|
} catch (JsonParseException expected) { }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testTypeAdapterThrowsException() throws Exception {
|
public void testTypeAdapterThrowsException() throws Exception {
|
||||||
try {
|
try {
|
||||||
gson.toJson(new AtomicLong(0));
|
gson.toJson(new AtomicLong(0));
|
||||||
|
@ -54,7 +59,7 @@ public class GsonTypeAdapterTest extends TestCase {
|
||||||
} catch (IllegalStateException expected) { }
|
} catch (IllegalStateException expected) { }
|
||||||
|
|
||||||
// Verify that serializer is made null-safe, i.e. it is not called for null
|
// Verify that serializer is made null-safe, i.e. it is not called for null
|
||||||
assertEquals("null", gson.toJson(null, AtomicLong.class));
|
assertThat(gson.toJson(null, AtomicLong.class)).isEqualTo("null");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
gson.fromJson("123", AtomicLong.class);
|
gson.fromJson("123", AtomicLong.class);
|
||||||
|
@ -62,26 +67,28 @@ public class GsonTypeAdapterTest extends TestCase {
|
||||||
} catch (JsonParseException expected) { }
|
} catch (JsonParseException expected) { }
|
||||||
|
|
||||||
// Verify that deserializer is made null-safe, i.e. it is not called for null
|
// Verify that deserializer is made null-safe, i.e. it is not called for null
|
||||||
assertNull(gson.fromJson(JsonNull.INSTANCE, AtomicLong.class));
|
assertThat(gson.fromJson(JsonNull.INSTANCE, AtomicLong.class)).isNull();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void testTypeAdapterProperlyConvertsTypes() throws Exception {
|
@Test
|
||||||
|
public void testTypeAdapterProperlyConvertsTypes() {
|
||||||
int intialValue = 1;
|
int intialValue = 1;
|
||||||
AtomicInteger atomicInt = new AtomicInteger(intialValue);
|
AtomicInteger atomicInt = new AtomicInteger(intialValue);
|
||||||
String json = gson.toJson(atomicInt);
|
String json = gson.toJson(atomicInt);
|
||||||
assertEquals(intialValue + 1, Integer.parseInt(json));
|
assertThat(Integer.parseInt(json)).isEqualTo(intialValue + 1);
|
||||||
|
|
||||||
atomicInt = gson.fromJson(json, AtomicInteger.class);
|
atomicInt = gson.fromJson(json, AtomicInteger.class);
|
||||||
assertEquals(intialValue, atomicInt.get());
|
assertThat(atomicInt.get()).isEqualTo(intialValue);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void testTypeAdapterDoesNotAffectNonAdaptedTypes() throws Exception {
|
@Test
|
||||||
|
public void testTypeAdapterDoesNotAffectNonAdaptedTypes() {
|
||||||
String expected = "blah";
|
String expected = "blah";
|
||||||
String actual = gson.toJson(expected);
|
String actual = gson.toJson(expected);
|
||||||
assertEquals("\"" + expected + "\"", actual);
|
assertThat(actual).isEqualTo("\"" + expected + "\"");
|
||||||
|
|
||||||
actual = gson.fromJson(actual, String.class);
|
actual = gson.fromJson(actual, String.class);
|
||||||
assertEquals(expected, actual);
|
assertThat(actual).isEqualTo(expected);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static class ExceptionTypeAdapter
|
private static class ExceptionTypeAdapter
|
||||||
|
@ -119,6 +126,7 @@ public class GsonTypeAdapterTest extends TestCase {
|
||||||
}
|
}
|
||||||
|
|
||||||
// https://groups.google.com/d/topic/google-gson/EBmOCa8kJPE/discussion
|
// https://groups.google.com/d/topic/google-gson/EBmOCa8kJPE/discussion
|
||||||
|
@Test
|
||||||
public void testDeserializerForAbstractClass() {
|
public void testDeserializerForAbstractClass() {
|
||||||
Concrete instance = new Concrete();
|
Concrete instance = new Concrete();
|
||||||
instance.a = "android";
|
instance.a = "android";
|
||||||
|
@ -149,6 +157,6 @@ public class GsonTypeAdapterTest extends TestCase {
|
||||||
builder.registerTypeHierarchyAdapter(Abstract.class, deserializer);
|
builder.registerTypeHierarchyAdapter(Abstract.class, deserializer);
|
||||||
}
|
}
|
||||||
Gson gson = builder.create();
|
Gson gson = builder.create();
|
||||||
assertEquals(expected, gson.toJson(instance, instanceType));
|
assertThat(gson.toJson(instance, instanceType)).isEqualTo(expected);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -16,38 +16,44 @@
|
||||||
|
|
||||||
package com.google.gson;
|
package com.google.gson;
|
||||||
|
|
||||||
|
import static com.google.common.truth.Truth.assertThat;
|
||||||
|
|
||||||
import com.google.gson.internal.Excluder;
|
import com.google.gson.internal.Excluder;
|
||||||
import java.lang.reflect.Field;
|
import java.lang.reflect.Field;
|
||||||
import junit.framework.TestCase;
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Unit test for GsonBuilder.EXCLUDE_INNER_CLASSES.
|
* Unit test for GsonBuilder.EXCLUDE_INNER_CLASSES.
|
||||||
*
|
*
|
||||||
* @author Joel Leitch
|
* @author Joel Leitch
|
||||||
*/
|
*/
|
||||||
public class InnerClassExclusionStrategyTest extends TestCase {
|
public class InnerClassExclusionStrategyTest {
|
||||||
public InnerClass innerClass = new InnerClass();
|
public InnerClass innerClass = new InnerClass();
|
||||||
public StaticNestedClass staticNestedClass = new StaticNestedClass();
|
public StaticNestedClass staticNestedClass = new StaticNestedClass();
|
||||||
private Excluder excluder = Excluder.DEFAULT.disableInnerClassSerialization();
|
private Excluder excluder = Excluder.DEFAULT.disableInnerClassSerialization();
|
||||||
|
|
||||||
public void testExcludeInnerClassObject() throws Exception {
|
@Test
|
||||||
|
public void testExcludeInnerClassObject() {
|
||||||
Class<?> clazz = innerClass.getClass();
|
Class<?> clazz = innerClass.getClass();
|
||||||
assertTrue(excluder.excludeClass(clazz, true));
|
assertThat(excluder.excludeClass(clazz, true)).isTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testExcludeInnerClassField() throws Exception {
|
public void testExcludeInnerClassField() throws Exception {
|
||||||
Field f = getClass().getField("innerClass");
|
Field f = getClass().getField("innerClass");
|
||||||
assertTrue(excluder.excludeField(f, true));
|
assertThat(excluder.excludeField(f, true)).isTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void testIncludeStaticNestedClassObject() throws Exception {
|
@Test
|
||||||
|
public void testIncludeStaticNestedClassObject() {
|
||||||
Class<?> clazz = staticNestedClass.getClass();
|
Class<?> clazz = staticNestedClass.getClass();
|
||||||
assertFalse(excluder.excludeClass(clazz, true));
|
assertThat(excluder.excludeClass(clazz, true)).isFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testIncludeStaticNestedClassField() throws Exception {
|
public void testIncludeStaticNestedClassField() throws Exception {
|
||||||
Field f = getClass().getField("staticNestedClass");
|
Field f = getClass().getField("staticNestedClass");
|
||||||
assertFalse(excluder.excludeField(f, true));
|
assertThat(excluder.excludeField(f, true)).isFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
class InnerClass {
|
class InnerClass {
|
||||||
|
|
|
@ -16,6 +16,8 @@
|
||||||
|
|
||||||
package com.google.gson;
|
package com.google.gson;
|
||||||
|
|
||||||
|
import static com.google.common.truth.Truth.assertThat;
|
||||||
|
|
||||||
import com.google.gson.reflect.TypeToken;
|
import com.google.gson.reflect.TypeToken;
|
||||||
import java.io.ByteArrayInputStream;
|
import java.io.ByteArrayInputStream;
|
||||||
import java.io.ByteArrayOutputStream;
|
import java.io.ByteArrayOutputStream;
|
||||||
|
@ -23,43 +25,44 @@ import java.io.IOException;
|
||||||
import java.io.ObjectInputStream;
|
import java.io.ObjectInputStream;
|
||||||
import java.io.ObjectOutputStream;
|
import java.io.ObjectOutputStream;
|
||||||
import java.lang.reflect.Type;
|
import java.lang.reflect.Type;
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import junit.framework.TestCase;
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Check that Gson doesn't return non-serializable data types.
|
* Check that Gson doesn't return non-serializable data types.
|
||||||
*
|
*
|
||||||
* @author Jesse Wilson
|
* @author Jesse Wilson
|
||||||
*/
|
*/
|
||||||
public final class JavaSerializationTest extends TestCase {
|
public final class JavaSerializationTest {
|
||||||
private final Gson gson = new Gson();
|
private final Gson gson = new Gson();
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testMapIsSerializable() throws Exception {
|
public void testMapIsSerializable() throws Exception {
|
||||||
Type type = new TypeToken<Map<String, Integer>>() {}.getType();
|
Type type = new TypeToken<Map<String, Integer>>() {}.getType();
|
||||||
Map<String, Integer> map = gson.fromJson("{\"b\":1,\"c\":2,\"a\":3}", type);
|
Map<String, Integer> map = gson.fromJson("{\"b\":1,\"c\":2,\"a\":3}", type);
|
||||||
Map<String, Integer> serialized = serializedCopy(map);
|
Map<String, Integer> serialized = serializedCopy(map);
|
||||||
assertEquals(map, serialized);
|
assertThat(serialized).isEqualTo(map);
|
||||||
// Also check that the iteration order is retained.
|
// Also check that the iteration order is retained.
|
||||||
assertEquals(Arrays.asList("b", "c", "a"), new ArrayList<>(serialized.keySet()));
|
assertThat(serialized.keySet()).containsExactly("b", "c", "a").inOrder();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testListIsSerializable() throws Exception {
|
public void testListIsSerializable() throws Exception {
|
||||||
Type type = new TypeToken<List<String>>() {}.getType();
|
Type type = new TypeToken<List<String>>() {}.getType();
|
||||||
List<String> list = gson.fromJson("[\"a\",\"b\",\"c\"]", type);
|
List<String> list = gson.fromJson("[\"a\",\"b\",\"c\"]", type);
|
||||||
List<String> serialized = serializedCopy(list);
|
List<String> serialized = serializedCopy(list);
|
||||||
assertEquals(list, serialized);
|
assertThat(serialized).isEqualTo(list);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNumberIsSerializable() throws Exception {
|
public void testNumberIsSerializable() throws Exception {
|
||||||
Type type = new TypeToken<List<Number>>() {}.getType();
|
Type type = new TypeToken<List<Number>>() {}.getType();
|
||||||
List<Number> list = gson.fromJson("[1,3.14,6.673e-11]", type);
|
List<Number> list = gson.fromJson("[1,3.14,6.673e-11]", type);
|
||||||
List<Number> serialized = serializedCopy(list);
|
List<Number> serialized = serializedCopy(list);
|
||||||
assertEquals(1.0, serialized.get(0).doubleValue());
|
assertThat(serialized.get(0).doubleValue()).isEqualTo(1.0);
|
||||||
assertEquals(3.14, serialized.get(1).doubleValue());
|
assertThat(serialized.get(1).doubleValue()).isEqualTo(3.14);
|
||||||
assertEquals(6.673e-11, serialized.get(2).doubleValue());
|
assertThat(serialized.get(2).doubleValue()).isEqualTo(6.673e-11);
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings("unchecked") // Serialization promises to return the same type.
|
@SuppressWarnings("unchecked") // Serialization promises to return the same type.
|
||||||
|
|
|
@ -1,10 +1,6 @@
|
||||||
package com.google.gson;
|
package com.google.gson;
|
||||||
|
|
||||||
import static org.junit.Assert.assertArrayEquals;
|
import static com.google.common.truth.Truth.assertThat;
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
import static org.junit.Assert.assertFalse;
|
|
||||||
import static org.junit.Assert.assertSame;
|
|
||||||
import static org.junit.Assert.assertTrue;
|
|
||||||
import static org.junit.Assert.fail;
|
import static org.junit.Assert.fail;
|
||||||
|
|
||||||
import com.google.gson.common.MoreAsserts;
|
import com.google.gson.common.MoreAsserts;
|
||||||
|
@ -23,7 +19,7 @@ public class JsonArrayAsListTest {
|
||||||
a.add(1);
|
a.add(1);
|
||||||
|
|
||||||
List<JsonElement> list = a.asList();
|
List<JsonElement> list = a.asList();
|
||||||
assertEquals(new JsonPrimitive(1), list.get(0));
|
assertThat(list.get(0)).isEqualTo(new JsonPrimitive(1));
|
||||||
|
|
||||||
try {
|
try {
|
||||||
list.get(-1);
|
list.get(-1);
|
||||||
|
@ -38,7 +34,7 @@ public class JsonArrayAsListTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
a.add((JsonElement) null);
|
a.add((JsonElement) null);
|
||||||
assertEquals(JsonNull.INSTANCE, list.get(1));
|
assertThat(list.get(1)).isEqualTo(JsonNull.INSTANCE);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -47,9 +43,9 @@ public class JsonArrayAsListTest {
|
||||||
a.add(1);
|
a.add(1);
|
||||||
|
|
||||||
List<JsonElement> list = a.asList();
|
List<JsonElement> list = a.asList();
|
||||||
assertEquals(1, list.size());
|
assertThat(list).hasSize(1);
|
||||||
list.add(new JsonPrimitive(2));
|
list.add(new JsonPrimitive(2));
|
||||||
assertEquals(2, list.size());
|
assertThat(list).hasSize(2);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -59,9 +55,9 @@ public class JsonArrayAsListTest {
|
||||||
|
|
||||||
List<JsonElement> list = a.asList();
|
List<JsonElement> list = a.asList();
|
||||||
JsonElement old = list.set(0, new JsonPrimitive(2));
|
JsonElement old = list.set(0, new JsonPrimitive(2));
|
||||||
assertEquals(new JsonPrimitive(1), old);
|
assertThat(old).isEqualTo(new JsonPrimitive(1));
|
||||||
assertEquals(new JsonPrimitive(2), list.get(0));
|
assertThat(list.get(0)).isEqualTo(new JsonPrimitive(2));
|
||||||
assertEquals(new JsonPrimitive(2), a.get(0));
|
assertThat(a.get(0)).isEqualTo(new JsonPrimitive(2));
|
||||||
|
|
||||||
try {
|
try {
|
||||||
list.set(-1, new JsonPrimitive(1));
|
list.set(-1, new JsonPrimitive(1));
|
||||||
|
@ -79,7 +75,7 @@ public class JsonArrayAsListTest {
|
||||||
list.set(0, null);
|
list.set(0, null);
|
||||||
fail();
|
fail();
|
||||||
} catch (NullPointerException e) {
|
} catch (NullPointerException e) {
|
||||||
assertEquals("Element must be non-null", e.getMessage());
|
assertThat(e).hasMessageThat().isEqualTo("Element must be non-null");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -91,8 +87,8 @@ public class JsonArrayAsListTest {
|
||||||
List<JsonElement> list = a.asList();
|
List<JsonElement> list = a.asList();
|
||||||
list.add(0, new JsonPrimitive(2));
|
list.add(0, new JsonPrimitive(2));
|
||||||
list.add(1, new JsonPrimitive(3));
|
list.add(1, new JsonPrimitive(3));
|
||||||
assertTrue(list.add(new JsonPrimitive(4)));
|
assertThat(list.add(new JsonPrimitive(4))).isTrue();
|
||||||
assertTrue(list.add(JsonNull.INSTANCE));
|
assertThat(list.add(JsonNull.INSTANCE)).isTrue();
|
||||||
|
|
||||||
List<JsonElement> expectedList = Arrays.<JsonElement>asList(
|
List<JsonElement> expectedList = Arrays.<JsonElement>asList(
|
||||||
new JsonPrimitive(2),
|
new JsonPrimitive(2),
|
||||||
|
@ -101,7 +97,7 @@ public class JsonArrayAsListTest {
|
||||||
new JsonPrimitive(4),
|
new JsonPrimitive(4),
|
||||||
JsonNull.INSTANCE
|
JsonNull.INSTANCE
|
||||||
);
|
);
|
||||||
assertEquals(expectedList, list);
|
assertThat(list).isEqualTo(expectedList);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
list.set(-1, new JsonPrimitive(1));
|
list.set(-1, new JsonPrimitive(1));
|
||||||
|
@ -119,13 +115,13 @@ public class JsonArrayAsListTest {
|
||||||
list.add(0, null);
|
list.add(0, null);
|
||||||
fail();
|
fail();
|
||||||
} catch (NullPointerException e) {
|
} catch (NullPointerException e) {
|
||||||
assertEquals("Element must be non-null", e.getMessage());
|
assertThat(e).hasMessageThat().isEqualTo("Element must be non-null");
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
list.add(null);
|
list.add(null);
|
||||||
fail();
|
fail();
|
||||||
} catch (NullPointerException e) {
|
} catch (NullPointerException e) {
|
||||||
assertEquals("Element must be non-null", e.getMessage());
|
assertThat(e).hasMessageThat().isEqualTo("Element must be non-null");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -142,19 +138,20 @@ public class JsonArrayAsListTest {
|
||||||
new JsonPrimitive(2),
|
new JsonPrimitive(2),
|
||||||
new JsonPrimitive(3)
|
new JsonPrimitive(3)
|
||||||
);
|
);
|
||||||
assertEquals(expectedList, list);
|
assertThat(list).isEqualTo(expectedList);
|
||||||
|
assertThat(list).isEqualTo(expectedList);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
list.addAll(0, Collections.<JsonElement>singletonList(null));
|
list.addAll(0, Collections.<JsonElement>singletonList(null));
|
||||||
fail();
|
fail();
|
||||||
} catch (NullPointerException e) {
|
} catch (NullPointerException e) {
|
||||||
assertEquals("Element must be non-null", e.getMessage());
|
assertThat(e).hasMessageThat().isEqualTo("Element must be non-null");
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
list.addAll(Collections.<JsonElement>singletonList(null));
|
list.addAll(Collections.<JsonElement>singletonList(null));
|
||||||
fail();
|
fail();
|
||||||
} catch (NullPointerException e) {
|
} catch (NullPointerException e) {
|
||||||
assertEquals("Element must be non-null", e.getMessage());
|
assertThat(e).hasMessageThat().isEqualTo("Element must be non-null");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -164,10 +161,9 @@ public class JsonArrayAsListTest {
|
||||||
a.add(1);
|
a.add(1);
|
||||||
|
|
||||||
List<JsonElement> list = a.asList();
|
List<JsonElement> list = a.asList();
|
||||||
assertEquals(new JsonPrimitive(1), list.remove(0));
|
assertThat(list.remove(0)).isEqualTo(new JsonPrimitive(1));
|
||||||
assertEquals(0, list.size());
|
assertThat(list).hasSize(0);
|
||||||
assertEquals(0, a.size());
|
assertThat(a).hasSize(0);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
list.remove(0);
|
list.remove(0);
|
||||||
fail();
|
fail();
|
||||||
|
@ -181,12 +177,12 @@ public class JsonArrayAsListTest {
|
||||||
a.add(1);
|
a.add(1);
|
||||||
|
|
||||||
List<JsonElement> list = a.asList();
|
List<JsonElement> list = a.asList();
|
||||||
assertTrue(list.remove(new JsonPrimitive(1)));
|
assertThat(list.remove(new JsonPrimitive(1))).isTrue();
|
||||||
assertEquals(0, list.size());
|
assertThat(list).hasSize(0);
|
||||||
assertEquals(0, a.size());
|
assertThat(a).hasSize(0);
|
||||||
|
|
||||||
assertFalse(list.remove(new JsonPrimitive(1)));
|
assertThat(list.remove(new JsonPrimitive(1))).isFalse();
|
||||||
assertFalse(list.remove(null));
|
assertThat(list.remove(null)).isFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -196,8 +192,8 @@ public class JsonArrayAsListTest {
|
||||||
|
|
||||||
List<JsonElement> list = a.asList();
|
List<JsonElement> list = a.asList();
|
||||||
list.clear();
|
list.clear();
|
||||||
assertEquals(0, list.size());
|
assertThat(list).hasSize(0);
|
||||||
assertEquals(0, a.size());
|
assertThat(a).hasSize(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -206,13 +202,13 @@ public class JsonArrayAsListTest {
|
||||||
a.add(1);
|
a.add(1);
|
||||||
|
|
||||||
List<JsonElement> list = a.asList();
|
List<JsonElement> list = a.asList();
|
||||||
assertTrue(list.contains(new JsonPrimitive(1)));
|
assertThat(list.contains(new JsonPrimitive(1))).isTrue();
|
||||||
assertFalse(list.contains(new JsonPrimitive(2)));
|
assertThat(list.contains(new JsonPrimitive(2))).isFalse();
|
||||||
assertFalse(list.contains(null));
|
assertThat(list.contains(null)).isFalse();
|
||||||
|
|
||||||
@SuppressWarnings({"unlikely-arg-type", "CollectionIncompatibleType"})
|
@SuppressWarnings({"unlikely-arg-type", "CollectionIncompatibleType"})
|
||||||
boolean containsInt = list.contains(1); // should only contain JsonPrimitive(1)
|
boolean containsInt = list.contains(1); // should only contain JsonPrimitive(1)
|
||||||
assertFalse(containsInt);
|
assertThat(containsInt).isFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -223,17 +219,17 @@ public class JsonArrayAsListTest {
|
||||||
a.add(1);
|
a.add(1);
|
||||||
|
|
||||||
List<JsonElement> list = a.asList();
|
List<JsonElement> list = a.asList();
|
||||||
assertEquals(0, list.indexOf(new JsonPrimitive(1)));
|
assertThat(list.indexOf(new JsonPrimitive(1))).isEqualTo(0);
|
||||||
assertEquals(-1, list.indexOf(new JsonPrimitive(2)));
|
assertThat(list.indexOf(new JsonPrimitive(2))).isEqualTo(-1);
|
||||||
assertEquals(-1, list.indexOf(null));
|
assertThat(list.indexOf(null)).isEqualTo(-1);
|
||||||
|
|
||||||
@SuppressWarnings({"unlikely-arg-type", "CollectionIncompatibleType"})
|
@SuppressWarnings({"unlikely-arg-type", "CollectionIncompatibleType"})
|
||||||
int indexOfInt = list.indexOf(1); // should only contain JsonPrimitive(1)
|
int indexOfInt = list.indexOf(1); // should only contain JsonPrimitive(1)
|
||||||
assertEquals(-1, indexOfInt);
|
assertThat(indexOfInt).isEqualTo(-1);
|
||||||
|
|
||||||
assertEquals(1, list.lastIndexOf(new JsonPrimitive(1)));
|
assertThat(list.lastIndexOf(new JsonPrimitive(1))).isEqualTo(1);
|
||||||
assertEquals(-1, list.lastIndexOf(new JsonPrimitive(2)));
|
assertThat(list.lastIndexOf(new JsonPrimitive(2))).isEqualTo(-1);
|
||||||
assertEquals(-1, list.lastIndexOf(null));
|
assertThat(list.lastIndexOf(null)).isEqualTo(-1);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -242,19 +238,19 @@ public class JsonArrayAsListTest {
|
||||||
a.add(1);
|
a.add(1);
|
||||||
|
|
||||||
List<JsonElement> list = a.asList();
|
List<JsonElement> list = a.asList();
|
||||||
assertArrayEquals(new Object[] {new JsonPrimitive(1)}, list.toArray());
|
assertThat(list.toArray()).isEqualTo(new Object[] {new JsonPrimitive(1)});
|
||||||
|
|
||||||
JsonElement[] array = list.toArray(new JsonElement[0]);
|
JsonElement[] array = list.toArray(new JsonElement[0]);
|
||||||
assertArrayEquals(new Object[] {new JsonPrimitive(1)}, array);
|
assertThat(array).isEqualTo(new Object[] {new JsonPrimitive(1)});
|
||||||
|
|
||||||
array = new JsonElement[1];
|
array = new JsonElement[1];
|
||||||
assertSame(array, list.toArray(array));
|
assertThat(list.toArray(array)).isEqualTo(array);
|
||||||
assertArrayEquals(new Object[] {new JsonPrimitive(1)}, array);
|
assertThat(array).isEqualTo(new Object[] {new JsonPrimitive(1)});
|
||||||
|
|
||||||
array = new JsonElement[] {null, new JsonPrimitive(2)};
|
array = new JsonElement[] {null, new JsonPrimitive(2)};
|
||||||
assertSame(array, list.toArray(array));
|
assertThat(list.toArray(array)).isEqualTo(array);
|
||||||
// Should have set existing array element to null
|
// Should have set existing array element to null
|
||||||
assertArrayEquals(new Object[] {new JsonPrimitive(1), null}, array);
|
assertThat(array).isEqualTo(new Object[] {new JsonPrimitive(1), null});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -264,8 +260,8 @@ public class JsonArrayAsListTest {
|
||||||
|
|
||||||
List<JsonElement> list = a.asList();
|
List<JsonElement> list = a.asList();
|
||||||
MoreAsserts.assertEqualsAndHashCode(list, Collections.singletonList(new JsonPrimitive(1)));
|
MoreAsserts.assertEqualsAndHashCode(list, Collections.singletonList(new JsonPrimitive(1)));
|
||||||
assertFalse(list.equals(Collections.emptyList()));
|
assertThat(list.equals(Collections.emptyList())).isFalse();
|
||||||
assertFalse(list.equals(Collections.singletonList(new JsonPrimitive(2))));
|
assertThat(list.equals(Collections.singletonList(new JsonPrimitive(2)))).isFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Verify that {@code JsonArray} updates are visible to view and vice versa */
|
/** Verify that {@code JsonArray} updates are visible to view and vice versa */
|
||||||
|
@ -275,11 +271,11 @@ public class JsonArrayAsListTest {
|
||||||
List<JsonElement> list = a.asList();
|
List<JsonElement> list = a.asList();
|
||||||
|
|
||||||
a.add(1);
|
a.add(1);
|
||||||
assertEquals(1, list.size());
|
assertThat(list).hasSize(1);
|
||||||
assertEquals(new JsonPrimitive(1), list.get(0));
|
assertThat(list.get(0)).isEqualTo(new JsonPrimitive(1));
|
||||||
|
|
||||||
list.add(new JsonPrimitive(2));
|
list.add(new JsonPrimitive(2));
|
||||||
assertEquals(2, a.size());
|
assertThat(a).hasSize(2);
|
||||||
assertEquals(new JsonPrimitive(2), a.get(1));
|
assertThat(a.get(1)).isEqualTo(new JsonPrimitive(2));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -16,9 +16,8 @@
|
||||||
|
|
||||||
package com.google.gson;
|
package com.google.gson;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static com.google.common.truth.Truth.assertThat;
|
||||||
import static org.junit.Assert.assertFalse;
|
import static com.google.common.truth.Truth.assertWithMessage;
|
||||||
import static org.junit.Assert.assertTrue;
|
|
||||||
import static org.junit.Assert.fail;
|
import static org.junit.Assert.fail;
|
||||||
|
|
||||||
import com.google.gson.common.MoreAsserts;
|
import com.google.gson.common.MoreAsserts;
|
||||||
|
@ -40,22 +39,22 @@ public final class JsonArrayTest {
|
||||||
JsonArray a = new JsonArray();
|
JsonArray a = new JsonArray();
|
||||||
JsonArray b = new JsonArray();
|
JsonArray b = new JsonArray();
|
||||||
|
|
||||||
assertEquals(a, a);
|
assertThat(a).isEqualTo(a);
|
||||||
|
|
||||||
a.add(new JsonObject());
|
a.add(new JsonObject());
|
||||||
assertFalse(a.equals(b));
|
assertThat(a.equals(b)).isFalse();
|
||||||
assertFalse(b.equals(a));
|
assertThat(b.equals(a)).isFalse();
|
||||||
|
|
||||||
b.add(new JsonObject());
|
b.add(new JsonObject());
|
||||||
MoreAsserts.assertEqualsAndHashCode(a, b);
|
MoreAsserts.assertEqualsAndHashCode(a, b);
|
||||||
|
|
||||||
a.add(new JsonObject());
|
a.add(new JsonObject());
|
||||||
assertFalse(a.equals(b));
|
assertThat(a.equals(b)).isFalse();
|
||||||
assertFalse(b.equals(a));
|
assertThat(b.equals(a)).isFalse();
|
||||||
|
|
||||||
b.add(JsonNull.INSTANCE);
|
b.add(JsonNull.INSTANCE);
|
||||||
assertFalse(a.equals(b));
|
assertThat(a.equals(b)).isFalse();
|
||||||
assertFalse(b.equals(a));
|
assertThat(b.equals(a)).isFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -67,13 +66,13 @@ public final class JsonArrayTest {
|
||||||
} catch (IndexOutOfBoundsException expected) {}
|
} catch (IndexOutOfBoundsException expected) {}
|
||||||
JsonPrimitive a = new JsonPrimitive("a");
|
JsonPrimitive a = new JsonPrimitive("a");
|
||||||
array.add(a);
|
array.add(a);
|
||||||
assertTrue(array.remove(a));
|
assertThat(array.remove(a)).isTrue();
|
||||||
assertFalse(array.contains(a));
|
assertThat(array.contains(a)).isFalse();
|
||||||
array.add(a);
|
array.add(a);
|
||||||
array.add(new JsonPrimitive("b"));
|
array.add(new JsonPrimitive("b"));
|
||||||
assertEquals("b", array.remove(1).getAsString());
|
assertThat(array.remove(1).getAsString()).isEqualTo("b");
|
||||||
assertEquals(1, array.size());
|
assertThat(array).hasSize(1);
|
||||||
assertTrue(array.contains(a));
|
assertThat(array.contains(a)).isTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -88,17 +87,17 @@ public final class JsonArrayTest {
|
||||||
|
|
||||||
JsonPrimitive b = new JsonPrimitive("b");
|
JsonPrimitive b = new JsonPrimitive("b");
|
||||||
JsonElement oldValue = array.set(0, b);
|
JsonElement oldValue = array.set(0, b);
|
||||||
assertEquals(a, oldValue);
|
assertThat(oldValue).isEqualTo(a);
|
||||||
assertEquals("b", array.get(0).getAsString());
|
assertThat(array.get(0).getAsString()).isEqualTo("b");
|
||||||
|
|
||||||
oldValue = array.set(0, null);
|
oldValue = array.set(0, null);
|
||||||
assertEquals(b, oldValue);
|
assertThat(oldValue).isEqualTo(b);
|
||||||
assertEquals(JsonNull.INSTANCE, array.get(0));
|
assertThat(array.get(0)).isEqualTo(JsonNull.INSTANCE);
|
||||||
|
|
||||||
oldValue = array.set(0, new JsonPrimitive("c"));
|
oldValue = array.set(0, new JsonPrimitive("c"));
|
||||||
assertEquals(JsonNull.INSTANCE, oldValue);
|
assertThat(oldValue).isEqualTo(JsonNull.INSTANCE);
|
||||||
assertEquals("c", array.get(0).getAsString());
|
assertThat(array.get(0).getAsString()).isEqualTo("c");
|
||||||
assertEquals(1, array.size());
|
assertThat(array).hasSize(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -110,24 +109,24 @@ public final class JsonArrayTest {
|
||||||
JsonArray copy = original.deepCopy();
|
JsonArray copy = original.deepCopy();
|
||||||
original.add(new JsonPrimitive("y"));
|
original.add(new JsonPrimitive("y"));
|
||||||
|
|
||||||
assertEquals(1, copy.size());
|
assertThat(copy).hasSize(1);
|
||||||
firstEntry.add(new JsonPrimitive("z"));
|
firstEntry.add(new JsonPrimitive("z"));
|
||||||
|
|
||||||
assertEquals(1, original.get(0).getAsJsonArray().size());
|
assertThat(original.get(0).getAsJsonArray()).hasSize(1);
|
||||||
assertEquals(0, copy.get(0).getAsJsonArray().size());
|
assertThat(copy.get(0).getAsJsonArray()).hasSize(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testIsEmpty() {
|
public void testIsEmpty() {
|
||||||
JsonArray array = new JsonArray();
|
JsonArray array = new JsonArray();
|
||||||
assertTrue(array.isEmpty());
|
assertThat(array).isEmpty();
|
||||||
|
|
||||||
JsonPrimitive a = new JsonPrimitive("a");
|
JsonPrimitive a = new JsonPrimitive("a");
|
||||||
array.add(a);
|
array.add(a);
|
||||||
assertFalse(array.isEmpty());
|
assertThat(array).isNotEmpty();
|
||||||
|
|
||||||
array.remove(0);
|
array.remove(0);
|
||||||
assertTrue(array.isEmpty());
|
assertThat(array).isEmpty();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -138,22 +137,22 @@ public final class JsonArrayTest {
|
||||||
jsonArray.getAsBoolean();
|
jsonArray.getAsBoolean();
|
||||||
fail("expected getBoolean to fail");
|
fail("expected getBoolean to fail");
|
||||||
} catch (UnsupportedOperationException e) {
|
} catch (UnsupportedOperationException e) {
|
||||||
assertEquals("Expected an exception message",
|
assertWithMessage("Expected an exception message")
|
||||||
"JsonObject", e.getMessage());
|
.that(e).hasMessageThat().isEqualTo("JsonObject");
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
jsonArray.get(-1);
|
jsonArray.get(-1);
|
||||||
fail("expected get to fail");
|
fail("expected get to fail");
|
||||||
} catch (IndexOutOfBoundsException e) {
|
} catch (IndexOutOfBoundsException e) {
|
||||||
assertEquals("Expected an exception message",
|
assertWithMessage("Expected an exception message")
|
||||||
"Index -1 out of bounds for length 1", e.getMessage());
|
.that(e).hasMessageThat().isEqualTo("Index -1 out of bounds for length 1");
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
jsonArray.getAsString();
|
jsonArray.getAsString();
|
||||||
fail("expected getString to fail");
|
fail("expected getString to fail");
|
||||||
} catch (UnsupportedOperationException e) {
|
} catch (UnsupportedOperationException e) {
|
||||||
assertEquals("Expected an exception message",
|
assertWithMessage("Expected an exception message")
|
||||||
"JsonObject", e.getMessage());
|
.that(e).hasMessageThat().isEqualTo("JsonObject");
|
||||||
}
|
}
|
||||||
|
|
||||||
jsonArray.remove(0);
|
jsonArray.remove(0);
|
||||||
|
@ -162,36 +161,36 @@ public final class JsonArrayTest {
|
||||||
jsonArray.getAsDouble();
|
jsonArray.getAsDouble();
|
||||||
fail("expected getDouble to fail");
|
fail("expected getDouble to fail");
|
||||||
} catch (NumberFormatException e) {
|
} catch (NumberFormatException e) {
|
||||||
assertEquals("Expected an exception message",
|
assertWithMessage("Expected an exception message")
|
||||||
"For input string: \"hello\"", e.getMessage());
|
.that(e).hasMessageThat().isEqualTo("For input string: \"hello\"");
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
jsonArray.getAsInt();
|
jsonArray.getAsInt();
|
||||||
fail("expected getInt to fail");
|
fail("expected getInt to fail");
|
||||||
} catch (NumberFormatException e) {
|
} catch (NumberFormatException e) {
|
||||||
assertEquals("Expected an exception message",
|
assertWithMessage("Expected an exception message")
|
||||||
"For input string: \"hello\"", e.getMessage());
|
.that(e).hasMessageThat().isEqualTo("For input string: \"hello\"");
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
jsonArray.get(0).getAsJsonArray();
|
jsonArray.get(0).getAsJsonArray();
|
||||||
fail("expected getJSONArray to fail");
|
fail("expected getJSONArray to fail");
|
||||||
} catch (IllegalStateException e) {
|
} catch (IllegalStateException e) {
|
||||||
assertEquals("Expected an exception message",
|
assertWithMessage("Expected an exception message")
|
||||||
"Not a JSON Array: \"hello\"", e.getMessage());
|
.that(e).hasMessageThat().isEqualTo("Not a JSON Array: \"hello\"");
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
jsonArray.getAsJsonObject();
|
jsonArray.getAsJsonObject();
|
||||||
fail("expected getJSONObject to fail");
|
fail("expected getJSONObject to fail");
|
||||||
} catch (IllegalStateException e) {
|
} catch (IllegalStateException e) {
|
||||||
assertEquals("Expected an exception message",
|
assertWithMessage("Expected an exception message")
|
||||||
"Not a JSON Object: [\"hello\"]", e.getMessage());
|
.that(e).hasMessageThat().isEqualTo( "Not a JSON Object: [\"hello\"]");
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
jsonArray.getAsLong();
|
jsonArray.getAsLong();
|
||||||
fail("expected getLong to fail");
|
fail("expected getLong to fail");
|
||||||
} catch (NumberFormatException e) {
|
} catch (NumberFormatException e) {
|
||||||
assertEquals("Expected an exception message",
|
assertWithMessage("Expected an exception message")
|
||||||
"For input string: \"hello\"", e.getMessage());
|
.that(e).hasMessageThat().isEqualTo("For input string: \"hello\"");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -202,7 +201,7 @@ public final class JsonArrayTest {
|
||||||
jsonArray.getAsByte();
|
jsonArray.getAsByte();
|
||||||
fail();
|
fail();
|
||||||
} catch (IllegalStateException e) {
|
} catch (IllegalStateException e) {
|
||||||
assertEquals("Array must have size 1, but has size 0", e.getMessage());
|
assertThat(e).hasMessageThat().isEqualTo("Array must have size 1, but has size 0");
|
||||||
}
|
}
|
||||||
|
|
||||||
jsonArray.add(true);
|
jsonArray.add(true);
|
||||||
|
@ -211,7 +210,7 @@ public final class JsonArrayTest {
|
||||||
jsonArray.getAsByte();
|
jsonArray.getAsByte();
|
||||||
fail();
|
fail();
|
||||||
} catch (IllegalStateException e) {
|
} catch (IllegalStateException e) {
|
||||||
assertEquals("Array must have size 1, but has size 2", e.getMessage());
|
assertThat(e).hasMessageThat().isEqualTo("Array must have size 1, but has size 2");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -225,7 +224,7 @@ public final class JsonArrayTest {
|
||||||
jsonArray.add((String) null);
|
jsonArray.add((String) null);
|
||||||
jsonArray.add("Yes");
|
jsonArray.add("Yes");
|
||||||
|
|
||||||
assertEquals("[\"Hello\",\"Goodbye\",\"Thank you\",null,\"Yes\"]", jsonArray.toString());
|
assertThat(jsonArray.toString()).isEqualTo("[\"Hello\",\"Goodbye\",\"Thank you\",null,\"Yes\"]");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -249,7 +248,7 @@ public final class JsonArrayTest {
|
||||||
x = 0;
|
x = 0;
|
||||||
jsonArray.add(x);
|
jsonArray.add(x);
|
||||||
|
|
||||||
assertEquals("[1,2,-3,null,4,0]", jsonArray.toString());
|
assertThat(jsonArray.toString()).isEqualTo("[1,2,-3,null,4,0]");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -272,7 +271,7 @@ public final class JsonArrayTest {
|
||||||
|
|
||||||
jsonArray.add((Double) null);
|
jsonArray.add((Double) null);
|
||||||
|
|
||||||
assertEquals("[1.0,2.13232,0.121,null,-0.00234,null]", jsonArray.toString());
|
assertThat(jsonArray.toString()).isEqualTo("[1.0,2.13232,0.121,null,-0.00234,null]");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -286,7 +285,7 @@ public final class JsonArrayTest {
|
||||||
jsonArray.add((Boolean) null);
|
jsonArray.add((Boolean) null);
|
||||||
jsonArray.add(true);
|
jsonArray.add(true);
|
||||||
|
|
||||||
assertEquals("[true,true,false,false,null,true]", jsonArray.toString());
|
assertThat(jsonArray.toString()).isEqualTo("[true,true,false,false,null,true]");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -301,7 +300,7 @@ public final class JsonArrayTest {
|
||||||
jsonArray.add('u');
|
jsonArray.add('u');
|
||||||
jsonArray.add("and sometimes Y");
|
jsonArray.add("and sometimes Y");
|
||||||
|
|
||||||
assertEquals("[\"a\",\"e\",\"i\",\"o\",null,\"u\",\"and sometimes Y\"]", jsonArray.toString());
|
assertThat(jsonArray.toString()).isEqualTo("[\"a\",\"e\",\"i\",\"o\",null,\"u\",\"and sometimes Y\"]");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -314,15 +313,15 @@ public final class JsonArrayTest {
|
||||||
jsonArray.add((char) 111);
|
jsonArray.add((char) 111);
|
||||||
|
|
||||||
jsonArray.add((Boolean) null);
|
jsonArray.add((Boolean) null);
|
||||||
assertEquals(JsonNull.INSTANCE, jsonArray.get(jsonArray.size() - 1));
|
assertThat(jsonArray.get(jsonArray.size() - 1)).isEqualTo(JsonNull.INSTANCE);
|
||||||
|
|
||||||
jsonArray.add((Character) null);
|
jsonArray.add((Character) null);
|
||||||
assertEquals(JsonNull.INSTANCE, jsonArray.get(jsonArray.size() - 1));
|
assertThat(jsonArray.get(jsonArray.size() - 1)).isEqualTo(JsonNull.INSTANCE);
|
||||||
|
|
||||||
jsonArray.add(12.232);
|
jsonArray.add(12.232);
|
||||||
jsonArray.add(BigInteger.valueOf(2323));
|
jsonArray.add(BigInteger.valueOf(2323));
|
||||||
|
|
||||||
assertEquals("[\"a\",\"apple\",12121,\"o\",null,null,12.232,2323]", jsonArray.toString());
|
assertThat(jsonArray.toString()).isEqualTo("[\"a\",\"apple\",12121,\"o\",null,null,12.232,2323]");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -339,10 +338,10 @@ public final class JsonArrayTest {
|
||||||
jsonArray.add((Boolean) null);
|
jsonArray.add((Boolean) null);
|
||||||
jsonArray.add((Number) null);
|
jsonArray.add((Number) null);
|
||||||
|
|
||||||
assertEquals("[null,null,null,null,null,null,null,null,null]", jsonArray.toString());
|
assertThat(jsonArray.toString()).isEqualTo("[null,null,null,null,null,null,null,null,null]");
|
||||||
for (int i = 0; i < jsonArray.size(); i++) {
|
for (int i = 0; i < jsonArray.size(); i++) {
|
||||||
// Verify that they are actually a JsonNull and not a Java null
|
// Verify that they are actually a JsonNull and not a Java null
|
||||||
assertEquals(JsonNull.INSTANCE, jsonArray.get(i));
|
assertThat(jsonArray.get(i)).isEqualTo(JsonNull.INSTANCE);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -350,7 +349,7 @@ public final class JsonArrayTest {
|
||||||
public void testNullJsonElementAddition() {
|
public void testNullJsonElementAddition() {
|
||||||
JsonArray jsonArray = new JsonArray();
|
JsonArray jsonArray = new JsonArray();
|
||||||
jsonArray.add((JsonElement) null);
|
jsonArray.add((JsonElement) null);
|
||||||
assertEquals(JsonNull.INSTANCE, jsonArray.get(0));
|
assertThat(jsonArray.get(0)).isEqualTo(JsonNull.INSTANCE);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -368,6 +367,6 @@ public final class JsonArrayTest {
|
||||||
jsonArray.add((Boolean) null);
|
jsonArray.add((Boolean) null);
|
||||||
jsonArray.add((Boolean) null);
|
jsonArray.add((Boolean) null);
|
||||||
|
|
||||||
assertEquals("[\"a\",\"a\",true,true,1212,1212,34.34,34.34,null,null]", jsonArray.toString());
|
assertThat(jsonArray.toString()).isEqualTo("[\"a\",\"a\",true,true,1212,1212,34.34,34.34,null,null]");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -16,25 +16,29 @@
|
||||||
|
|
||||||
package com.google.gson;
|
package com.google.gson;
|
||||||
|
|
||||||
|
import static com.google.common.truth.Truth.assertThat;
|
||||||
|
|
||||||
import com.google.gson.common.MoreAsserts;
|
import com.google.gson.common.MoreAsserts;
|
||||||
import junit.framework.TestCase;
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Jesse Wilson
|
* @author Jesse Wilson
|
||||||
*/
|
*/
|
||||||
public final class JsonNullTest extends TestCase {
|
public final class JsonNullTest {
|
||||||
|
|
||||||
@SuppressWarnings("deprecation")
|
@SuppressWarnings("deprecation")
|
||||||
|
@Test
|
||||||
public void testEqualsAndHashcode() {
|
public void testEqualsAndHashcode() {
|
||||||
MoreAsserts.assertEqualsAndHashCode(new JsonNull(), new JsonNull());
|
MoreAsserts.assertEqualsAndHashCode(new JsonNull(), new JsonNull());
|
||||||
MoreAsserts.assertEqualsAndHashCode(new JsonNull(), JsonNull.INSTANCE);
|
MoreAsserts.assertEqualsAndHashCode(new JsonNull(), JsonNull.INSTANCE);
|
||||||
MoreAsserts.assertEqualsAndHashCode(JsonNull.INSTANCE, JsonNull.INSTANCE);
|
MoreAsserts.assertEqualsAndHashCode(JsonNull.INSTANCE, JsonNull.INSTANCE);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeepCopy() {
|
public void testDeepCopy() {
|
||||||
@SuppressWarnings("deprecation")
|
@SuppressWarnings("deprecation")
|
||||||
JsonNull a = new JsonNull();
|
JsonNull a = new JsonNull();
|
||||||
assertSame(JsonNull.INSTANCE, a.deepCopy());
|
assertThat(a.deepCopy()).isSameInstanceAs(JsonNull.INSTANCE);
|
||||||
assertSame(JsonNull.INSTANCE, JsonNull.INSTANCE.deepCopy());
|
assertThat(JsonNull.INSTANCE.deepCopy()).isSameInstanceAs(JsonNull.INSTANCE);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,9 +1,6 @@
|
||||||
package com.google.gson;
|
package com.google.gson;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static com.google.common.truth.Truth.assertThat;
|
||||||
import static org.junit.Assert.assertFalse;
|
|
||||||
import static org.junit.Assert.assertNull;
|
|
||||||
import static org.junit.Assert.assertTrue;
|
|
||||||
import static org.junit.Assert.fail;
|
import static org.junit.Assert.fail;
|
||||||
|
|
||||||
import com.google.gson.common.MoreAsserts;
|
import com.google.gson.common.MoreAsserts;
|
||||||
|
@ -26,15 +23,15 @@ public class JsonObjectAsMapTest {
|
||||||
@Test
|
@Test
|
||||||
public void testSize() {
|
public void testSize() {
|
||||||
JsonObject o = new JsonObject();
|
JsonObject o = new JsonObject();
|
||||||
assertEquals(0, o.asMap().size());
|
assertThat(o.asMap().size()).isEqualTo(0);
|
||||||
|
|
||||||
o.addProperty("a", 1);
|
o.addProperty("a", 1);
|
||||||
Map<String, JsonElement> map = o.asMap();
|
Map<String, JsonElement> map = o.asMap();
|
||||||
assertEquals(1, map.size());
|
assertThat(map).hasSize(1);
|
||||||
|
|
||||||
map.clear();
|
map.clear();
|
||||||
assertEquals(0, map.size());
|
assertThat(map).hasSize(0);
|
||||||
assertEquals(0, o.size());
|
assertThat(o.size()).isEqualTo(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -43,9 +40,9 @@ public class JsonObjectAsMapTest {
|
||||||
o.addProperty("a", 1);
|
o.addProperty("a", 1);
|
||||||
|
|
||||||
Map<String, JsonElement> map = o.asMap();
|
Map<String, JsonElement> map = o.asMap();
|
||||||
assertTrue(map.containsKey("a"));
|
assertThat(map.containsKey("a")).isTrue();
|
||||||
assertFalse(map.containsKey("b"));
|
assertThat(map.containsKey("b")).isFalse();
|
||||||
assertFalse(map.containsKey(null));
|
assertThat(map.containsKey(null)).isFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -55,13 +52,13 @@ public class JsonObjectAsMapTest {
|
||||||
o.add("b", JsonNull.INSTANCE);
|
o.add("b", JsonNull.INSTANCE);
|
||||||
|
|
||||||
Map<String, JsonElement> map = o.asMap();
|
Map<String, JsonElement> map = o.asMap();
|
||||||
assertTrue(map.containsValue(new JsonPrimitive(1)));
|
assertThat(map.containsValue(new JsonPrimitive(1))).isTrue();
|
||||||
assertFalse(map.containsValue(new JsonPrimitive(2)));
|
assertThat(map.containsValue(new JsonPrimitive(2))).isFalse();
|
||||||
assertFalse(map.containsValue(null));
|
assertThat(map.containsValue(null)).isFalse();
|
||||||
|
|
||||||
@SuppressWarnings({"unlikely-arg-type", "CollectionIncompatibleType"})
|
@SuppressWarnings({"unlikely-arg-type", "CollectionIncompatibleType"})
|
||||||
boolean containsInt = map.containsValue(1); // should only contain JsonPrimitive(1)
|
boolean containsInt = map.containsValue(1); // should only contain JsonPrimitive(1)
|
||||||
assertFalse(containsInt);
|
assertThat(containsInt).isFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -70,9 +67,9 @@ public class JsonObjectAsMapTest {
|
||||||
o.addProperty("a", 1);
|
o.addProperty("a", 1);
|
||||||
|
|
||||||
Map<String, JsonElement> map = o.asMap();
|
Map<String, JsonElement> map = o.asMap();
|
||||||
assertEquals(new JsonPrimitive(1), map.get("a"));
|
assertThat(map.get("a")).isEqualTo(new JsonPrimitive(1));
|
||||||
assertNull(map.get("b"));
|
assertThat(map.get("b")).isNull();
|
||||||
assertNull(map.get(null));
|
assertThat(map.get(null)).isNull();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -80,31 +77,30 @@ public class JsonObjectAsMapTest {
|
||||||
JsonObject o = new JsonObject();
|
JsonObject o = new JsonObject();
|
||||||
Map<String, JsonElement> map = o.asMap();
|
Map<String, JsonElement> map = o.asMap();
|
||||||
|
|
||||||
assertNull(map.put("a", new JsonPrimitive(1)));
|
assertThat(map.put("a", new JsonPrimitive(1))).isNull();
|
||||||
assertEquals(1, map.size());
|
assertThat(map.get("a")).isEqualTo(new JsonPrimitive(1));
|
||||||
assertEquals(new JsonPrimitive(1), map.get("a"));
|
|
||||||
|
|
||||||
JsonElement old = map.put("a", new JsonPrimitive(2));
|
JsonElement old = map.put("a", new JsonPrimitive(2));
|
||||||
assertEquals(new JsonPrimitive(1), old);
|
assertThat(old).isEqualTo(new JsonPrimitive(1));
|
||||||
assertEquals(1, map.size());
|
assertThat(map).hasSize(1);
|
||||||
assertEquals(new JsonPrimitive(2), map.get("a"));
|
assertThat(map.get("a")).isEqualTo(new JsonPrimitive(2));
|
||||||
assertEquals(new JsonPrimitive(2), o.get("a"));
|
assertThat(o.get("a")).isEqualTo(new JsonPrimitive(2));
|
||||||
|
|
||||||
assertNull(map.put("b", JsonNull.INSTANCE));
|
assertThat(map.put("b", JsonNull.INSTANCE)).isNull();
|
||||||
assertEquals(JsonNull.INSTANCE, map.get("b"));
|
assertThat(map.get("b")).isEqualTo(JsonNull.INSTANCE);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
map.put(null, new JsonPrimitive(1));
|
map.put(null, new JsonPrimitive(1));
|
||||||
fail();
|
fail();
|
||||||
} catch (NullPointerException e) {
|
} catch (NullPointerException e) {
|
||||||
assertEquals("key == null", e.getMessage());
|
assertThat(e).hasMessageThat().isEqualTo("key == null");
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
map.put("a", null);
|
map.put("a", null);
|
||||||
fail();
|
fail();
|
||||||
} catch (NullPointerException e) {
|
} catch (NullPointerException e) {
|
||||||
assertEquals("value == null", e.getMessage());
|
assertThat(e).hasMessageThat().isEqualTo("value == null");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -114,18 +110,18 @@ public class JsonObjectAsMapTest {
|
||||||
o.addProperty("a", 1);
|
o.addProperty("a", 1);
|
||||||
|
|
||||||
Map<String, JsonElement> map = o.asMap();
|
Map<String, JsonElement> map = o.asMap();
|
||||||
assertNull(map.remove("b"));
|
assertThat(map.remove("b")).isNull();
|
||||||
assertEquals(1, map.size());
|
assertThat(map).hasSize(1);
|
||||||
|
|
||||||
JsonElement old = map.remove("a");
|
JsonElement old = map.remove("a");
|
||||||
assertEquals(new JsonPrimitive(1), old);
|
assertThat(old).isEqualTo(new JsonPrimitive(1));
|
||||||
assertEquals(0, map.size());
|
assertThat(map).hasSize(0);
|
||||||
|
|
||||||
assertNull(map.remove("a"));
|
assertThat(map.remove("a")).isNull();
|
||||||
assertEquals(0, map.size());
|
assertThat(map).hasSize(0);
|
||||||
assertEquals(0, o.size());
|
assertThat(o.size()).isEqualTo(0);
|
||||||
|
|
||||||
assertNull(map.remove(null));
|
assertThat(map.remove(null)).isNull();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -139,22 +135,22 @@ public class JsonObjectAsMapTest {
|
||||||
|
|
||||||
Map<String, JsonElement> map = o.asMap();
|
Map<String, JsonElement> map = o.asMap();
|
||||||
map.putAll(otherMap);
|
map.putAll(otherMap);
|
||||||
assertEquals(2, map.size());
|
assertThat(map).hasSize(2);
|
||||||
assertEquals(new JsonPrimitive(2), map.get("a"));
|
assertThat(map.get("a")).isEqualTo(new JsonPrimitive(2));
|
||||||
assertEquals(new JsonPrimitive(3), map.get("b"));
|
assertThat(map.get("b")).isEqualTo(new JsonPrimitive(3));
|
||||||
|
|
||||||
try {
|
try {
|
||||||
map.putAll(Collections.<String, JsonElement>singletonMap(null, new JsonPrimitive(1)));
|
map.putAll(Collections.<String, JsonElement>singletonMap(null, new JsonPrimitive(1)));
|
||||||
fail();
|
fail();
|
||||||
} catch (NullPointerException e) {
|
} catch (NullPointerException e) {
|
||||||
assertEquals("key == null", e.getMessage());
|
assertThat(e).hasMessageThat().isEqualTo("key == null");
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
map.putAll(Collections.<String, JsonElement>singletonMap("a", null));
|
map.putAll(Collections.<String, JsonElement>singletonMap("a", null));
|
||||||
fail();
|
fail();
|
||||||
} catch (NullPointerException e) {
|
} catch (NullPointerException e) {
|
||||||
assertEquals("value == null", e.getMessage());
|
assertThat(e).hasMessageThat().isEqualTo("value == null");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -165,8 +161,8 @@ public class JsonObjectAsMapTest {
|
||||||
|
|
||||||
Map<String, JsonElement> map = o.asMap();
|
Map<String, JsonElement> map = o.asMap();
|
||||||
map.clear();
|
map.clear();
|
||||||
assertEquals(0, map.size());
|
assertThat(map).hasSize(0);
|
||||||
assertEquals(0, o.size());
|
assertThat(o.size()).isEqualTo(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -178,7 +174,7 @@ public class JsonObjectAsMapTest {
|
||||||
Map<String, JsonElement> map = o.asMap();
|
Map<String, JsonElement> map = o.asMap();
|
||||||
Set<String> keySet = map.keySet();
|
Set<String> keySet = map.keySet();
|
||||||
// Should contain keys in same order
|
// Should contain keys in same order
|
||||||
assertEquals(Arrays.asList("b", "a"), new ArrayList<>(keySet));
|
assertThat(keySet).containsExactly("b", "a").inOrder();
|
||||||
|
|
||||||
// Key set doesn't support insertions
|
// Key set doesn't support insertions
|
||||||
try {
|
try {
|
||||||
|
@ -187,9 +183,9 @@ public class JsonObjectAsMapTest {
|
||||||
} catch (UnsupportedOperationException e) {
|
} catch (UnsupportedOperationException e) {
|
||||||
}
|
}
|
||||||
|
|
||||||
assertTrue(keySet.remove("a"));
|
assertThat(keySet.remove("a")).isTrue();
|
||||||
assertEquals(Collections.singleton("b"), map.keySet());
|
assertThat(map.keySet()).isEqualTo(Collections.singleton("b"));
|
||||||
assertEquals(Collections.singleton("b"), o.keySet());
|
assertThat(o.keySet()).isEqualTo(Collections.singleton("b"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -201,7 +197,7 @@ public class JsonObjectAsMapTest {
|
||||||
Map<String, JsonElement> map = o.asMap();
|
Map<String, JsonElement> map = o.asMap();
|
||||||
Collection<JsonElement> values = map.values();
|
Collection<JsonElement> values = map.values();
|
||||||
// Should contain values in same order
|
// Should contain values in same order
|
||||||
assertEquals(Arrays.asList(new JsonPrimitive(2), new JsonPrimitive(1)), new ArrayList<>(values));
|
assertThat(values).containsExactly(new JsonPrimitive(2), new JsonPrimitive(1)).inOrder();
|
||||||
|
|
||||||
// Values collection doesn't support insertions
|
// Values collection doesn't support insertions
|
||||||
try {
|
try {
|
||||||
|
@ -210,10 +206,10 @@ public class JsonObjectAsMapTest {
|
||||||
} catch (UnsupportedOperationException e) {
|
} catch (UnsupportedOperationException e) {
|
||||||
}
|
}
|
||||||
|
|
||||||
assertTrue(values.remove(new JsonPrimitive(2)));
|
assertThat(values.remove(new JsonPrimitive(2))).isTrue();
|
||||||
assertEquals(Collections.singletonList(new JsonPrimitive(1)), new ArrayList<>(map.values()));
|
assertThat(new ArrayList<>(map.values())).isEqualTo(Collections.singletonList(new JsonPrimitive(1)));
|
||||||
assertEquals(1, o.size());
|
assertThat(o.size()).isEqualTo(1);
|
||||||
assertEquals(new JsonPrimitive(1), o.get("b"));
|
assertThat(o.get("b")).isEqualTo(new JsonPrimitive(1));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -230,7 +226,7 @@ public class JsonObjectAsMapTest {
|
||||||
new SimpleEntry<>("a", new JsonPrimitive(1))
|
new SimpleEntry<>("a", new JsonPrimitive(1))
|
||||||
);
|
);
|
||||||
// Should contain entries in same order
|
// Should contain entries in same order
|
||||||
assertEquals(expectedEntrySet, new ArrayList<>(entrySet));
|
assertThat(new ArrayList<>(entrySet)).isEqualTo(expectedEntrySet);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
entrySet.add(new SimpleEntry<String, JsonElement>("c", new JsonPrimitive(3)));
|
entrySet.add(new SimpleEntry<String, JsonElement>("c", new JsonPrimitive(3)));
|
||||||
|
@ -238,24 +234,24 @@ public class JsonObjectAsMapTest {
|
||||||
} catch (UnsupportedOperationException e) {
|
} catch (UnsupportedOperationException e) {
|
||||||
}
|
}
|
||||||
|
|
||||||
assertTrue(entrySet.remove(new SimpleEntry<>("a", new JsonPrimitive(1))));
|
assertThat(entrySet.remove(new SimpleEntry<>("a", new JsonPrimitive(1)))).isTrue();
|
||||||
assertEquals(Collections.singleton(new SimpleEntry<>("b", new JsonPrimitive(2))), map.entrySet());
|
assertThat(map.entrySet()).isEqualTo(Collections.singleton(new SimpleEntry<>("b", new JsonPrimitive(2))));
|
||||||
assertEquals(Collections.singleton(new SimpleEntry<>("b", new JsonPrimitive(2))), o.entrySet());
|
assertThat(o.entrySet()).isEqualTo(Collections.singleton(new SimpleEntry<>("b", new JsonPrimitive(2))));
|
||||||
|
|
||||||
// Should return false because entry has already been removed
|
// Should return false because entry has already been removed
|
||||||
assertFalse(entrySet.remove(new SimpleEntry<>("a", new JsonPrimitive(1))));
|
assertThat(entrySet.remove(new SimpleEntry<>("a", new JsonPrimitive(1)))).isFalse();
|
||||||
|
|
||||||
Entry<String, JsonElement> entry = entrySet.iterator().next();
|
Entry<String, JsonElement> entry = entrySet.iterator().next();
|
||||||
JsonElement old = entry.setValue(new JsonPrimitive(3));
|
JsonElement old = entry.setValue(new JsonPrimitive(3));
|
||||||
assertEquals(new JsonPrimitive(2), old);
|
assertThat(old).isEqualTo(new JsonPrimitive(2));
|
||||||
assertEquals(Collections.singleton(new SimpleEntry<>("b", new JsonPrimitive(3))), map.entrySet());
|
assertThat(map.entrySet()).isEqualTo(Collections.singleton(new SimpleEntry<>("b", new JsonPrimitive(3))));
|
||||||
assertEquals(Collections.singleton(new SimpleEntry<>("b", new JsonPrimitive(3))), o.entrySet());
|
assertThat(o.entrySet()).isEqualTo(Collections.singleton(new SimpleEntry<>("b", new JsonPrimitive(3))));
|
||||||
|
|
||||||
try {
|
try {
|
||||||
entry.setValue(null);
|
entry.setValue(null);
|
||||||
fail();
|
fail();
|
||||||
} catch (NullPointerException e) {
|
} catch (NullPointerException e) {
|
||||||
assertEquals("value == null", e.getMessage());
|
assertThat(e).hasMessageThat().isEqualTo("value == null");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -266,8 +262,8 @@ public class JsonObjectAsMapTest {
|
||||||
|
|
||||||
Map<String, JsonElement> map = o.asMap();
|
Map<String, JsonElement> map = o.asMap();
|
||||||
MoreAsserts.assertEqualsAndHashCode(map, Collections.singletonMap("a", new JsonPrimitive(1)));
|
MoreAsserts.assertEqualsAndHashCode(map, Collections.singletonMap("a", new JsonPrimitive(1)));
|
||||||
assertFalse(map.equals(Collections.emptyMap()));
|
assertThat(map.equals(Collections.emptyMap())).isFalse();
|
||||||
assertFalse(map.equals(Collections.singletonMap("a", new JsonPrimitive(2))));
|
assertThat(map.equals(Collections.singletonMap("a", new JsonPrimitive(2)))).isFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Verify that {@code JsonObject} updates are visible to view and vice versa */
|
/** Verify that {@code JsonObject} updates are visible to view and vice versa */
|
||||||
|
@ -277,11 +273,11 @@ public class JsonObjectAsMapTest {
|
||||||
Map<String, JsonElement> map = o.asMap();
|
Map<String, JsonElement> map = o.asMap();
|
||||||
|
|
||||||
o.addProperty("a", 1);
|
o.addProperty("a", 1);
|
||||||
assertEquals(1, map.size());
|
assertThat(map).hasSize(1);
|
||||||
assertEquals(new JsonPrimitive(1), map.get("a"));
|
assertThat(map.get("a")).isEqualTo(new JsonPrimitive(1));
|
||||||
|
|
||||||
map.put("b", new JsonPrimitive(2));
|
map.put("b", new JsonPrimitive(2));
|
||||||
assertEquals(2, o.size());
|
assertThat(o.size()).isEqualTo(2);
|
||||||
assertEquals(new JsonPrimitive(2), o.get("b"));
|
assertThat(map.get("b")).isEqualTo(new JsonPrimitive(2));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -16,11 +16,7 @@
|
||||||
|
|
||||||
package com.google.gson;
|
package com.google.gson;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static com.google.common.truth.Truth.assertThat;
|
||||||
import static org.junit.Assert.assertFalse;
|
|
||||||
import static org.junit.Assert.assertNotNull;
|
|
||||||
import static org.junit.Assert.assertNull;
|
|
||||||
import static org.junit.Assert.assertTrue;
|
|
||||||
import static org.junit.Assert.fail;
|
import static org.junit.Assert.fail;
|
||||||
|
|
||||||
import com.google.gson.common.MoreAsserts;
|
import com.google.gson.common.MoreAsserts;
|
||||||
|
@ -44,39 +40,39 @@ import org.junit.Test;
|
||||||
public class JsonObjectTest {
|
public class JsonObjectTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testAddingAndRemovingObjectProperties() throws Exception {
|
public void testAddingAndRemovingObjectProperties() {
|
||||||
JsonObject jsonObj = new JsonObject();
|
JsonObject jsonObj = new JsonObject();
|
||||||
String propertyName = "property";
|
String propertyName = "property";
|
||||||
assertFalse(jsonObj.has(propertyName));
|
assertThat(jsonObj.has(propertyName)).isFalse();
|
||||||
assertNull(jsonObj.get(propertyName));
|
assertThat(jsonObj.get(propertyName)).isNull();
|
||||||
|
|
||||||
JsonPrimitive value = new JsonPrimitive("blah");
|
JsonPrimitive value = new JsonPrimitive("blah");
|
||||||
jsonObj.add(propertyName, value);
|
jsonObj.add(propertyName, value);
|
||||||
assertEquals(value, jsonObj.get(propertyName));
|
assertThat(jsonObj.get(propertyName)).isEqualTo(value);
|
||||||
|
|
||||||
JsonElement removedElement = jsonObj.remove(propertyName);
|
JsonElement removedElement = jsonObj.remove(propertyName);
|
||||||
assertEquals(value, removedElement);
|
assertThat(removedElement).isEqualTo(value);
|
||||||
assertFalse(jsonObj.has(propertyName));
|
assertThat(jsonObj.has(propertyName)).isFalse();
|
||||||
assertNull(jsonObj.get(propertyName));
|
assertThat(jsonObj.get(propertyName)).isNull();
|
||||||
|
|
||||||
assertNull(jsonObj.remove(propertyName));
|
assertThat(jsonObj.remove(propertyName)).isNull();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testAddingNullPropertyValue() throws Exception {
|
public void testAddingNullPropertyValue() {
|
||||||
String propertyName = "property";
|
String propertyName = "property";
|
||||||
JsonObject jsonObj = new JsonObject();
|
JsonObject jsonObj = new JsonObject();
|
||||||
jsonObj.add(propertyName, null);
|
jsonObj.add(propertyName, null);
|
||||||
|
|
||||||
assertTrue(jsonObj.has(propertyName));
|
assertThat(jsonObj.has(propertyName)).isTrue();
|
||||||
|
|
||||||
JsonElement jsonElement = jsonObj.get(propertyName);
|
JsonElement jsonElement = jsonObj.get(propertyName);
|
||||||
assertNotNull(jsonElement);
|
assertThat(jsonElement).isNotNull();
|
||||||
assertTrue(jsonElement.isJsonNull());
|
assertThat(jsonElement.isJsonNull()).isTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testAddingNullOrEmptyPropertyName() throws Exception {
|
public void testAddingNullOrEmptyPropertyName() {
|
||||||
JsonObject jsonObj = new JsonObject();
|
JsonObject jsonObj = new JsonObject();
|
||||||
try {
|
try {
|
||||||
jsonObj.add(null, JsonNull.INSTANCE);
|
jsonObj.add(null, JsonNull.INSTANCE);
|
||||||
|
@ -88,50 +84,50 @@ public class JsonObjectTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testAddingBooleanProperties() throws Exception {
|
public void testAddingBooleanProperties() {
|
||||||
String propertyName = "property";
|
String propertyName = "property";
|
||||||
JsonObject jsonObj = new JsonObject();
|
JsonObject jsonObj = new JsonObject();
|
||||||
jsonObj.addProperty(propertyName, true);
|
jsonObj.addProperty(propertyName, true);
|
||||||
|
|
||||||
assertTrue(jsonObj.has(propertyName));
|
assertThat(jsonObj.has(propertyName)).isTrue();
|
||||||
|
|
||||||
JsonElement jsonElement = jsonObj.get(propertyName);
|
JsonElement jsonElement = jsonObj.get(propertyName);
|
||||||
assertNotNull(jsonElement);
|
assertThat(jsonElement).isNotNull();
|
||||||
assertTrue(jsonElement.getAsBoolean());
|
assertThat(jsonElement.getAsBoolean()).isTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testAddingStringProperties() throws Exception {
|
public void testAddingStringProperties() {
|
||||||
String propertyName = "property";
|
String propertyName = "property";
|
||||||
String value = "blah";
|
String value = "blah";
|
||||||
|
|
||||||
JsonObject jsonObj = new JsonObject();
|
JsonObject jsonObj = new JsonObject();
|
||||||
jsonObj.addProperty(propertyName, value);
|
jsonObj.addProperty(propertyName, value);
|
||||||
|
|
||||||
assertTrue(jsonObj.has(propertyName));
|
assertThat(jsonObj.has(propertyName)).isTrue();
|
||||||
|
|
||||||
JsonElement jsonElement = jsonObj.get(propertyName);
|
JsonElement jsonElement = jsonObj.get(propertyName);
|
||||||
assertNotNull(jsonElement);
|
assertThat(jsonElement).isNotNull();
|
||||||
assertEquals(value, jsonElement.getAsString());
|
assertThat(jsonElement.getAsString()).isEqualTo(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testAddingCharacterProperties() throws Exception {
|
public void testAddingCharacterProperties() {
|
||||||
String propertyName = "property";
|
String propertyName = "property";
|
||||||
char value = 'a';
|
char value = 'a';
|
||||||
|
|
||||||
JsonObject jsonObj = new JsonObject();
|
JsonObject jsonObj = new JsonObject();
|
||||||
jsonObj.addProperty(propertyName, value);
|
jsonObj.addProperty(propertyName, value);
|
||||||
|
|
||||||
assertTrue(jsonObj.has(propertyName));
|
assertThat(jsonObj.has(propertyName)).isTrue();
|
||||||
|
|
||||||
JsonElement jsonElement = jsonObj.get(propertyName);
|
JsonElement jsonElement = jsonObj.get(propertyName);
|
||||||
assertNotNull(jsonElement);
|
assertThat(jsonElement).isNotNull();
|
||||||
assertEquals(String.valueOf(value), jsonElement.getAsString());
|
assertThat(jsonElement.getAsString()).isEqualTo(String.valueOf(value));
|
||||||
|
|
||||||
@SuppressWarnings("deprecation")
|
@SuppressWarnings("deprecation")
|
||||||
char character = jsonElement.getAsCharacter();
|
char character = jsonElement.getAsCharacter();
|
||||||
assertEquals(value, character);
|
assertThat(character).isEqualTo(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -142,7 +138,7 @@ public class JsonObjectTest {
|
||||||
JsonObject jsonObj = new JsonObject();
|
JsonObject jsonObj = new JsonObject();
|
||||||
jsonObj.add("a\"b", new JsonPrimitive("c\"d"));
|
jsonObj.add("a\"b", new JsonPrimitive("c\"d"));
|
||||||
String json = new Gson().toJson(jsonObj);
|
String json = new Gson().toJson(jsonObj);
|
||||||
assertEquals("{\"a\\\"b\":\"c\\\"d\"}", json);
|
assertThat(json).isEqualTo("{\"a\\\"b\":\"c\\\"d\"}");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -152,14 +148,13 @@ public class JsonObjectTest {
|
||||||
public void testWritePropertyWithEmptyStringName() {
|
public void testWritePropertyWithEmptyStringName() {
|
||||||
JsonObject jsonObj = new JsonObject();
|
JsonObject jsonObj = new JsonObject();
|
||||||
jsonObj.add("", new JsonPrimitive(true));
|
jsonObj.add("", new JsonPrimitive(true));
|
||||||
assertEquals("{\"\":true}", new Gson().toJson(jsonObj));
|
assertThat(new Gson().toJson(jsonObj)).isEqualTo("{\"\":true}");
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testReadPropertyWithEmptyStringName() {
|
public void testReadPropertyWithEmptyStringName() {
|
||||||
JsonObject jsonObj = JsonParser.parseString("{\"\":true}").getAsJsonObject();
|
JsonObject jsonObj = JsonParser.parseString("{\"\":true}").getAsJsonObject();
|
||||||
assertEquals(true, jsonObj.get("").getAsBoolean());
|
assertThat(jsonObj.get("").getAsBoolean()).isTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -172,22 +167,22 @@ public class JsonObjectTest {
|
||||||
JsonObject a = new JsonObject();
|
JsonObject a = new JsonObject();
|
||||||
JsonObject b = new JsonObject();
|
JsonObject b = new JsonObject();
|
||||||
|
|
||||||
assertEquals(a, a);
|
assertThat(a).isEqualTo(a);
|
||||||
|
|
||||||
a.add("foo", new JsonObject());
|
a.add("foo", new JsonObject());
|
||||||
assertFalse(a.equals(b));
|
assertThat(a.equals(b)).isFalse();
|
||||||
assertFalse(b.equals(a));
|
assertThat(b.equals(a)).isFalse();
|
||||||
|
|
||||||
b.add("foo", new JsonObject());
|
b.add("foo", new JsonObject());
|
||||||
MoreAsserts.assertEqualsAndHashCode(a, b);
|
MoreAsserts.assertEqualsAndHashCode(a, b);
|
||||||
|
|
||||||
a.add("bar", new JsonObject());
|
a.add("bar", new JsonObject());
|
||||||
assertFalse(a.equals(b));
|
assertThat(a.equals(b)).isFalse();
|
||||||
assertFalse(b.equals(a));
|
assertThat(b.equals(a)).isFalse();
|
||||||
|
|
||||||
b.add("bar", JsonNull.INSTANCE);
|
b.add("bar", JsonNull.INSTANCE);
|
||||||
assertFalse(a.equals(b));
|
assertThat(a.equals(b)).isFalse();
|
||||||
assertFalse(b.equals(a));
|
assertThat(b.equals(a)).isFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -201,8 +196,8 @@ public class JsonObjectTest {
|
||||||
a.addProperty("2", false);
|
a.addProperty("2", false);
|
||||||
b.addProperty("1", true);
|
b.addProperty("1", true);
|
||||||
|
|
||||||
assertEquals(Arrays.asList("1", "2"), new ArrayList<>(a.keySet()));
|
assertThat(new ArrayList<>(a.keySet())).containsExactly("1", "2").inOrder();
|
||||||
assertEquals(Arrays.asList("2", "1"), new ArrayList<>(b.keySet()));
|
assertThat(new ArrayList<>(b.keySet())).containsExactly("2", "1").inOrder();
|
||||||
|
|
||||||
MoreAsserts.assertEqualsAndHashCode(a, b);
|
MoreAsserts.assertEqualsAndHashCode(a, b);
|
||||||
}
|
}
|
||||||
|
@ -210,28 +205,28 @@ public class JsonObjectTest {
|
||||||
@Test
|
@Test
|
||||||
public void testSize() {
|
public void testSize() {
|
||||||
JsonObject o = new JsonObject();
|
JsonObject o = new JsonObject();
|
||||||
assertEquals(0, o.size());
|
assertThat(o.size()).isEqualTo(0);
|
||||||
|
|
||||||
o.add("Hello", new JsonPrimitive(1));
|
o.add("Hello", new JsonPrimitive(1));
|
||||||
assertEquals(1, o.size());
|
assertThat(o.size()).isEqualTo(1);
|
||||||
|
|
||||||
o.add("Hi", new JsonPrimitive(1));
|
o.add("Hi", new JsonPrimitive(1));
|
||||||
assertEquals(2, o.size());
|
assertThat(o.size()).isEqualTo(2);
|
||||||
|
|
||||||
o.remove("Hello");
|
o.remove("Hello");
|
||||||
assertEquals(1, o.size());
|
assertThat(o.size()).isEqualTo(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testIsEmpty() {
|
public void testIsEmpty() {
|
||||||
JsonObject o = new JsonObject();
|
JsonObject o = new JsonObject();
|
||||||
assertTrue(o.isEmpty());
|
assertThat(o.isEmpty()).isTrue();
|
||||||
|
|
||||||
o.add("Hello", new JsonPrimitive(1));
|
o.add("Hello", new JsonPrimitive(1));
|
||||||
assertFalse(o.isEmpty());
|
assertThat(o.isEmpty()).isFalse();
|
||||||
|
|
||||||
o.remove("Hello");
|
o.remove("Hello");
|
||||||
assertTrue(o.isEmpty());
|
assertThat(o.isEmpty()).isTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -243,8 +238,8 @@ public class JsonObjectTest {
|
||||||
JsonObject copy = original.deepCopy();
|
JsonObject copy = original.deepCopy();
|
||||||
firstEntry.add(new JsonPrimitive("z"));
|
firstEntry.add(new JsonPrimitive("z"));
|
||||||
|
|
||||||
assertEquals(1, original.get("key").getAsJsonArray().size());
|
assertThat(original.get("key").getAsJsonArray()).hasSize(1);
|
||||||
assertEquals(0, copy.get("key").getAsJsonArray().size());
|
assertThat(copy.get("key").getAsJsonArray()).hasSize(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -253,15 +248,15 @@ public class JsonObjectTest {
|
||||||
@Test
|
@Test
|
||||||
public void testKeySet() {
|
public void testKeySet() {
|
||||||
JsonObject a = new JsonObject();
|
JsonObject a = new JsonObject();
|
||||||
assertEquals(0, a.keySet().size());
|
assertThat(a.keySet()).hasSize(0);
|
||||||
|
|
||||||
a.add("foo", new JsonArray());
|
a.add("foo", new JsonArray());
|
||||||
a.add("bar", new JsonObject());
|
a.add("bar", new JsonObject());
|
||||||
|
|
||||||
assertEquals(2, a.size());
|
assertThat(a.size()).isEqualTo(2);
|
||||||
assertEquals(2, a.keySet().size());
|
assertThat(a.keySet()).hasSize(2);
|
||||||
assertTrue(a.keySet().contains("foo"));
|
assertThat(a.keySet().contains("foo")).isTrue();
|
||||||
assertTrue(a.keySet().contains("bar"));
|
assertThat(a.keySet().contains("bar")).isTrue();
|
||||||
|
|
||||||
a.addProperty("1", true);
|
a.addProperty("1", true);
|
||||||
a.addProperty("2", false);
|
a.addProperty("2", false);
|
||||||
|
@ -269,30 +264,30 @@ public class JsonObjectTest {
|
||||||
// Insertion order should be preserved by keySet()
|
// Insertion order should be preserved by keySet()
|
||||||
Deque<String> expectedKeys = new ArrayDeque<>(Arrays.asList("foo", "bar", "1", "2"));
|
Deque<String> expectedKeys = new ArrayDeque<>(Arrays.asList("foo", "bar", "1", "2"));
|
||||||
// Note: Must wrap in ArrayList because Deque implementations do not implement `equals`
|
// Note: Must wrap in ArrayList because Deque implementations do not implement `equals`
|
||||||
assertEquals(new ArrayList<>(expectedKeys), new ArrayList<>(a.keySet()));
|
assertThat(new ArrayList<>(a.keySet())).isEqualTo(new ArrayList<>(expectedKeys));
|
||||||
Iterator<String> iterator = a.keySet().iterator();
|
Iterator<String> iterator = a.keySet().iterator();
|
||||||
|
|
||||||
// Remove keys one by one
|
// Remove keys one by one
|
||||||
for (int i = a.size(); i >= 1; i--) {
|
for (int i = a.size(); i >= 1; i--) {
|
||||||
assertTrue(iterator.hasNext());
|
assertThat(iterator.hasNext()).isTrue();
|
||||||
assertEquals(expectedKeys.getFirst(), iterator.next());
|
assertThat(iterator.next()).isEqualTo(expectedKeys.getFirst());
|
||||||
iterator.remove();
|
iterator.remove();
|
||||||
expectedKeys.removeFirst();
|
expectedKeys.removeFirst();
|
||||||
|
|
||||||
assertEquals(i - 1, a.size());
|
assertThat(a.size()).isEqualTo(i - 1);
|
||||||
assertEquals(new ArrayList<>(expectedKeys), new ArrayList<>(a.keySet()));
|
assertThat(new ArrayList<>(a.keySet())).isEqualTo(new ArrayList<>(expectedKeys));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testEntrySet() {
|
public void testEntrySet() {
|
||||||
JsonObject o = new JsonObject();
|
JsonObject o = new JsonObject();
|
||||||
assertEquals(0, o.entrySet().size());
|
assertThat(o.entrySet()).hasSize(0);
|
||||||
|
|
||||||
o.addProperty("b", true);
|
o.addProperty("b", true);
|
||||||
Set<?> expectedEntries = Collections.singleton(new SimpleEntry<>("b", new JsonPrimitive(true)));
|
Set<?> expectedEntries = Collections.singleton(new SimpleEntry<>("b", new JsonPrimitive(true)));
|
||||||
assertEquals(expectedEntries, o.entrySet());
|
assertThat(o.entrySet()).isEqualTo(expectedEntries);
|
||||||
assertEquals(1, o.entrySet().size());
|
assertThat(o.entrySet()).hasSize(1);
|
||||||
|
|
||||||
o.addProperty("a", false);
|
o.addProperty("a", false);
|
||||||
// Insertion order should be preserved by entrySet()
|
// Insertion order should be preserved by entrySet()
|
||||||
|
@ -300,7 +295,7 @@ public class JsonObjectTest {
|
||||||
new SimpleEntry<>("b", new JsonPrimitive(true)),
|
new SimpleEntry<>("b", new JsonPrimitive(true)),
|
||||||
new SimpleEntry<>("a", new JsonPrimitive(false))
|
new SimpleEntry<>("a", new JsonPrimitive(false))
|
||||||
);
|
);
|
||||||
assertEquals(expectedEntriesList, new ArrayList<>(o.entrySet()));
|
assertThat(new ArrayList<>(o.entrySet())).isEqualTo(expectedEntriesList);
|
||||||
|
|
||||||
Iterator<Entry<String, JsonElement>> iterator = o.entrySet().iterator();
|
Iterator<Entry<String, JsonElement>> iterator = o.entrySet().iterator();
|
||||||
// Test behavior of Entry.setValue
|
// Test behavior of Entry.setValue
|
||||||
|
@ -308,14 +303,14 @@ public class JsonObjectTest {
|
||||||
Entry<String, JsonElement> entry = iterator.next();
|
Entry<String, JsonElement> entry = iterator.next();
|
||||||
entry.setValue(new JsonPrimitive(i));
|
entry.setValue(new JsonPrimitive(i));
|
||||||
|
|
||||||
assertEquals(new JsonPrimitive(i), entry.getValue());
|
assertThat(entry.getValue()).isEqualTo(new JsonPrimitive(i));
|
||||||
}
|
}
|
||||||
|
|
||||||
expectedEntriesList = Arrays.asList(
|
expectedEntriesList = Arrays.asList(
|
||||||
new SimpleEntry<>("b", new JsonPrimitive(0)),
|
new SimpleEntry<>("b", new JsonPrimitive(0)),
|
||||||
new SimpleEntry<>("a", new JsonPrimitive(1))
|
new SimpleEntry<>("a", new JsonPrimitive(1))
|
||||||
);
|
);
|
||||||
assertEquals(expectedEntriesList, new ArrayList<>(o.entrySet()));
|
assertThat(new ArrayList<>(o.entrySet())).isEqualTo(expectedEntriesList);
|
||||||
|
|
||||||
Entry<String, JsonElement> entry = o.entrySet().iterator().next();
|
Entry<String, JsonElement> entry = o.entrySet().iterator().next();
|
||||||
try {
|
try {
|
||||||
|
@ -325,9 +320,9 @@ public class JsonObjectTest {
|
||||||
entry.setValue(null);
|
entry.setValue(null);
|
||||||
fail();
|
fail();
|
||||||
} catch (NullPointerException e) {
|
} catch (NullPointerException e) {
|
||||||
assertEquals("value == null", e.getMessage());
|
assertThat(e).hasMessageThat().isEqualTo("value == null");
|
||||||
}
|
}
|
||||||
assertNotNull(entry.getValue());
|
assertThat(entry.getValue()).isNotNull();
|
||||||
|
|
||||||
o.addProperty("key1", 1);
|
o.addProperty("key1", 1);
|
||||||
o.addProperty("key2", 2);
|
o.addProperty("key2", 2);
|
||||||
|
@ -339,18 +334,18 @@ public class JsonObjectTest {
|
||||||
new SimpleEntry<>("key2", new JsonPrimitive(2))
|
new SimpleEntry<>("key2", new JsonPrimitive(2))
|
||||||
));
|
));
|
||||||
// Note: Must wrap in ArrayList because Deque implementations do not implement `equals`
|
// Note: Must wrap in ArrayList because Deque implementations do not implement `equals`
|
||||||
assertEquals(new ArrayList<>(expectedEntriesQueue), new ArrayList<>(o.entrySet()));
|
assertThat(new ArrayList<>(o.entrySet())).isEqualTo(new ArrayList<>(expectedEntriesQueue));
|
||||||
iterator = o.entrySet().iterator();
|
iterator = o.entrySet().iterator();
|
||||||
|
|
||||||
// Remove entries one by one
|
// Remove entries one by one
|
||||||
for (int i = o.size(); i >= 1; i--) {
|
for (int i = o.size(); i >= 1; i--) {
|
||||||
assertTrue(iterator.hasNext());
|
assertThat(iterator.hasNext()).isTrue();
|
||||||
assertEquals(expectedEntriesQueue.getFirst(), iterator.next());
|
assertThat(iterator.next()).isEqualTo(expectedEntriesQueue.getFirst());
|
||||||
iterator.remove();
|
iterator.remove();
|
||||||
expectedEntriesQueue.removeFirst();
|
expectedEntriesQueue.removeFirst();
|
||||||
|
|
||||||
assertEquals(i - 1, o.size());
|
assertThat(o.size()).isEqualTo(i - 1);
|
||||||
assertEquals(new ArrayList<>(expectedEntriesQueue), new ArrayList<>(o.entrySet()));
|
assertThat(new ArrayList<>(o.entrySet())).isEqualTo(new ArrayList<>(expectedEntriesQueue));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,8 +1,7 @@
|
||||||
package com.google.gson;
|
package com.google.gson;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static com.google.common.truth.Truth.assertThat;
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.junit.runner.RunWith;
|
import org.junit.runner.RunWith;
|
||||||
|
@ -31,11 +30,11 @@ public class JsonParserParameterizedTest {
|
||||||
public String json;
|
public String json;
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testParse() throws IOException {
|
public void testParse() {
|
||||||
JsonElement deserialized = JsonParser.parseString(json);
|
JsonElement deserialized = JsonParser.parseString(json);
|
||||||
String actualSerialized = adapter.toJson(deserialized);
|
String actualSerialized = adapter.toJson(deserialized);
|
||||||
|
|
||||||
// Serialized JsonElement should be the same as original JSON
|
// Serialized JsonElement should be the same as original JSON
|
||||||
assertEquals(json, actualSerialized);
|
assertThat(actualSerialized).isEqualTo(json);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -16,23 +16,26 @@
|
||||||
|
|
||||||
package com.google.gson;
|
package com.google.gson;
|
||||||
|
|
||||||
import java.io.CharArrayReader;
|
import static com.google.common.truth.Truth.assertThat;
|
||||||
import java.io.CharArrayWriter;
|
import static org.junit.Assert.fail;
|
||||||
import java.io.IOException;
|
|
||||||
import java.io.StringReader;
|
|
||||||
import junit.framework.TestCase;
|
|
||||||
|
|
||||||
import com.google.gson.common.TestTypes.BagOfPrimitives;
|
import com.google.gson.common.TestTypes.BagOfPrimitives;
|
||||||
import com.google.gson.internal.Streams;
|
import com.google.gson.internal.Streams;
|
||||||
import com.google.gson.stream.JsonReader;
|
import com.google.gson.stream.JsonReader;
|
||||||
|
import java.io.CharArrayReader;
|
||||||
|
import java.io.CharArrayWriter;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.StringReader;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Unit test for {@link JsonParser}
|
* Unit test for {@link JsonParser}
|
||||||
*
|
*
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
*/
|
*/
|
||||||
public class JsonParserTest extends TestCase {
|
public class JsonParserTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testParseInvalidJson() {
|
public void testParseInvalidJson() {
|
||||||
try {
|
try {
|
||||||
JsonParser.parseString("[[]");
|
JsonParser.parseString("[[]");
|
||||||
|
@ -40,37 +43,43 @@ public class JsonParserTest extends TestCase {
|
||||||
} catch (JsonSyntaxException expected) { }
|
} catch (JsonSyntaxException expected) { }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testParseUnquotedStringArrayFails() {
|
public void testParseUnquotedStringArrayFails() {
|
||||||
JsonElement element = JsonParser.parseString("[a,b,c]");
|
JsonElement element = JsonParser.parseString("[a,b,c]");
|
||||||
assertEquals("a", element.getAsJsonArray().get(0).getAsString());
|
assertThat(element.getAsJsonArray().get(0).getAsString()).isEqualTo("a");
|
||||||
assertEquals("b", element.getAsJsonArray().get(1).getAsString());
|
assertThat(element.getAsJsonArray().get(1).getAsString()).isEqualTo("b");
|
||||||
assertEquals("c", element.getAsJsonArray().get(2).getAsString());
|
assertThat(element.getAsJsonArray().get(2).getAsString()).isEqualTo("c");
|
||||||
assertEquals(3, element.getAsJsonArray().size());
|
assertThat(element.getAsJsonArray()).hasSize(3);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testParseString() {
|
public void testParseString() {
|
||||||
String json = "{a:10,b:'c'}";
|
String json = "{a:10,b:'c'}";
|
||||||
JsonElement e = JsonParser.parseString(json);
|
JsonElement e = JsonParser.parseString(json);
|
||||||
assertTrue(e.isJsonObject());
|
assertThat(e.isJsonObject()).isTrue();
|
||||||
assertEquals(10, e.getAsJsonObject().get("a").getAsInt());
|
assertThat(e.getAsJsonObject().get("a").getAsInt()).isEqualTo(10);
|
||||||
assertEquals("c", e.getAsJsonObject().get("b").getAsString());
|
assertThat(e.getAsJsonObject().get("b").getAsString()).isEqualTo("c");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testParseEmptyString() {
|
public void testParseEmptyString() {
|
||||||
JsonElement e = JsonParser.parseString("\" \"");
|
JsonElement e = JsonParser.parseString("\" \"");
|
||||||
assertTrue(e.isJsonPrimitive());
|
assertThat(e.isJsonPrimitive()).isTrue();
|
||||||
assertEquals(" ", e.getAsString());
|
assertThat(e.getAsString()).isEqualTo(" ");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testParseEmptyWhitespaceInput() {
|
public void testParseEmptyWhitespaceInput() {
|
||||||
JsonElement e = JsonParser.parseString(" ");
|
JsonElement e = JsonParser.parseString(" ");
|
||||||
assertTrue(e.isJsonNull());
|
assertThat(e.isJsonNull()).isTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testParseUnquotedSingleWordStringFails() {
|
public void testParseUnquotedSingleWordStringFails() {
|
||||||
assertEquals("Test", JsonParser.parseString("Test").getAsString());
|
assertThat(JsonParser.parseString("Test").getAsString()).isEqualTo("Test");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testParseUnquotedMultiWordStringFails() {
|
public void testParseUnquotedMultiWordStringFails() {
|
||||||
String unquotedSentence = "Test is a test..blah blah";
|
String unquotedSentence = "Test is a test..blah blah";
|
||||||
try {
|
try {
|
||||||
|
@ -79,15 +88,16 @@ public class JsonParserTest extends TestCase {
|
||||||
} catch (JsonSyntaxException expected) { }
|
} catch (JsonSyntaxException expected) { }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testParseMixedArray() {
|
public void testParseMixedArray() {
|
||||||
String json = "[{},13,\"stringValue\"]";
|
String json = "[{},13,\"stringValue\"]";
|
||||||
JsonElement e = JsonParser.parseString(json);
|
JsonElement e = JsonParser.parseString(json);
|
||||||
assertTrue(e.isJsonArray());
|
assertThat(e.isJsonArray()).isTrue();
|
||||||
|
|
||||||
JsonArray array = e.getAsJsonArray();
|
JsonArray array = e.getAsJsonArray();
|
||||||
assertEquals("{}", array.get(0).toString());
|
assertThat(array.get(0).toString()).isEqualTo("{}");
|
||||||
assertEquals(13, array.get(1).getAsInt());
|
assertThat(array.get(1).getAsInt()).isEqualTo(13);
|
||||||
assertEquals("stringValue", array.get(2).getAsString());
|
assertThat(array.get(2).getAsString()).isEqualTo("stringValue");
|
||||||
}
|
}
|
||||||
|
|
||||||
private static String repeat(String s, int times) {
|
private static String repeat(String s, int times) {
|
||||||
|
@ -99,6 +109,7 @@ public class JsonParserTest extends TestCase {
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Deeply nested JSON arrays should not cause {@link StackOverflowError} */
|
/** Deeply nested JSON arrays should not cause {@link StackOverflowError} */
|
||||||
|
@Test
|
||||||
public void testParseDeeplyNestedArrays() throws IOException {
|
public void testParseDeeplyNestedArrays() throws IOException {
|
||||||
int times = 10000;
|
int times = 10000;
|
||||||
// [[[ ... ]]]
|
// [[[ ... ]]]
|
||||||
|
@ -111,13 +122,14 @@ public class JsonParserTest extends TestCase {
|
||||||
if (current.isEmpty()) {
|
if (current.isEmpty()) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
assertEquals(1, current.size());
|
assertThat(current.size()).isEqualTo(1);
|
||||||
current = current.get(0).getAsJsonArray();
|
current = current.get(0).getAsJsonArray();
|
||||||
}
|
}
|
||||||
assertEquals(times, actualTimes);
|
assertThat(actualTimes).isEqualTo(times);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Deeply nested JSON objects should not cause {@link StackOverflowError} */
|
/** Deeply nested JSON objects should not cause {@link StackOverflowError} */
|
||||||
|
@Test
|
||||||
public void testParseDeeplyNestedObjects() throws IOException {
|
public void testParseDeeplyNestedObjects() throws IOException {
|
||||||
int times = 10000;
|
int times = 10000;
|
||||||
// {"a":{"a": ... {"a":null} ... }}
|
// {"a":{"a": ... {"a":null} ... }}
|
||||||
|
@ -126,7 +138,7 @@ public class JsonParserTest extends TestCase {
|
||||||
int actualTimes = 0;
|
int actualTimes = 0;
|
||||||
JsonObject current = JsonParser.parseString(json).getAsJsonObject();
|
JsonObject current = JsonParser.parseString(json).getAsJsonObject();
|
||||||
while (true) {
|
while (true) {
|
||||||
assertEquals(1, current.size());
|
assertThat(current.size()).isEqualTo(1);
|
||||||
actualTimes++;
|
actualTimes++;
|
||||||
JsonElement next = current.get("a");
|
JsonElement next = current.get("a");
|
||||||
if (next.isJsonNull()) {
|
if (next.isJsonNull()) {
|
||||||
|
@ -135,17 +147,19 @@ public class JsonParserTest extends TestCase {
|
||||||
current = next.getAsJsonObject();
|
current = next.getAsJsonObject();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
assertEquals(times, actualTimes);
|
assertThat(actualTimes).isEqualTo(times);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testParseReader() {
|
public void testParseReader() {
|
||||||
StringReader reader = new StringReader("{a:10,b:'c'}");
|
StringReader reader = new StringReader("{a:10,b:'c'}");
|
||||||
JsonElement e = JsonParser.parseReader(reader);
|
JsonElement e = JsonParser.parseReader(reader);
|
||||||
assertTrue(e.isJsonObject());
|
assertThat(e.isJsonObject()).isTrue();
|
||||||
assertEquals(10, e.getAsJsonObject().get("a").getAsInt());
|
assertThat(e.getAsJsonObject().get("a").getAsInt()).isEqualTo(10);
|
||||||
assertEquals("c", e.getAsJsonObject().get("b").getAsString());
|
assertThat(e.getAsJsonObject().get("b").getAsString()).isEqualTo("c");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testReadWriteTwoObjects() throws Exception {
|
public void testReadWriteTwoObjects() throws Exception {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
CharArrayWriter writer = new CharArrayWriter();
|
CharArrayWriter writer = new CharArrayWriter();
|
||||||
|
@ -160,8 +174,8 @@ public class JsonParserTest extends TestCase {
|
||||||
JsonElement element1 = Streams.parse(parser);
|
JsonElement element1 = Streams.parse(parser);
|
||||||
JsonElement element2 = Streams.parse(parser);
|
JsonElement element2 = Streams.parse(parser);
|
||||||
BagOfPrimitives actualOne = gson.fromJson(element1, BagOfPrimitives.class);
|
BagOfPrimitives actualOne = gson.fromJson(element1, BagOfPrimitives.class);
|
||||||
assertEquals("one", actualOne.stringValue);
|
assertThat(actualOne.stringValue).isEqualTo("one");
|
||||||
BagOfPrimitives actualTwo = gson.fromJson(element2, BagOfPrimitives.class);
|
BagOfPrimitives actualTwo = gson.fromJson(element2, BagOfPrimitives.class);
|
||||||
assertEquals("two", actualTwo.stringValue);
|
assertThat(actualTwo.stringValue).isEqualTo("two");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -16,19 +16,24 @@
|
||||||
|
|
||||||
package com.google.gson;
|
package com.google.gson;
|
||||||
|
|
||||||
|
import static com.google.common.truth.Truth.assertThat;
|
||||||
|
import static com.google.common.truth.Truth.assertWithMessage;
|
||||||
|
import static org.junit.Assert.fail;
|
||||||
|
|
||||||
import com.google.gson.common.MoreAsserts;
|
import com.google.gson.common.MoreAsserts;
|
||||||
import java.math.BigDecimal;
|
import java.math.BigDecimal;
|
||||||
import java.math.BigInteger;
|
import java.math.BigInteger;
|
||||||
import junit.framework.TestCase;
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Unit test for the {@link JsonPrimitive} class.
|
* Unit test for the {@link JsonPrimitive} class.
|
||||||
*
|
*
|
||||||
* @author Joel Leitch
|
* @author Joel Leitch
|
||||||
*/
|
*/
|
||||||
public class JsonPrimitiveTest extends TestCase {
|
public class JsonPrimitiveTest {
|
||||||
|
|
||||||
@SuppressWarnings("unused")
|
@SuppressWarnings("unused")
|
||||||
|
@Test
|
||||||
public void testNulls() {
|
public void testNulls() {
|
||||||
try {
|
try {
|
||||||
new JsonPrimitive((Boolean) null);
|
new JsonPrimitive((Boolean) null);
|
||||||
|
@ -52,91 +57,96 @@ public class JsonPrimitiveTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void testBoolean() throws Exception {
|
@Test
|
||||||
|
public void testBoolean() {
|
||||||
JsonPrimitive json = new JsonPrimitive(Boolean.TRUE);
|
JsonPrimitive json = new JsonPrimitive(Boolean.TRUE);
|
||||||
|
|
||||||
assertTrue(json.isBoolean());
|
assertThat(json.isBoolean()).isTrue();
|
||||||
assertTrue(json.getAsBoolean());
|
assertThat(json.getAsBoolean()).isTrue();
|
||||||
|
|
||||||
// Extra support for booleans
|
// Extra support for booleans
|
||||||
json = new JsonPrimitive(1);
|
json = new JsonPrimitive(1);
|
||||||
assertFalse(json.getAsBoolean());
|
assertThat(json.getAsBoolean()).isFalse();
|
||||||
|
|
||||||
json = new JsonPrimitive("1");
|
json = new JsonPrimitive("1");
|
||||||
assertFalse(json.getAsBoolean());
|
assertThat(json.getAsBoolean()).isFalse();
|
||||||
|
|
||||||
json = new JsonPrimitive("true");
|
json = new JsonPrimitive("true");
|
||||||
assertTrue(json.getAsBoolean());
|
assertThat(json.getAsBoolean()).isTrue();
|
||||||
|
|
||||||
json = new JsonPrimitive("TrUe");
|
json = new JsonPrimitive("TrUe");
|
||||||
assertTrue(json.getAsBoolean());
|
assertThat(json.getAsBoolean()).isTrue();
|
||||||
|
|
||||||
json = new JsonPrimitive("1.3");
|
json = new JsonPrimitive("1.3");
|
||||||
assertFalse(json.getAsBoolean());
|
assertThat(json.getAsBoolean()).isFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void testParsingStringAsBoolean() throws Exception {
|
@Test
|
||||||
|
public void testParsingStringAsBoolean() {
|
||||||
JsonPrimitive json = new JsonPrimitive("true");
|
JsonPrimitive json = new JsonPrimitive("true");
|
||||||
|
|
||||||
assertFalse(json.isBoolean());
|
assertThat(json.isBoolean()).isFalse();
|
||||||
assertTrue(json.getAsBoolean());
|
assertThat(json.getAsBoolean()).isTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void testParsingStringAsNumber() throws Exception {
|
@Test
|
||||||
|
public void testParsingStringAsNumber() {
|
||||||
JsonPrimitive json = new JsonPrimitive("1");
|
JsonPrimitive json = new JsonPrimitive("1");
|
||||||
|
|
||||||
assertFalse(json.isNumber());
|
assertThat(json.isNumber()).isFalse();
|
||||||
assertEquals(1D, json.getAsDouble(), 0.00001);
|
assertThat(json.getAsDouble()).isEqualTo(1.0);
|
||||||
assertEquals(1F, json.getAsFloat(), 0.00001);
|
assertThat(json.getAsFloat()).isEqualTo(1F);
|
||||||
assertEquals(1, json.getAsInt());
|
assertThat(json.getAsInt()).isEqualTo(1);
|
||||||
assertEquals(1L, json.getAsLong());
|
assertThat(json.getAsLong()).isEqualTo(1L);
|
||||||
assertEquals((short) 1, json.getAsShort());
|
assertThat(json.getAsShort()).isEqualTo((short) 1);
|
||||||
assertEquals((byte) 1, json.getAsByte());
|
assertThat(json.getAsByte()).isEqualTo((byte) 1);
|
||||||
assertEquals(new BigInteger("1"), json.getAsBigInteger());
|
assertThat(json.getAsBigInteger()).isEqualTo(new BigInteger("1"));
|
||||||
assertEquals(new BigDecimal("1"), json.getAsBigDecimal());
|
assertThat(json.getAsBigDecimal()).isEqualTo(new BigDecimal("1"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testAsNumber_Boolean() {
|
public void testAsNumber_Boolean() {
|
||||||
JsonPrimitive json = new JsonPrimitive(true);
|
JsonPrimitive json = new JsonPrimitive(true);
|
||||||
try {
|
try {
|
||||||
json.getAsNumber();
|
json.getAsNumber();
|
||||||
fail();
|
fail();
|
||||||
} catch (UnsupportedOperationException e) {
|
} catch (UnsupportedOperationException e) {
|
||||||
assertEquals("Primitive is neither a number nor a string", e.getMessage());
|
assertThat(e).hasMessageThat().isEqualTo("Primitive is neither a number nor a string");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings("deprecation")
|
@SuppressWarnings("deprecation")
|
||||||
public void testStringsAndChar() throws Exception {
|
@Test
|
||||||
|
public void testStringsAndChar() {
|
||||||
JsonPrimitive json = new JsonPrimitive("abc");
|
JsonPrimitive json = new JsonPrimitive("abc");
|
||||||
assertTrue(json.isString());
|
assertThat(json.isString()).isTrue();
|
||||||
assertEquals('a', json.getAsCharacter());
|
assertThat(json.getAsCharacter()).isEqualTo('a');
|
||||||
assertEquals("abc", json.getAsString());
|
assertThat(json.getAsString()).isEqualTo("abc");
|
||||||
|
|
||||||
json = new JsonPrimitive('z');
|
json = new JsonPrimitive('z');
|
||||||
assertTrue(json.isString());
|
assertThat(json.isString()).isTrue();
|
||||||
assertEquals('z', json.getAsCharacter());
|
assertThat(json.getAsCharacter()).isEqualTo('z');
|
||||||
assertEquals("z", json.getAsString());
|
assertThat(json.getAsString()).isEqualTo("z");
|
||||||
|
|
||||||
json = new JsonPrimitive(true);
|
json = new JsonPrimitive(true);
|
||||||
assertEquals("true", json.getAsString());
|
assertThat(json.getAsString()).isEqualTo("true");
|
||||||
|
|
||||||
json = new JsonPrimitive("");
|
json = new JsonPrimitive("");
|
||||||
assertEquals("", json.getAsString());
|
assertThat(json.getAsString()).isEqualTo("");
|
||||||
try {
|
try {
|
||||||
json.getAsCharacter();
|
json.getAsCharacter();
|
||||||
fail();
|
fail();
|
||||||
} catch (UnsupportedOperationException e) {
|
} catch (UnsupportedOperationException e) {
|
||||||
assertEquals("String value is empty", e.getMessage());
|
assertThat(e).hasMessageThat().isEqualTo("String value is empty");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void testExponential() throws Exception {
|
@Test
|
||||||
|
public void testExponential() {
|
||||||
JsonPrimitive json = new JsonPrimitive("1E+7");
|
JsonPrimitive json = new JsonPrimitive("1E+7");
|
||||||
|
|
||||||
assertEquals(new BigDecimal("1E+7"), json.getAsBigDecimal());
|
assertThat(json.getAsBigDecimal()).isEqualTo(new BigDecimal("1E+7"));
|
||||||
assertEquals(1E+7, json.getAsDouble(), 0.00001);
|
assertThat(json.getAsDouble()).isEqualTo(1E+7);
|
||||||
assertEquals(1E+7, json.getAsDouble(), 0.00001);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
json.getAsInt();
|
json.getAsInt();
|
||||||
|
@ -144,105 +154,120 @@ public class JsonPrimitiveTest extends TestCase {
|
||||||
} catch (NumberFormatException expected) { }
|
} catch (NumberFormatException expected) { }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testByteEqualsShort() {
|
public void testByteEqualsShort() {
|
||||||
JsonPrimitive p1 = new JsonPrimitive(Byte.valueOf((byte)10));
|
JsonPrimitive p1 = new JsonPrimitive((byte) 10);
|
||||||
JsonPrimitive p2 = new JsonPrimitive(Short.valueOf((short)10));
|
JsonPrimitive p2 = new JsonPrimitive((short) 10);
|
||||||
assertEquals(p1, p2);
|
assertThat(p1).isEqualTo(p2);
|
||||||
assertEquals(p1.hashCode(), p2.hashCode());
|
assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testByteEqualsInteger() {
|
public void testByteEqualsInteger() {
|
||||||
JsonPrimitive p1 = new JsonPrimitive(Byte.valueOf((byte)10));
|
JsonPrimitive p1 = new JsonPrimitive((byte) 10);
|
||||||
JsonPrimitive p2 = new JsonPrimitive(Integer.valueOf(10));
|
JsonPrimitive p2 = new JsonPrimitive(10);
|
||||||
assertEquals(p1, p2);
|
assertThat(p1).isEqualTo(p2);
|
||||||
assertEquals(p1.hashCode(), p2.hashCode());
|
assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testByteEqualsLong() {
|
public void testByteEqualsLong() {
|
||||||
JsonPrimitive p1 = new JsonPrimitive(Byte.valueOf((byte)10));
|
JsonPrimitive p1 = new JsonPrimitive((byte) 10);
|
||||||
JsonPrimitive p2 = new JsonPrimitive(Long.valueOf(10L));
|
JsonPrimitive p2 = new JsonPrimitive(10L);
|
||||||
assertEquals(p1, p2);
|
assertThat(p1).isEqualTo(p2);
|
||||||
assertEquals(p1.hashCode(), p2.hashCode());
|
assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testByteEqualsBigInteger() {
|
public void testByteEqualsBigInteger() {
|
||||||
JsonPrimitive p1 = new JsonPrimitive(Byte.valueOf((byte)10));
|
JsonPrimitive p1 = new JsonPrimitive((byte) 10);
|
||||||
JsonPrimitive p2 = new JsonPrimitive(new BigInteger("10"));
|
JsonPrimitive p2 = new JsonPrimitive(new BigInteger("10"));
|
||||||
assertEquals(p1, p2);
|
assertThat(p1).isEqualTo(p2);
|
||||||
assertEquals(p1.hashCode(), p2.hashCode());
|
assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testShortEqualsInteger() {
|
public void testShortEqualsInteger() {
|
||||||
JsonPrimitive p1 = new JsonPrimitive(Short.valueOf((short)10));
|
JsonPrimitive p1 = new JsonPrimitive((short) 10);
|
||||||
JsonPrimitive p2 = new JsonPrimitive(Integer.valueOf(10));
|
JsonPrimitive p2 = new JsonPrimitive(10);
|
||||||
assertEquals(p1, p2);
|
assertThat(p1).isEqualTo(p2);
|
||||||
assertEquals(p1.hashCode(), p2.hashCode());
|
assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testShortEqualsLong() {
|
public void testShortEqualsLong() {
|
||||||
JsonPrimitive p1 = new JsonPrimitive(Short.valueOf((short)10));
|
JsonPrimitive p1 = new JsonPrimitive((short) 10);
|
||||||
JsonPrimitive p2 = new JsonPrimitive(Long.valueOf(10));
|
JsonPrimitive p2 = new JsonPrimitive(10L);
|
||||||
assertEquals(p1, p2);
|
assertThat(p1).isEqualTo(p2);
|
||||||
assertEquals(p1.hashCode(), p2.hashCode());
|
assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testShortEqualsBigInteger() {
|
public void testShortEqualsBigInteger() {
|
||||||
JsonPrimitive p1 = new JsonPrimitive(Short.valueOf((short)10));
|
JsonPrimitive p1 = new JsonPrimitive((short) 10);
|
||||||
JsonPrimitive p2 = new JsonPrimitive(new BigInteger("10"));
|
JsonPrimitive p2 = new JsonPrimitive(new BigInteger("10"));
|
||||||
assertEquals(p1, p2);
|
assertThat(p1).isEqualTo(p2);
|
||||||
assertEquals(p1.hashCode(), p2.hashCode());
|
assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testIntegerEqualsLong() {
|
public void testIntegerEqualsLong() {
|
||||||
JsonPrimitive p1 = new JsonPrimitive(Integer.valueOf(10));
|
JsonPrimitive p1 = new JsonPrimitive(10);
|
||||||
JsonPrimitive p2 = new JsonPrimitive(Long.valueOf(10L));
|
JsonPrimitive p2 = new JsonPrimitive(10L);
|
||||||
assertEquals(p1, p2);
|
assertThat(p1).isEqualTo(p2);
|
||||||
assertEquals(p1.hashCode(), p2.hashCode());
|
assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testIntegerEqualsBigInteger() {
|
public void testIntegerEqualsBigInteger() {
|
||||||
JsonPrimitive p1 = new JsonPrimitive(Integer.valueOf(10));
|
JsonPrimitive p1 = new JsonPrimitive(10);
|
||||||
JsonPrimitive p2 = new JsonPrimitive(new BigInteger("10"));
|
JsonPrimitive p2 = new JsonPrimitive(new BigInteger("10"));
|
||||||
assertEquals(p1, p2);
|
assertThat(p1).isEqualTo(p2);
|
||||||
assertEquals(p1.hashCode(), p2.hashCode());
|
assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testLongEqualsBigInteger() {
|
public void testLongEqualsBigInteger() {
|
||||||
JsonPrimitive p1 = new JsonPrimitive(Long.valueOf(10L));
|
JsonPrimitive p1 = new JsonPrimitive(10L);
|
||||||
JsonPrimitive p2 = new JsonPrimitive(new BigInteger("10"));
|
JsonPrimitive p2 = new JsonPrimitive(new BigInteger("10"));
|
||||||
assertEquals(p1, p2);
|
assertThat(p1).isEqualTo(p2);
|
||||||
assertEquals(p1.hashCode(), p2.hashCode());
|
assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testFloatEqualsDouble() {
|
public void testFloatEqualsDouble() {
|
||||||
JsonPrimitive p1 = new JsonPrimitive(Float.valueOf(10.25F));
|
JsonPrimitive p1 = new JsonPrimitive(10.25F);
|
||||||
JsonPrimitive p2 = new JsonPrimitive(Double.valueOf(10.25D));
|
JsonPrimitive p2 = new JsonPrimitive(10.25D);
|
||||||
assertEquals(p1, p2);
|
assertThat(p1).isEqualTo(p2);
|
||||||
assertEquals(p1.hashCode(), p2.hashCode());
|
assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testFloatEqualsBigDecimal() {
|
public void testFloatEqualsBigDecimal() {
|
||||||
JsonPrimitive p1 = new JsonPrimitive(Float.valueOf(10.25F));
|
JsonPrimitive p1 = new JsonPrimitive(10.25F);
|
||||||
JsonPrimitive p2 = new JsonPrimitive(new BigDecimal("10.25"));
|
JsonPrimitive p2 = new JsonPrimitive(new BigDecimal("10.25"));
|
||||||
assertEquals(p1, p2);
|
assertThat(p1).isEqualTo(p2);
|
||||||
assertEquals(p1.hashCode(), p2.hashCode());
|
assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDoubleEqualsBigDecimal() {
|
public void testDoubleEqualsBigDecimal() {
|
||||||
JsonPrimitive p1 = new JsonPrimitive(Double.valueOf(10.25D));
|
JsonPrimitive p1 = new JsonPrimitive(10.25D);
|
||||||
JsonPrimitive p2 = new JsonPrimitive(new BigDecimal("10.25"));
|
JsonPrimitive p2 = new JsonPrimitive(new BigDecimal("10.25"));
|
||||||
assertEquals(p1, p2);
|
assertThat(p1).isEqualTo(p2);
|
||||||
assertEquals(p1.hashCode(), p2.hashCode());
|
assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
|
||||||
}
|
}
|
||||||
|
|
||||||
public void testValidJsonOnToString() throws Exception {
|
@Test
|
||||||
|
public void testValidJsonOnToString() {
|
||||||
JsonPrimitive json = new JsonPrimitive("Some\nEscaped\nValue");
|
JsonPrimitive json = new JsonPrimitive("Some\nEscaped\nValue");
|
||||||
assertEquals("\"Some\\nEscaped\\nValue\"", json.toString());
|
assertThat(json.toString()).isEqualTo("\"Some\\nEscaped\\nValue\"");
|
||||||
|
|
||||||
json = new JsonPrimitive(new BigDecimal("1.333"));
|
json = new JsonPrimitive(new BigDecimal("1.333"));
|
||||||
assertEquals("1.333", json.toString());
|
assertThat(json.toString()).isEqualTo("1.333");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testEquals() {
|
public void testEquals() {
|
||||||
MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive("A"), new JsonPrimitive("A"));
|
MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive("A"), new JsonPrimitive("A"));
|
||||||
MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(true), new JsonPrimitive(true));
|
MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(true), new JsonPrimitive(true));
|
||||||
|
@ -258,11 +283,12 @@ public class JsonPrimitiveTest extends TestCase {
|
||||||
new JsonPrimitive(Double.NEGATIVE_INFINITY));
|
new JsonPrimitive(Double.NEGATIVE_INFINITY));
|
||||||
MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(Double.POSITIVE_INFINITY),
|
MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(Double.POSITIVE_INFINITY),
|
||||||
new JsonPrimitive(Double.POSITIVE_INFINITY));
|
new JsonPrimitive(Double.POSITIVE_INFINITY));
|
||||||
assertFalse(new JsonPrimitive("a").equals(new JsonPrimitive("b")));
|
assertThat(new JsonPrimitive("a").equals(new JsonPrimitive("b"))).isFalse();
|
||||||
assertFalse(new JsonPrimitive(true).equals(new JsonPrimitive(false)));
|
assertThat(new JsonPrimitive(true).equals(new JsonPrimitive(false))).isFalse();
|
||||||
assertFalse(new JsonPrimitive(0).equals(new JsonPrimitive(1)));
|
assertThat(new JsonPrimitive(0).equals(new JsonPrimitive(1))).isFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testEqualsAcrossTypes() {
|
public void testEqualsAcrossTypes() {
|
||||||
MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive("a"), new JsonPrimitive('a'));
|
MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive("a"), new JsonPrimitive('a'));
|
||||||
MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(new BigInteger("0")), new JsonPrimitive(0));
|
MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(new BigInteger("0")), new JsonPrimitive(0));
|
||||||
|
@ -271,22 +297,25 @@ public class JsonPrimitiveTest extends TestCase {
|
||||||
MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(Float.NaN), new JsonPrimitive(Double.NaN));
|
MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(Float.NaN), new JsonPrimitive(Double.NaN));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testEqualsIntegerAndBigInteger() {
|
public void testEqualsIntegerAndBigInteger() {
|
||||||
JsonPrimitive a = new JsonPrimitive(5L);
|
JsonPrimitive a = new JsonPrimitive(5L);
|
||||||
JsonPrimitive b = new JsonPrimitive(new BigInteger("18446744073709551621")); // 2^64 + 5
|
JsonPrimitive b = new JsonPrimitive(new BigInteger("18446744073709551621")); // 2^64 + 5
|
||||||
// Ideally, the following assertion should have failed but the price is too much to pay
|
// Ideally, the following assertion should have failed but the price is too much to pay
|
||||||
// assertFalse(a + " equals " + b, a.equals(b));
|
// assertFalse(a + " equals " + b, a.equals(b));
|
||||||
assertTrue(a + " equals " + b, a.equals(b));
|
assertWithMessage("%s equals %s", a, b).that(a.equals(b)).isTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testEqualsDoesNotEquateStringAndNonStringTypes() {
|
public void testEqualsDoesNotEquateStringAndNonStringTypes() {
|
||||||
assertFalse(new JsonPrimitive("true").equals(new JsonPrimitive(true)));
|
assertThat(new JsonPrimitive("true").equals(new JsonPrimitive(true))).isFalse();
|
||||||
assertFalse(new JsonPrimitive("0").equals(new JsonPrimitive(0)));
|
assertThat(new JsonPrimitive("0").equals(new JsonPrimitive(0))).isFalse();
|
||||||
assertFalse(new JsonPrimitive("NaN").equals(new JsonPrimitive(Float.NaN)));
|
assertThat(new JsonPrimitive("NaN").equals(new JsonPrimitive(Float.NaN))).isFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeepCopy() {
|
public void testDeepCopy() {
|
||||||
JsonPrimitive a = new JsonPrimitive("a");
|
JsonPrimitive a = new JsonPrimitive("a");
|
||||||
assertSame(a, a.deepCopy()); // Primitives are immutable!
|
assertThat(a).isSameInstanceAs(a.deepCopy()); // Primitives are immutable!
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -15,53 +15,60 @@
|
||||||
*/
|
*/
|
||||||
package com.google.gson;
|
package com.google.gson;
|
||||||
|
|
||||||
import junit.framework.TestCase;
|
import static com.google.common.truth.Truth.assertThat;
|
||||||
|
import static org.junit.Assert.fail;
|
||||||
|
|
||||||
|
import java.io.EOFException;
|
||||||
import java.util.NoSuchElementException;
|
import java.util.NoSuchElementException;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Unit tests for {@link JsonStreamParser}
|
* Unit tests for {@link JsonStreamParser}
|
||||||
*
|
*
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
*/
|
*/
|
||||||
public class JsonStreamParserTest extends TestCase {
|
public class JsonStreamParserTest {
|
||||||
private JsonStreamParser parser;
|
private JsonStreamParser parser;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
parser = new JsonStreamParser("'one' 'two'");
|
parser = new JsonStreamParser("'one' 'two'");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testParseTwoStrings() {
|
public void testParseTwoStrings() {
|
||||||
String actualOne = parser.next().getAsString();
|
String actualOne = parser.next().getAsString();
|
||||||
assertEquals("one", actualOne);
|
assertThat(actualOne).isEqualTo("one");
|
||||||
String actualTwo = parser.next().getAsString();
|
String actualTwo = parser.next().getAsString();
|
||||||
assertEquals("two", actualTwo);
|
assertThat(actualTwo).isEqualTo("two");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testIterator() {
|
public void testIterator() {
|
||||||
assertTrue(parser.hasNext());
|
assertThat(parser.hasNext()).isTrue();
|
||||||
assertEquals("one", parser.next().getAsString());
|
assertThat(parser.next().getAsString()).isEqualTo("one");
|
||||||
assertTrue(parser.hasNext());
|
assertThat(parser.hasNext()).isTrue();
|
||||||
assertEquals("two", parser.next().getAsString());
|
assertThat(parser.next().getAsString()).isEqualTo("two");
|
||||||
assertFalse(parser.hasNext());
|
assertThat(parser.hasNext()).isFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void testNoSideEffectForHasNext() throws Exception {
|
@Test
|
||||||
assertTrue(parser.hasNext());
|
public void testNoSideEffectForHasNext() {
|
||||||
assertTrue(parser.hasNext());
|
assertThat(parser.hasNext()).isTrue();
|
||||||
assertTrue(parser.hasNext());
|
assertThat(parser.hasNext()).isTrue();
|
||||||
assertEquals("one", parser.next().getAsString());
|
assertThat(parser.hasNext()).isTrue();
|
||||||
|
assertThat(parser.next().getAsString()).isEqualTo("one");
|
||||||
|
|
||||||
assertTrue(parser.hasNext());
|
assertThat(parser.hasNext()).isTrue();
|
||||||
assertTrue(parser.hasNext());
|
assertThat(parser.hasNext()).isTrue();
|
||||||
assertEquals("two", parser.next().getAsString());
|
assertThat(parser.next().getAsString()).isEqualTo("two");
|
||||||
|
|
||||||
assertFalse(parser.hasNext());
|
assertThat(parser.hasNext()).isFalse();
|
||||||
assertFalse(parser.hasNext());
|
assertThat(parser.hasNext()).isFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testCallingNextBeyondAvailableInput() {
|
public void testCallingNextBeyondAvailableInput() {
|
||||||
parser.next();
|
parser.next();
|
||||||
parser.next();
|
parser.next();
|
||||||
|
@ -71,4 +78,51 @@ public class JsonStreamParserTest extends TestCase {
|
||||||
} catch (NoSuchElementException expected) {
|
} catch (NoSuchElementException expected) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testEmptyInput() {
|
||||||
|
JsonStreamParser parser = new JsonStreamParser("");
|
||||||
|
try {
|
||||||
|
parser.next();
|
||||||
|
fail();
|
||||||
|
} catch (JsonIOException e) {
|
||||||
|
assertThat(e.getCause()).isInstanceOf(EOFException.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
parser = new JsonStreamParser("");
|
||||||
|
try {
|
||||||
|
parser.hasNext();
|
||||||
|
fail();
|
||||||
|
} catch (JsonIOException e) {
|
||||||
|
assertThat(e.getCause()).isInstanceOf(EOFException.class);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testIncompleteInput() {
|
||||||
|
JsonStreamParser parser = new JsonStreamParser("[");
|
||||||
|
assertThat(parser.hasNext()).isTrue();
|
||||||
|
try {
|
||||||
|
parser.next();
|
||||||
|
fail();
|
||||||
|
} catch (JsonSyntaxException e) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testMalformedInput() {
|
||||||
|
JsonStreamParser parser = new JsonStreamParser(":");
|
||||||
|
try {
|
||||||
|
parser.hasNext();
|
||||||
|
fail();
|
||||||
|
} catch (JsonSyntaxException e) {
|
||||||
|
}
|
||||||
|
|
||||||
|
parser = new JsonStreamParser(":");
|
||||||
|
try {
|
||||||
|
parser.next();
|
||||||
|
fail();
|
||||||
|
} catch (JsonSyntaxException e) {
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -16,7 +16,9 @@
|
||||||
|
|
||||||
package com.google.gson;
|
package com.google.gson;
|
||||||
|
|
||||||
import junit.framework.TestCase;
|
import static com.google.common.truth.Truth.assertThat;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Unit test for the {@link LongSerializationPolicy} class.
|
* Unit test for the {@link LongSerializationPolicy} class.
|
||||||
|
@ -24,61 +26,67 @@ import junit.framework.TestCase;
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
* @author Joel Leitch
|
* @author Joel Leitch
|
||||||
*/
|
*/
|
||||||
public class LongSerializationPolicyTest extends TestCase {
|
public class LongSerializationPolicyTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDefaultLongSerialization() throws Exception {
|
public void testDefaultLongSerialization() throws Exception {
|
||||||
JsonElement element = LongSerializationPolicy.DEFAULT.serialize(1556L);
|
JsonElement element = LongSerializationPolicy.DEFAULT.serialize(1556L);
|
||||||
assertTrue(element.isJsonPrimitive());
|
assertThat(element.isJsonPrimitive()).isTrue();
|
||||||
|
|
||||||
JsonPrimitive jsonPrimitive = element.getAsJsonPrimitive();
|
JsonPrimitive jsonPrimitive = element.getAsJsonPrimitive();
|
||||||
assertFalse(jsonPrimitive.isString());
|
assertThat(jsonPrimitive.isString()).isFalse();
|
||||||
assertTrue(jsonPrimitive.isNumber());
|
assertThat(jsonPrimitive.isNumber()).isTrue();
|
||||||
assertEquals(1556L, element.getAsLong());
|
assertThat(element.getAsLong()).isEqualTo(1556L);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDefaultLongSerializationIntegration() {
|
public void testDefaultLongSerializationIntegration() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.setLongSerializationPolicy(LongSerializationPolicy.DEFAULT)
|
.setLongSerializationPolicy(LongSerializationPolicy.DEFAULT)
|
||||||
.create();
|
.create();
|
||||||
assertEquals("[1]", gson.toJson(new long[] { 1L }, long[].class));
|
assertThat(gson.toJson(new long[] { 1L }, long[].class)).isEqualTo("[1]");
|
||||||
assertEquals("[1]", gson.toJson(new Long[] { 1L }, Long[].class));
|
assertThat(gson.toJson(new Long[] { 1L }, Long[].class)).isEqualTo("[1]");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDefaultLongSerializationNull() {
|
public void testDefaultLongSerializationNull() {
|
||||||
LongSerializationPolicy policy = LongSerializationPolicy.DEFAULT;
|
LongSerializationPolicy policy = LongSerializationPolicy.DEFAULT;
|
||||||
assertTrue(policy.serialize(null).isJsonNull());
|
assertThat(policy.serialize(null).isJsonNull()).isTrue();
|
||||||
|
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.setLongSerializationPolicy(policy)
|
.setLongSerializationPolicy(policy)
|
||||||
.create();
|
.create();
|
||||||
assertEquals("null", gson.toJson(null, Long.class));
|
assertThat(gson.toJson(null, Long.class)).isEqualTo("null");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testStringLongSerialization() throws Exception {
|
public void testStringLongSerialization() throws Exception {
|
||||||
JsonElement element = LongSerializationPolicy.STRING.serialize(1556L);
|
JsonElement element = LongSerializationPolicy.STRING.serialize(1556L);
|
||||||
assertTrue(element.isJsonPrimitive());
|
assertThat(element.isJsonPrimitive()).isTrue();
|
||||||
|
|
||||||
JsonPrimitive jsonPrimitive = element.getAsJsonPrimitive();
|
JsonPrimitive jsonPrimitive = element.getAsJsonPrimitive();
|
||||||
assertFalse(jsonPrimitive.isNumber());
|
assertThat(jsonPrimitive.isNumber()).isFalse();
|
||||||
assertTrue(jsonPrimitive.isString());
|
assertThat(jsonPrimitive.isString()).isTrue();
|
||||||
assertEquals("1556", element.getAsString());
|
assertThat(element.getAsString()).isEqualTo("1556");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testStringLongSerializationIntegration() {
|
public void testStringLongSerializationIntegration() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.setLongSerializationPolicy(LongSerializationPolicy.STRING)
|
.setLongSerializationPolicy(LongSerializationPolicy.STRING)
|
||||||
.create();
|
.create();
|
||||||
assertEquals("[\"1\"]", gson.toJson(new long[] { 1L }, long[].class));
|
assertThat(gson.toJson(new long[] { 1L }, long[].class)).isEqualTo("[\"1\"]");
|
||||||
assertEquals("[\"1\"]", gson.toJson(new Long[] { 1L }, Long[].class));
|
assertThat(gson.toJson(new Long[] { 1L }, long[].class)).isEqualTo("[\"1\"]");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testStringLongSerializationNull() {
|
public void testStringLongSerializationNull() {
|
||||||
LongSerializationPolicy policy = LongSerializationPolicy.STRING;
|
LongSerializationPolicy policy = LongSerializationPolicy.STRING;
|
||||||
assertTrue(policy.serialize(null).isJsonNull());
|
assertThat(policy.serialize(null).isJsonNull()).isTrue();
|
||||||
|
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.setLongSerializationPolicy(policy)
|
.setLongSerializationPolicy(policy)
|
||||||
.create();
|
.create();
|
||||||
assertEquals("null", gson.toJson(null, Long.class));
|
assertThat(gson.toJson(null, Long.class)).isEqualTo("null");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -16,6 +16,9 @@
|
||||||
|
|
||||||
package com.google.gson;
|
package com.google.gson;
|
||||||
|
|
||||||
|
import static com.google.common.truth.Truth.assertThat;
|
||||||
|
import static org.junit.Assert.fail;
|
||||||
|
|
||||||
import com.google.gson.reflect.TypeToken;
|
import com.google.gson.reflect.TypeToken;
|
||||||
import com.google.gson.stream.JsonReader;
|
import com.google.gson.stream.JsonReader;
|
||||||
import com.google.gson.stream.JsonWriter;
|
import com.google.gson.stream.JsonWriter;
|
||||||
|
@ -25,9 +28,9 @@ import java.io.StringWriter;
|
||||||
import java.lang.reflect.Type;
|
import java.lang.reflect.Type;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import junit.framework.TestCase;
|
import org.junit.Test;
|
||||||
|
|
||||||
public final class MixedStreamTest extends TestCase {
|
public final class MixedStreamTest {
|
||||||
|
|
||||||
private static final Car BLUE_MUSTANG = new Car("mustang", 0x0000FF);
|
private static final Car BLUE_MUSTANG = new Car("mustang", 0x0000FF);
|
||||||
private static final Car BLACK_BMW = new Car("bmw", 0x000000);
|
private static final Car BLACK_BMW = new Car("bmw", 0x000000);
|
||||||
|
@ -47,6 +50,7 @@ public final class MixedStreamTest extends TestCase {
|
||||||
+ " }\n"
|
+ " }\n"
|
||||||
+ "]";
|
+ "]";
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testWriteMixedStreamed() throws IOException {
|
public void testWriteMixedStreamed() throws IOException {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
StringWriter stringWriter = new StringWriter();
|
StringWriter stringWriter = new StringWriter();
|
||||||
|
@ -59,21 +63,25 @@ public final class MixedStreamTest extends TestCase {
|
||||||
gson.toJson(RED_MIATA, Car.class, jsonWriter);
|
gson.toJson(RED_MIATA, Car.class, jsonWriter);
|
||||||
jsonWriter.endArray();
|
jsonWriter.endArray();
|
||||||
|
|
||||||
assertEquals(CARS_JSON, stringWriter.toString());
|
assertThat(stringWriter.toString()).isEqualTo(CARS_JSON);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testReadMixedStreamed() throws IOException {
|
public void testReadMixedStreamed() throws IOException {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
StringReader stringReader = new StringReader(CARS_JSON);
|
StringReader stringReader = new StringReader(CARS_JSON);
|
||||||
JsonReader jsonReader = new JsonReader(stringReader);
|
JsonReader jsonReader = new JsonReader(stringReader);
|
||||||
|
|
||||||
jsonReader.beginArray();
|
jsonReader.beginArray();
|
||||||
assertEquals(BLUE_MUSTANG, gson.fromJson(jsonReader, Car.class));
|
// actual and expected object are inverted in the test.
|
||||||
assertEquals(BLACK_BMW, gson.fromJson(jsonReader, Car.class));
|
// gson.fromJson(jsonReader, Car.class) as arg of assertThat() cause an ambiguous method call
|
||||||
assertEquals(RED_MIATA, gson.fromJson(jsonReader, Car.class));
|
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));
|
||||||
jsonReader.endArray();
|
jsonReader.endArray();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testReaderDoesNotMutateState() throws IOException {
|
public void testReaderDoesNotMutateState() throws IOException {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
JsonReader jsonReader = new JsonReader(new StringReader(CARS_JSON));
|
JsonReader jsonReader = new JsonReader(new StringReader(CARS_JSON));
|
||||||
|
@ -81,13 +89,14 @@ public final class MixedStreamTest extends TestCase {
|
||||||
|
|
||||||
jsonReader.setLenient(false);
|
jsonReader.setLenient(false);
|
||||||
gson.fromJson(jsonReader, Car.class);
|
gson.fromJson(jsonReader, Car.class);
|
||||||
assertFalse(jsonReader.isLenient());
|
assertThat(jsonReader.isLenient()).isFalse();
|
||||||
|
|
||||||
jsonReader.setLenient(true);
|
jsonReader.setLenient(true);
|
||||||
gson.fromJson(jsonReader, Car.class);
|
gson.fromJson(jsonReader, Car.class);
|
||||||
assertTrue(jsonReader.isLenient());
|
assertThat(jsonReader.isLenient()).isTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testWriteDoesNotMutateState() throws IOException {
|
public void testWriteDoesNotMutateState() throws IOException {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
JsonWriter jsonWriter = new JsonWriter(new StringWriter());
|
JsonWriter jsonWriter = new JsonWriter(new StringWriter());
|
||||||
|
@ -96,16 +105,17 @@ public final class MixedStreamTest extends TestCase {
|
||||||
jsonWriter.setHtmlSafe(true);
|
jsonWriter.setHtmlSafe(true);
|
||||||
jsonWriter.setLenient(true);
|
jsonWriter.setLenient(true);
|
||||||
gson.toJson(BLUE_MUSTANG, Car.class, jsonWriter);
|
gson.toJson(BLUE_MUSTANG, Car.class, jsonWriter);
|
||||||
assertTrue(jsonWriter.isHtmlSafe());
|
assertThat(jsonWriter.isHtmlSafe()).isTrue();
|
||||||
assertTrue(jsonWriter.isLenient());
|
assertThat(jsonWriter.isLenient()).isTrue();
|
||||||
|
|
||||||
jsonWriter.setHtmlSafe(false);
|
jsonWriter.setHtmlSafe(false);
|
||||||
jsonWriter.setLenient(false);
|
jsonWriter.setLenient(false);
|
||||||
gson.toJson(BLUE_MUSTANG, Car.class, jsonWriter);
|
gson.toJson(BLUE_MUSTANG, Car.class, jsonWriter);
|
||||||
assertFalse(jsonWriter.isHtmlSafe());
|
assertThat(jsonWriter.isHtmlSafe()).isFalse();
|
||||||
assertFalse(jsonWriter.isLenient());
|
assertThat(jsonWriter.isLenient()).isFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testReadInvalidState() throws IOException {
|
public void testReadInvalidState() throws IOException {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
JsonReader jsonReader = new JsonReader(new StringReader(CARS_JSON));
|
JsonReader jsonReader = new JsonReader(new StringReader(CARS_JSON));
|
||||||
|
@ -118,6 +128,7 @@ public final class MixedStreamTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testReadClosed() throws IOException {
|
public void testReadClosed() throws IOException {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
JsonReader jsonReader = new JsonReader(new StringReader(CARS_JSON));
|
JsonReader jsonReader = new JsonReader(new StringReader(CARS_JSON));
|
||||||
|
@ -129,6 +140,7 @@ public final class MixedStreamTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testWriteInvalidState() throws IOException {
|
public void testWriteInvalidState() throws IOException {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
JsonWriter jsonWriter = new JsonWriter(new StringWriter());
|
JsonWriter jsonWriter = new JsonWriter(new StringWriter());
|
||||||
|
@ -140,6 +152,7 @@ public final class MixedStreamTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testWriteClosed() throws IOException {
|
public void testWriteClosed() throws IOException {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
JsonWriter jsonWriter = new JsonWriter(new StringWriter());
|
JsonWriter jsonWriter = new JsonWriter(new StringWriter());
|
||||||
|
@ -153,6 +166,7 @@ public final class MixedStreamTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testWriteNulls() {
|
public void testWriteNulls() {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
try {
|
try {
|
||||||
|
@ -163,9 +177,10 @@ public final class MixedStreamTest extends TestCase {
|
||||||
|
|
||||||
StringWriter stringWriter = new StringWriter();
|
StringWriter stringWriter = new StringWriter();
|
||||||
gson.toJson(null, new JsonWriter(stringWriter));
|
gson.toJson(null, new JsonWriter(stringWriter));
|
||||||
assertEquals("null", stringWriter.toString());
|
assertThat(stringWriter.toString()).isEqualTo("null");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testReadNulls() {
|
public void testReadNulls() {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
try {
|
try {
|
||||||
|
@ -180,22 +195,24 @@ public final class MixedStreamTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testWriteHtmlSafe() {
|
public void testWriteHtmlSafe() {
|
||||||
List<String> contents = Arrays.asList("<", ">", "&", "=", "'");
|
List<String> contents = Arrays.asList("<", ">", "&", "=", "'");
|
||||||
Type type = new TypeToken<List<String>>() {}.getType();
|
Type type = new TypeToken<List<String>>() {}.getType();
|
||||||
|
|
||||||
StringWriter writer = new StringWriter();
|
StringWriter writer = new StringWriter();
|
||||||
new Gson().toJson(contents, type, new JsonWriter(writer));
|
new Gson().toJson(contents, type, new JsonWriter(writer));
|
||||||
assertEquals("[\"\\u003c\",\"\\u003e\",\"\\u0026\",\"\\u003d\",\"\\u0027\"]",
|
assertThat(writer.toString())
|
||||||
writer.toString());
|
.isEqualTo("[\"\\u003c\",\"\\u003e\",\"\\u0026\",\"\\u003d\",\"\\u0027\"]");
|
||||||
|
|
||||||
writer = new StringWriter();
|
writer = new StringWriter();
|
||||||
new GsonBuilder().disableHtmlEscaping().create()
|
new GsonBuilder().disableHtmlEscaping().create()
|
||||||
.toJson(contents, type, new JsonWriter(writer));
|
.toJson(contents, type, new JsonWriter(writer));
|
||||||
assertEquals("[\"<\",\">\",\"&\",\"=\",\"'\"]",
|
assertThat(writer.toString())
|
||||||
writer.toString());
|
.isEqualTo("[\"<\",\">\",\"&\",\"=\",\"'\"]");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testWriteLenient() {
|
public void testWriteLenient() {
|
||||||
List<Double> doubles = Arrays.asList(Double.NaN, Double.NEGATIVE_INFINITY,
|
List<Double> doubles = Arrays.asList(Double.NaN, Double.NEGATIVE_INFINITY,
|
||||||
Double.POSITIVE_INFINITY, -0.0d, 0.5d, 0.0d);
|
Double.POSITIVE_INFINITY, -0.0d, 0.5d, 0.0d);
|
||||||
|
@ -205,7 +222,7 @@ public final class MixedStreamTest extends TestCase {
|
||||||
JsonWriter jsonWriter = new JsonWriter(writer);
|
JsonWriter jsonWriter = new JsonWriter(writer);
|
||||||
new GsonBuilder().setLenient().serializeSpecialFloatingPointValues().create()
|
new GsonBuilder().setLenient().serializeSpecialFloatingPointValues().create()
|
||||||
.toJson(doubles, type, jsonWriter);
|
.toJson(doubles, type, jsonWriter);
|
||||||
assertEquals("[NaN,-Infinity,Infinity,-0.0,0.5,0.0]", writer.toString());
|
assertThat(writer.toString()).isEqualTo("[NaN,-Infinity,Infinity,-0.0,0.5,0.0]");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
new Gson().toJson(doubles, type, new JsonWriter(new StringWriter()));
|
new Gson().toJson(doubles, type, new JsonWriter(new StringWriter()));
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
package com.google.gson;
|
package com.google.gson;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static com.google.common.truth.Truth.assertThat;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
|
@ -36,6 +36,6 @@ public class ObjectTypeAdapterParameterizedTest {
|
||||||
String actualSerialized = adapter.toJson(deserialized);
|
String actualSerialized = adapter.toJson(deserialized);
|
||||||
|
|
||||||
// Serialized Object should be the same as original JSON
|
// Serialized Object should be the same as original JSON
|
||||||
assertEquals(json, actualSerialized);
|
assertThat(actualSerialized).isEqualTo(json);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -16,45 +16,52 @@
|
||||||
|
|
||||||
package com.google.gson;
|
package com.google.gson;
|
||||||
|
|
||||||
|
import static com.google.common.truth.Truth.assertThat;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import junit.framework.TestCase;
|
import org.junit.Test;
|
||||||
|
|
||||||
public final class ObjectTypeAdapterTest extends TestCase {
|
public final class ObjectTypeAdapterTest {
|
||||||
private final Gson gson = new GsonBuilder().create();
|
private final Gson gson = new GsonBuilder().create();
|
||||||
private final TypeAdapter<Object> adapter = gson.getAdapter(Object.class);
|
private final TypeAdapter<Object> adapter = gson.getAdapter(Object.class);
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserialize() throws Exception {
|
public void testDeserialize() throws Exception {
|
||||||
Map<?, ?> map = (Map<?, ?>) adapter.fromJson("{\"a\":5,\"b\":[1,2,null],\"c\":{\"x\":\"y\"}}");
|
Map<?, ?> map = (Map<?, ?>) adapter.fromJson("{\"a\":5,\"b\":[1,2,null],\"c\":{\"x\":\"y\"}}");
|
||||||
assertEquals(5.0, map.get("a"));
|
assertThat(map.get("a")).isEqualTo(5.0);
|
||||||
assertEquals(Arrays.asList(1.0, 2.0, null), map.get("b"));
|
assertThat(map.get("b")).isEqualTo(Arrays.asList(1.0, 2.0, null));
|
||||||
assertEquals(Collections.singletonMap("x", "y"), map.get("c"));
|
assertThat(map.get("c")).isEqualTo(Collections.singletonMap("x", "y"));
|
||||||
assertEquals(3, map.size());
|
assertThat(map).hasSize(3);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void testSerialize() throws Exception {
|
@Test
|
||||||
|
public void testSerialize() {
|
||||||
Object object = new RuntimeType();
|
Object object = new RuntimeType();
|
||||||
assertEquals("{'a':5,'b':[1,2,null]}", adapter.toJson(object).replace("\"", "'"));
|
assertThat(adapter.toJson(object).replace("\"", "'")).isEqualTo("{'a':5,'b':[1,2,null]}");
|
||||||
}
|
}
|
||||||
|
|
||||||
public void testSerializeNullValue() throws Exception {
|
@Test
|
||||||
|
public void testSerializeNullValue() {
|
||||||
Map<String, Object> map = new LinkedHashMap<>();
|
Map<String, Object> map = new LinkedHashMap<>();
|
||||||
map.put("a", null);
|
map.put("a", null);
|
||||||
assertEquals("{'a':null}", adapter.toJson(map).replace('"', '\''));
|
assertThat(adapter.toJson(map).replace('"', '\'')).isEqualTo("{'a':null}");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserializeNullValue() throws Exception {
|
public void testDeserializeNullValue() throws Exception {
|
||||||
Map<String, Object> map = new LinkedHashMap<>();
|
Map<String, Object> map = new LinkedHashMap<>();
|
||||||
map.put("a", null);
|
map.put("a", null);
|
||||||
assertEquals(map, adapter.fromJson("{\"a\":null}"));
|
assertThat(adapter.fromJson("{\"a\":null}")).isEqualTo(map);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void testSerializeObject() throws Exception {
|
@Test
|
||||||
assertEquals("{}", adapter.toJson(new Object()));
|
public void testSerializeObject() {
|
||||||
|
assertThat(adapter.toJson(new Object())).isEqualTo("{}");
|
||||||
}
|
}
|
||||||
|
|
||||||
private static String repeat(String s, int times) {
|
private static String repeat(String s, int times) {
|
||||||
|
@ -67,6 +74,7 @@ public final class ObjectTypeAdapterTest extends TestCase {
|
||||||
|
|
||||||
/** Deeply nested JSON arrays should not cause {@link StackOverflowError} */
|
/** Deeply nested JSON arrays should not cause {@link StackOverflowError} */
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
|
@Test
|
||||||
public void testDeserializeDeeplyNestedArrays() throws IOException {
|
public void testDeserializeDeeplyNestedArrays() throws IOException {
|
||||||
int times = 10000;
|
int times = 10000;
|
||||||
// [[[ ... ]]]
|
// [[[ ... ]]]
|
||||||
|
@ -79,14 +87,15 @@ public final class ObjectTypeAdapterTest extends TestCase {
|
||||||
if (current.isEmpty()) {
|
if (current.isEmpty()) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
assertEquals(1, current.size());
|
assertThat(current).hasSize(1);
|
||||||
current = (List<List<?>>) current.get(0);
|
current = (List<List<?>>) current.get(0);
|
||||||
}
|
}
|
||||||
assertEquals(times, actualTimes);
|
assertThat(actualTimes).isEqualTo(times);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Deeply nested JSON objects should not cause {@link StackOverflowError} */
|
/** Deeply nested JSON objects should not cause {@link StackOverflowError} */
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
|
@Test
|
||||||
public void testDeserializeDeeplyNestedObjects() throws IOException {
|
public void testDeserializeDeeplyNestedObjects() throws IOException {
|
||||||
int times = 10000;
|
int times = 10000;
|
||||||
// {"a":{"a": ... {"a":null} ... }}
|
// {"a":{"a": ... {"a":null} ... }}
|
||||||
|
@ -95,11 +104,11 @@ public final class ObjectTypeAdapterTest extends TestCase {
|
||||||
int actualTimes = 0;
|
int actualTimes = 0;
|
||||||
Map<String, Map<?, ?>> current = (Map<String, Map<?, ?>>) adapter.fromJson(json);
|
Map<String, Map<?, ?>> current = (Map<String, Map<?, ?>>) adapter.fromJson(json);
|
||||||
while (current != null) {
|
while (current != null) {
|
||||||
assertEquals(1, current.size());
|
assertThat(current).hasSize(1);
|
||||||
actualTimes++;
|
actualTimes++;
|
||||||
current = (Map<String, Map<?, ?>>) current.get("a");
|
current = (Map<String, Map<?, ?>>) current.get("a");
|
||||||
}
|
}
|
||||||
assertEquals(times, actualTimes);
|
assertThat(actualTimes).isEqualTo(times);
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings("unused")
|
@SuppressWarnings("unused")
|
||||||
|
|
|
@ -16,16 +16,18 @@
|
||||||
|
|
||||||
package com.google.gson;
|
package com.google.gson;
|
||||||
|
|
||||||
|
import static com.google.common.truth.Truth.assertThat;
|
||||||
|
|
||||||
import com.google.gson.stream.JsonReader;
|
import com.google.gson.stream.JsonReader;
|
||||||
import com.google.gson.stream.JsonWriter;
|
import com.google.gson.stream.JsonWriter;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
import junit.framework.TestCase;
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Jesse Wilson
|
* @author Jesse Wilson
|
||||||
*/
|
*/
|
||||||
public class OverrideCoreTypeAdaptersTest extends TestCase {
|
public class OverrideCoreTypeAdaptersTest {
|
||||||
private static final TypeAdapter<Boolean> booleanAsIntAdapter = new TypeAdapter<Boolean>() {
|
private static final TypeAdapter<Boolean> booleanAsIntAdapter = new TypeAdapter<Boolean>() {
|
||||||
@Override public void write(JsonWriter out, Boolean value) throws IOException {
|
@Override public void write(JsonWriter out, Boolean value) throws IOException {
|
||||||
out.value(value ? 1 : 0);
|
out.value(value ? 1 : 0);
|
||||||
|
@ -45,33 +47,36 @@ public class OverrideCoreTypeAdaptersTest extends TestCase {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testOverrideWrapperBooleanAdapter() {
|
public void testOverrideWrapperBooleanAdapter() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.registerTypeAdapter(Boolean.class, booleanAsIntAdapter)
|
.registerTypeAdapter(Boolean.class, booleanAsIntAdapter)
|
||||||
.create();
|
.create();
|
||||||
assertEquals("true", gson.toJson(true, boolean.class));
|
assertThat(gson.toJson(true, boolean.class)).isEqualTo("true");
|
||||||
assertEquals("1", gson.toJson(true, Boolean.class));
|
assertThat(gson.toJson(true, Boolean.class)).isEqualTo("1");
|
||||||
assertEquals(Boolean.TRUE, gson.fromJson("true", boolean.class));
|
assertThat(gson.fromJson("true", boolean.class)).isEqualTo(Boolean.TRUE);
|
||||||
assertEquals(Boolean.TRUE, gson.fromJson("1", Boolean.class));
|
assertThat(gson.fromJson("1", Boolean.class)).isEqualTo(Boolean.TRUE);
|
||||||
assertEquals(Boolean.FALSE, gson.fromJson("0", Boolean.class));
|
assertThat(gson.fromJson("0", Boolean.class)).isEqualTo(Boolean.FALSE);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testOverridePrimitiveBooleanAdapter() {
|
public void testOverridePrimitiveBooleanAdapter() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.registerTypeAdapter(boolean.class, booleanAsIntAdapter)
|
.registerTypeAdapter(boolean.class, booleanAsIntAdapter)
|
||||||
.create();
|
.create();
|
||||||
assertEquals("1", gson.toJson(true, boolean.class));
|
assertThat(gson.toJson(true, boolean.class)).isEqualTo("1");
|
||||||
assertEquals("true", gson.toJson(true, Boolean.class));
|
assertThat(gson.toJson(true, Boolean.class)).isEqualTo("true");
|
||||||
assertEquals(Boolean.TRUE, gson.fromJson("1", boolean.class));
|
assertThat(gson.fromJson("1", boolean.class)).isEqualTo(Boolean.TRUE);
|
||||||
assertEquals(Boolean.TRUE, gson.fromJson("true", Boolean.class));
|
assertThat(gson.fromJson("true", Boolean.class)).isEqualTo(Boolean.TRUE);
|
||||||
assertEquals("0", gson.toJson(false, boolean.class));
|
assertThat(gson.toJson(false, boolean.class)).isEqualTo("0");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testOverrideStringAdapter() {
|
public void testOverrideStringAdapter() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.registerTypeAdapter(String.class, swapCaseStringAdapter)
|
.registerTypeAdapter(String.class, swapCaseStringAdapter)
|
||||||
.create();
|
.create();
|
||||||
assertEquals("\"HELLO\"", gson.toJson("Hello", String.class));
|
assertThat(gson.toJson("Hello", String.class)).isEqualTo("\"HELLO\"");
|
||||||
assertEquals("hello", gson.fromJson("\"Hello\"", String.class));
|
assertThat(gson.fromJson("\"Hello\"", String.class)).isEqualTo("hello");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -16,14 +16,15 @@
|
||||||
|
|
||||||
package com.google.gson;
|
package com.google.gson;
|
||||||
|
|
||||||
|
import static com.google.common.truth.Truth.assertThat;
|
||||||
|
|
||||||
import com.google.gson.internal.$Gson$Types;
|
import com.google.gson.internal.$Gson$Types;
|
||||||
import com.google.gson.reflect.TypeToken;
|
import com.google.gson.reflect.TypeToken;
|
||||||
|
|
||||||
import junit.framework.TestCase;
|
|
||||||
|
|
||||||
import java.lang.reflect.ParameterizedType;
|
import java.lang.reflect.ParameterizedType;
|
||||||
import java.lang.reflect.Type;
|
import java.lang.reflect.Type;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Unit tests for {@code ParameterizedType}s created by the {@link $Gson$Types} class.
|
* Unit tests for {@code ParameterizedType}s created by the {@link $Gson$Types} class.
|
||||||
|
@ -31,27 +32,28 @@ import java.util.List;
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
* @author Joel Leitch
|
* @author Joel Leitch
|
||||||
*/
|
*/
|
||||||
public class ParameterizedTypeTest extends TestCase {
|
public class ParameterizedTypeTest {
|
||||||
private ParameterizedType ourType;
|
private ParameterizedType ourType;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
ourType = $Gson$Types.newParameterizedTypeWithOwner(null, List.class, String.class);
|
ourType = $Gson$Types.newParameterizedTypeWithOwner(null, List.class, String.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void testOurTypeFunctionality() throws Exception {
|
@Test
|
||||||
|
public void testOurTypeFunctionality() {
|
||||||
Type parameterizedType = new TypeToken<List<String>>() {}.getType();
|
Type parameterizedType = new TypeToken<List<String>>() {}.getType();
|
||||||
assertNull(ourType.getOwnerType());
|
assertThat(ourType.getOwnerType()).isNull();
|
||||||
assertEquals(String.class, ourType.getActualTypeArguments()[0]);
|
assertThat(ourType.getActualTypeArguments()[0]).isSameInstanceAs(String.class);
|
||||||
assertEquals(List.class, ourType.getRawType());
|
assertThat(ourType.getRawType()).isSameInstanceAs(List.class);
|
||||||
assertEquals(parameterizedType, ourType);
|
assertThat(ourType).isEqualTo(parameterizedType);
|
||||||
assertEquals(parameterizedType.hashCode(), ourType.hashCode());
|
assertThat(ourType.hashCode()).isEqualTo(parameterizedType.hashCode());
|
||||||
}
|
}
|
||||||
|
|
||||||
public void testNotEquals() throws Exception {
|
@Test
|
||||||
|
public void testNotEquals() {
|
||||||
Type differentParameterizedType = new TypeToken<List<Integer>>() {}.getType();
|
Type differentParameterizedType = new TypeToken<List<Integer>>() {}.getType();
|
||||||
assertFalse(differentParameterizedType.equals(ourType));
|
assertThat(differentParameterizedType.equals(ourType)).isFalse();
|
||||||
assertFalse(ourType.equals(differentParameterizedType));
|
assertThat(ourType.equals(differentParameterizedType)).isFalse();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -16,24 +16,28 @@
|
||||||
|
|
||||||
package com.google.gson;
|
package com.google.gson;
|
||||||
|
|
||||||
import java.io.IOException;
|
import static com.google.common.truth.Truth.assertThat;
|
||||||
import java.io.StringReader;
|
import static org.junit.Assert.fail;
|
||||||
import java.math.BigDecimal;
|
|
||||||
import com.google.gson.internal.LazilyParsedNumber;
|
import com.google.gson.internal.LazilyParsedNumber;
|
||||||
import com.google.gson.stream.JsonReader;
|
import com.google.gson.stream.JsonReader;
|
||||||
import com.google.gson.stream.MalformedJsonException;
|
import com.google.gson.stream.MalformedJsonException;
|
||||||
import junit.framework.TestCase;
|
import java.io.IOException;
|
||||||
|
import java.io.StringReader;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
public class ToNumberPolicyTest extends TestCase {
|
public class ToNumberPolicyTest {
|
||||||
|
@Test
|
||||||
public void testDouble() throws IOException {
|
public void testDouble() throws IOException {
|
||||||
ToNumberStrategy strategy = ToNumberPolicy.DOUBLE;
|
ToNumberStrategy strategy = ToNumberPolicy.DOUBLE;
|
||||||
assertEquals(10.1, strategy.readNumber(fromString("10.1")));
|
assertThat(strategy.readNumber(fromString("10.1"))).isEqualTo(10.1);
|
||||||
assertEquals(3.141592653589793D, strategy.readNumber(fromString("3.141592653589793238462643383279")));
|
assertThat(strategy.readNumber(fromString("3.141592653589793238462643383279"))).isEqualTo(3.141592653589793D);
|
||||||
try {
|
try {
|
||||||
strategy.readNumber(fromString("1e400"));
|
strategy.readNumber(fromString("1e400"));
|
||||||
fail();
|
fail();
|
||||||
} catch (MalformedJsonException expected) {
|
} catch (MalformedJsonException expected) {
|
||||||
assertEquals("JSON forbids NaN and infinities: Infinity at line 1 column 6 (char '\0') path $", expected.getMessage());
|
assertThat(expected).hasMessageThat().isEqualTo("JSON forbids NaN and infinities: Infinity at line 1 column 6 (char '\0') path $");
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
strategy.readNumber(fromString("\"not-a-number\""));
|
strategy.readNumber(fromString("\"not-a-number\""));
|
||||||
|
@ -42,68 +46,72 @@ public class ToNumberPolicyTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testLazilyParsedNumber() throws IOException {
|
public void testLazilyParsedNumber() throws IOException {
|
||||||
ToNumberStrategy strategy = ToNumberPolicy.LAZILY_PARSED_NUMBER;
|
ToNumberStrategy strategy = ToNumberPolicy.LAZILY_PARSED_NUMBER;
|
||||||
assertEquals(new LazilyParsedNumber("10.1"), strategy.readNumber(fromString("10.1")));
|
assertThat(strategy.readNumber(fromString("10.1"))).isEqualTo(new LazilyParsedNumber("10.1"));
|
||||||
assertEquals(new LazilyParsedNumber("3.141592653589793238462643383279"), strategy.readNumber(fromString("3.141592653589793238462643383279")));
|
assertThat(strategy.readNumber(fromString("3.141592653589793238462643383279"))).isEqualTo(new LazilyParsedNumber("3.141592653589793238462643383279"));
|
||||||
assertEquals(new LazilyParsedNumber("1e400"), strategy.readNumber(fromString("1e400")));
|
assertThat(strategy.readNumber(fromString("1e400"))).isEqualTo(new LazilyParsedNumber("1e400"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testLongOrDouble() throws IOException {
|
public void testLongOrDouble() throws IOException {
|
||||||
ToNumberStrategy strategy = ToNumberPolicy.LONG_OR_DOUBLE;
|
ToNumberStrategy strategy = ToNumberPolicy.LONG_OR_DOUBLE;
|
||||||
assertEquals(10L, strategy.readNumber(fromString("10")));
|
assertThat(strategy.readNumber(fromString("10"))).isEqualTo(10L);
|
||||||
assertEquals(10.1, strategy.readNumber(fromString("10.1")));
|
assertThat(strategy.readNumber(fromString("10.1"))).isEqualTo(10.1);
|
||||||
assertEquals(3.141592653589793D, strategy.readNumber(fromString("3.141592653589793238462643383279")));
|
assertThat(strategy.readNumber(fromString("3.141592653589793238462643383279"))).isEqualTo(3.141592653589793D);
|
||||||
try {
|
try {
|
||||||
strategy.readNumber(fromString("1e400"));
|
strategy.readNumber(fromString("1e400"));
|
||||||
fail();
|
fail();
|
||||||
} catch (MalformedJsonException expected) {
|
} catch (MalformedJsonException expected) {
|
||||||
assertEquals("JSON forbids NaN and infinities: Infinity; at path $", expected.getMessage());
|
assertThat(expected).hasMessageThat().isEqualTo("JSON forbids NaN and infinities: Infinity; at path $");
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
strategy.readNumber(fromString("\"not-a-number\""));
|
strategy.readNumber(fromString("\"not-a-number\""));
|
||||||
fail();
|
fail();
|
||||||
} catch (JsonParseException expected) {
|
} catch (JsonParseException expected) {
|
||||||
assertEquals("Cannot parse not-a-number; at path $", expected.getMessage());
|
assertThat(expected).hasMessageThat().isEqualTo("Cannot parse not-a-number; at path $");
|
||||||
}
|
}
|
||||||
|
|
||||||
assertEquals(Double.NaN, strategy.readNumber(fromStringLenient("NaN")));
|
assertThat(strategy.readNumber(fromStringLenient("NaN"))).isEqualTo(Double.NaN);
|
||||||
assertEquals(Double.POSITIVE_INFINITY, strategy.readNumber(fromStringLenient("Infinity")));
|
assertThat(strategy.readNumber(fromStringLenient("Infinity"))).isEqualTo(Double.POSITIVE_INFINITY);
|
||||||
assertEquals(Double.NEGATIVE_INFINITY, strategy.readNumber(fromStringLenient("-Infinity")));
|
assertThat(strategy.readNumber(fromStringLenient("-Infinity"))).isEqualTo(Double.NEGATIVE_INFINITY);
|
||||||
try {
|
try {
|
||||||
strategy.readNumber(fromString("NaN"));
|
strategy.readNumber(fromString("NaN"));
|
||||||
fail();
|
fail();
|
||||||
} catch (MalformedJsonException expected) {
|
} catch (MalformedJsonException expected) {
|
||||||
assertEquals("Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 (char 'N') path $", expected.getMessage());
|
assertThat(expected).hasMessageThat().isEqualTo("Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 (char 'N') path $");
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
strategy.readNumber(fromString("Infinity"));
|
strategy.readNumber(fromString("Infinity"));
|
||||||
fail();
|
fail();
|
||||||
} catch (MalformedJsonException expected) {
|
} catch (MalformedJsonException expected) {
|
||||||
assertEquals("Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 (char 'I') path $", expected.getMessage());
|
assertThat(expected).hasMessageThat().isEqualTo("Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 (char 'I') path $");
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
strategy.readNumber(fromString("-Infinity"));
|
strategy.readNumber(fromString("-Infinity"));
|
||||||
fail();
|
fail();
|
||||||
} catch (MalformedJsonException expected) {
|
} catch (MalformedJsonException expected) {
|
||||||
assertEquals("Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 (char '-') path $", expected.getMessage());
|
assertThat(expected).hasMessageThat().isEqualTo("Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 (char '-') path $");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBigDecimal() throws IOException {
|
public void testBigDecimal() throws IOException {
|
||||||
ToNumberStrategy strategy = ToNumberPolicy.BIG_DECIMAL;
|
ToNumberStrategy strategy = ToNumberPolicy.BIG_DECIMAL;
|
||||||
assertEquals(new BigDecimal("10.1"), strategy.readNumber(fromString("10.1")));
|
assertThat(strategy.readNumber(fromString("10.1"))).isEqualTo(new BigDecimal("10.1"));
|
||||||
assertEquals(new BigDecimal("3.141592653589793238462643383279"), strategy.readNumber(fromString("3.141592653589793238462643383279")));
|
assertThat(strategy.readNumber(fromString("3.141592653589793238462643383279"))).isEqualTo(new BigDecimal("3.141592653589793238462643383279"));
|
||||||
assertEquals(new BigDecimal("1e400"), strategy.readNumber(fromString("1e400")));
|
assertThat(strategy.readNumber(fromString("1e400"))).isEqualTo(new BigDecimal("1e400"));
|
||||||
|
|
||||||
try {
|
try {
|
||||||
strategy.readNumber(fromString("\"not-a-number\""));
|
strategy.readNumber(fromString("\"not-a-number\""));
|
||||||
fail();
|
fail();
|
||||||
} catch (JsonParseException expected) {
|
} catch (JsonParseException expected) {
|
||||||
assertEquals("Cannot parse not-a-number; at path $", expected.getMessage());
|
assertThat(expected).hasMessageThat().isEqualTo("Cannot parse not-a-number; at path $");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNullsAreNeverExpected() throws IOException {
|
public void testNullsAreNeverExpected() throws IOException {
|
||||||
try {
|
try {
|
||||||
ToNumberPolicy.DOUBLE.readNumber(fromString("null"));
|
ToNumberPolicy.DOUBLE.readNumber(fromString("null"));
|
||||||
|
|
|
@ -1,7 +1,6 @@
|
||||||
package com.google.gson;
|
package com.google.gson;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static com.google.common.truth.Truth.assertThat;
|
||||||
import static org.junit.Assert.assertNull;
|
|
||||||
import static org.junit.Assert.fail;
|
import static org.junit.Assert.fail;
|
||||||
|
|
||||||
import com.google.gson.stream.JsonReader;
|
import com.google.gson.stream.JsonReader;
|
||||||
|
@ -23,8 +22,8 @@ public class TypeAdapterTest {
|
||||||
}
|
}
|
||||||
}.nullSafe();
|
}.nullSafe();
|
||||||
|
|
||||||
assertEquals("null", adapter.toJson(null));
|
assertThat(adapter.toJson(null)).isEqualTo("null");
|
||||||
assertNull(adapter.fromJson("null"));
|
assertThat(adapter.fromJson("null")).isNull();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -39,7 +38,7 @@ public class TypeAdapterTest {
|
||||||
throw exception;
|
throw exception;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override public Integer read(JsonReader in) throws IOException {
|
@Override public Integer read(JsonReader in) {
|
||||||
throw new AssertionError("not needed by this test");
|
throw new AssertionError("not needed by this test");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
@ -48,14 +47,14 @@ public class TypeAdapterTest {
|
||||||
adapter.toJson(1);
|
adapter.toJson(1);
|
||||||
fail();
|
fail();
|
||||||
} catch (JsonIOException e) {
|
} catch (JsonIOException e) {
|
||||||
assertEquals(exception, e.getCause());
|
assertThat(e.getCause()).isEqualTo(exception);
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
adapter.toJsonTree(1);
|
adapter.toJsonTree(1);
|
||||||
fail();
|
fail();
|
||||||
} catch (JsonIOException e) {
|
} catch (JsonIOException e) {
|
||||||
assertEquals(exception, e.getCause());
|
assertThat(e.getCause()).isEqualTo(exception);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -73,13 +72,13 @@ public class TypeAdapterTest {
|
||||||
// whether that behavior is actually desired
|
// whether that behavior is actually desired
|
||||||
@Test
|
@Test
|
||||||
public void testFromJson_Reader_TrailingData() throws IOException {
|
public void testFromJson_Reader_TrailingData() throws IOException {
|
||||||
assertEquals("a", adapter.fromJson(new StringReader("\"a\"1")));
|
assertThat(adapter.fromJson(new StringReader("\"a\"1"))).isEqualTo("a");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Note: This test just verifies the current behavior; it is a bit questionable
|
// Note: This test just verifies the current behavior; it is a bit questionable
|
||||||
// whether that behavior is actually desired
|
// whether that behavior is actually desired
|
||||||
@Test
|
@Test
|
||||||
public void testFromJson_String_TrailingData() throws IOException {
|
public void testFromJson_String_TrailingData() throws IOException {
|
||||||
assertEquals("a", adapter.fromJson("\"a\"1"));
|
assertThat(adapter.fromJson("\"a\"1")).isEqualTo("a");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -16,8 +16,7 @@
|
||||||
|
|
||||||
package com.google.gson;
|
package com.google.gson;
|
||||||
|
|
||||||
import static org.junit.Assert.assertFalse;
|
import static com.google.common.truth.Truth.assertThat;
|
||||||
import static org.junit.Assert.assertTrue;
|
|
||||||
|
|
||||||
import com.google.gson.annotations.Since;
|
import com.google.gson.annotations.Since;
|
||||||
import com.google.gson.annotations.Until;
|
import com.google.gson.annotations.Until;
|
||||||
|
@ -35,41 +34,41 @@ public class VersionExclusionStrategyTest {
|
||||||
@Test
|
@Test
|
||||||
public void testSameVersion() throws Exception {
|
public void testSameVersion() throws Exception {
|
||||||
Excluder excluder = Excluder.DEFAULT.withVersion(VERSION);
|
Excluder excluder = Excluder.DEFAULT.withVersion(VERSION);
|
||||||
assertFalse(excluder.excludeClass(MockClassSince.class, true));
|
assertThat(excluder.excludeClass(MockClassSince.class, true)).isFalse();
|
||||||
assertFalse(excluder.excludeField(MockClassSince.class.getField("someField"), true));
|
assertThat(excluder.excludeField(MockClassSince.class.getField("someField"), true)).isFalse();
|
||||||
|
|
||||||
// Until version is exclusive
|
// Until version is exclusive
|
||||||
assertTrue(excluder.excludeClass(MockClassUntil.class, true));
|
assertThat(excluder.excludeClass(MockClassUntil.class, true)).isTrue();
|
||||||
assertTrue(excluder.excludeField(MockClassUntil.class.getField("someField"), true));
|
assertThat(excluder.excludeField(MockClassUntil.class.getField("someField"), true)).isTrue();
|
||||||
|
|
||||||
assertFalse(excluder.excludeClass(MockClassBoth.class, true));
|
assertThat(excluder.excludeClass(MockClassBoth.class, true)).isFalse();
|
||||||
assertFalse(excluder.excludeField(MockClassBoth.class.getField("someField"), true));
|
assertThat(excluder.excludeField(MockClassBoth.class.getField("someField"), true)).isFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testNewerVersion() throws Exception {
|
public void testNewerVersion() throws Exception {
|
||||||
Excluder excluder = Excluder.DEFAULT.withVersion(VERSION + 5);
|
Excluder excluder = Excluder.DEFAULT.withVersion(VERSION + 5);
|
||||||
assertFalse(excluder.excludeClass(MockClassSince.class, true));
|
assertThat(excluder.excludeClass(MockClassSince.class, true)).isFalse();
|
||||||
assertFalse(excluder.excludeField(MockClassSince.class.getField("someField"), true));
|
assertThat(excluder.excludeField(MockClassSince.class.getField("someField"), true)).isFalse();
|
||||||
|
|
||||||
assertTrue(excluder.excludeClass(MockClassUntil.class, true));
|
assertThat(excluder.excludeClass(MockClassUntil.class, true)).isTrue();
|
||||||
assertTrue(excluder.excludeField(MockClassUntil.class.getField("someField"), true));
|
assertThat(excluder.excludeField(MockClassUntil.class.getField("someField"), true)).isTrue();
|
||||||
|
|
||||||
assertTrue(excluder.excludeClass(MockClassBoth.class, true));
|
assertThat(excluder.excludeClass(MockClassBoth.class, true)).isTrue();
|
||||||
assertTrue(excluder.excludeField(MockClassBoth.class.getField("someField"), true));
|
assertThat(excluder.excludeField(MockClassBoth.class.getField("someField"), true)).isTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testOlderVersion() throws Exception {
|
public void testOlderVersion() throws Exception {
|
||||||
Excluder excluder = Excluder.DEFAULT.withVersion(VERSION - 5);
|
Excluder excluder = Excluder.DEFAULT.withVersion(VERSION - 5);
|
||||||
assertTrue(excluder.excludeClass(MockClassSince.class, true));
|
assertThat(excluder.excludeClass(MockClassSince.class, true)).isTrue();
|
||||||
assertTrue(excluder.excludeField(MockClassSince.class.getField("someField"), true));
|
assertThat(excluder.excludeField(MockClassSince.class.getField("someField"), true)).isTrue();
|
||||||
|
|
||||||
assertFalse(excluder.excludeClass(MockClassUntil.class, true));
|
assertThat(excluder.excludeClass(MockClassUntil.class, true)).isFalse();
|
||||||
assertFalse(excluder.excludeField(MockClassUntil.class.getField("someField"), true));
|
assertThat(excluder.excludeField(MockClassUntil.class.getField("someField"), true)).isFalse();
|
||||||
|
|
||||||
assertTrue(excluder.excludeClass(MockClassBoth.class, true));
|
assertThat(excluder.excludeClass(MockClassBoth.class, true)).isTrue();
|
||||||
assertTrue(excluder.excludeField(MockClassBoth.class.getField("someField"), true));
|
assertThat(excluder.excludeField(MockClassBoth.class.getField("someField"), true)).isTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Since(VERSION)
|
@Since(VERSION)
|
||||||
|
|
|
@ -17,6 +17,10 @@
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
import static org.junit.Assert.assertArrayEquals;
|
import static org.junit.Assert.assertArrayEquals;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertNull;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
import static org.junit.Assert.fail;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.GsonBuilder;
|
import com.google.gson.GsonBuilder;
|
||||||
|
@ -28,33 +32,36 @@ import java.lang.reflect.Type;
|
||||||
import java.math.BigDecimal;
|
import java.math.BigDecimal;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
import junit.framework.TestCase;
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
/**
|
/**
|
||||||
* Functional tests for Json serialization and deserialization of arrays.
|
* Functional tests for Json serialization and deserialization of arrays.
|
||||||
*
|
*
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
* @author Joel Leitch
|
* @author Joel Leitch
|
||||||
*/
|
*/
|
||||||
public class ArrayTest extends TestCase {
|
public class ArrayTest {
|
||||||
private Gson gson;
|
private Gson gson;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
gson = new Gson();
|
gson = new Gson();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testTopLevelArrayOfIntsSerialization() {
|
public void testTopLevelArrayOfIntsSerialization() {
|
||||||
int[] target = {1, 2, 3, 4, 5, 6, 7, 8, 9};
|
int[] target = {1, 2, 3, 4, 5, 6, 7, 8, 9};
|
||||||
assertEquals("[1,2,3,4,5,6,7,8,9]", gson.toJson(target));
|
assertEquals("[1,2,3,4,5,6,7,8,9]", gson.toJson(target));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testTopLevelArrayOfIntsDeserialization() {
|
public void testTopLevelArrayOfIntsDeserialization() {
|
||||||
int[] expected = {1, 2, 3, 4, 5, 6, 7, 8, 9};
|
int[] expected = {1, 2, 3, 4, 5, 6, 7, 8, 9};
|
||||||
int[] actual = gson.fromJson("[1,2,3,4,5,6,7,8,9]", int[].class);
|
int[] actual = gson.fromJson("[1,2,3,4,5,6,7,8,9]", int[].class);
|
||||||
assertArrayEquals(expected, actual);
|
assertArrayEquals(expected, actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testInvalidArrayDeserialization() {
|
public void testInvalidArrayDeserialization() {
|
||||||
String json = "[1, 2 3, 4, 5]";
|
String json = "[1, 2 3, 4, 5]";
|
||||||
try {
|
try {
|
||||||
|
@ -64,11 +71,13 @@ public class ArrayTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testEmptyArraySerialization() {
|
public void testEmptyArraySerialization() {
|
||||||
int[] target = {};
|
int[] target = {};
|
||||||
assertEquals("[]", gson.toJson(target));
|
assertEquals("[]", gson.toJson(target));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testEmptyArrayDeserialization() {
|
public void testEmptyArrayDeserialization() {
|
||||||
int[] actualObject = gson.fromJson("[]", int[].class);
|
int[] actualObject = gson.fromJson("[]", int[].class);
|
||||||
assertTrue(actualObject.length == 0);
|
assertTrue(actualObject.length == 0);
|
||||||
|
@ -80,6 +89,7 @@ public class ArrayTest extends TestCase {
|
||||||
assertTrue(actualObject.length == 0);
|
assertTrue(actualObject.length == 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNullsInArraySerialization() {
|
public void testNullsInArraySerialization() {
|
||||||
String[] array = {"foo", null, "bar"};
|
String[] array = {"foo", null, "bar"};
|
||||||
String expected = "[\"foo\",null,\"bar\"]";
|
String expected = "[\"foo\",null,\"bar\"]";
|
||||||
|
@ -87,6 +97,7 @@ public class ArrayTest extends TestCase {
|
||||||
assertEquals(expected, json);
|
assertEquals(expected, json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNullsInArrayDeserialization() {
|
public void testNullsInArrayDeserialization() {
|
||||||
String json = "[\"foo\",null,\"bar\"]";
|
String json = "[\"foo\",null,\"bar\"]";
|
||||||
String[] expected = {"foo", null, "bar"};
|
String[] expected = {"foo", null, "bar"};
|
||||||
|
@ -96,6 +107,7 @@ public class ArrayTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSingleNullInArraySerialization() {
|
public void testSingleNullInArraySerialization() {
|
||||||
BagOfPrimitives[] array = new BagOfPrimitives[1];
|
BagOfPrimitives[] array = new BagOfPrimitives[1];
|
||||||
array[0] = null;
|
array[0] = null;
|
||||||
|
@ -103,11 +115,13 @@ public class ArrayTest extends TestCase {
|
||||||
assertEquals("[null]", json);
|
assertEquals("[null]", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSingleNullInArrayDeserialization() {
|
public void testSingleNullInArrayDeserialization() {
|
||||||
BagOfPrimitives[] array = gson.fromJson("[null]", BagOfPrimitives[].class);
|
BagOfPrimitives[] array = gson.fromJson("[null]", BagOfPrimitives[].class);
|
||||||
assertNull(array[0]);
|
assertNull(array[0]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNullsInArrayWithSerializeNullPropertySetSerialization() {
|
public void testNullsInArrayWithSerializeNullPropertySetSerialization() {
|
||||||
gson = new GsonBuilder().serializeNulls().create();
|
gson = new GsonBuilder().serializeNulls().create();
|
||||||
String[] array = {"foo", null, "bar"};
|
String[] array = {"foo", null, "bar"};
|
||||||
|
@ -116,11 +130,13 @@ public class ArrayTest extends TestCase {
|
||||||
assertEquals(expected, json);
|
assertEquals(expected, json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testArrayOfStringsSerialization() {
|
public void testArrayOfStringsSerialization() {
|
||||||
String[] target = {"Hello", "World"};
|
String[] target = {"Hello", "World"};
|
||||||
assertEquals("[\"Hello\",\"World\"]", gson.toJson(target));
|
assertEquals("[\"Hello\",\"World\"]", gson.toJson(target));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testArrayOfStringsDeserialization() {
|
public void testArrayOfStringsDeserialization() {
|
||||||
String json = "[\"Hello\",\"World\"]";
|
String json = "[\"Hello\",\"World\"]";
|
||||||
String[] target = gson.fromJson(json, String[].class);
|
String[] target = gson.fromJson(json, String[].class);
|
||||||
|
@ -128,12 +144,14 @@ public class ArrayTest extends TestCase {
|
||||||
assertEquals("World", target[1]);
|
assertEquals("World", target[1]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSingleStringArraySerialization() throws Exception {
|
public void testSingleStringArraySerialization() throws Exception {
|
||||||
String[] s = { "hello" };
|
String[] s = { "hello" };
|
||||||
String output = gson.toJson(s);
|
String output = gson.toJson(s);
|
||||||
assertEquals("[\"hello\"]", output);
|
assertEquals("[\"hello\"]", output);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSingleStringArrayDeserialization() throws Exception {
|
public void testSingleStringArrayDeserialization() throws Exception {
|
||||||
String json = "[\"hello\"]";
|
String json = "[\"hello\"]";
|
||||||
String[] arrayType = gson.fromJson(json, String[].class);
|
String[] arrayType = gson.fromJson(json, String[].class);
|
||||||
|
@ -141,6 +159,7 @@ public class ArrayTest extends TestCase {
|
||||||
assertEquals("hello", arrayType[0]);
|
assertEquals("hello", arrayType[0]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testArrayOfCollectionSerialization() throws Exception {
|
public void testArrayOfCollectionSerialization() throws Exception {
|
||||||
StringBuilder sb = new StringBuilder("[");
|
StringBuilder sb = new StringBuilder("[");
|
||||||
int arraySize = 3;
|
int arraySize = 3;
|
||||||
|
@ -166,6 +185,7 @@ public class ArrayTest extends TestCase {
|
||||||
assertEquals(sb.toString(), json);
|
assertEquals(sb.toString(), json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testArrayOfCollectionDeserialization() throws Exception {
|
public void testArrayOfCollectionDeserialization() throws Exception {
|
||||||
String json = "[[1,2],[3,4]]";
|
String json = "[[1,2],[3,4]]";
|
||||||
Type type = new TypeToken<Collection<Integer>[]>() {}.getType();
|
Type type = new TypeToken<Collection<Integer>[]>() {}.getType();
|
||||||
|
@ -176,6 +196,7 @@ public class ArrayTest extends TestCase {
|
||||||
assertArrayEquals(new Integer[] {3, 4}, target[1].toArray(new Integer[0]));
|
assertArrayEquals(new Integer[] {3, 4}, target[1].toArray(new Integer[0]));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testArrayOfPrimitivesAsObjectsSerialization() throws Exception {
|
public void testArrayOfPrimitivesAsObjectsSerialization() throws Exception {
|
||||||
Object[] objs = new Object[] {1, "abc", 0.3f, 5L};
|
Object[] objs = new Object[] {1, "abc", 0.3f, 5L};
|
||||||
String json = gson.toJson(objs);
|
String json = gson.toJson(objs);
|
||||||
|
@ -184,16 +205,18 @@ public class ArrayTest extends TestCase {
|
||||||
assertTrue(json.contains("5"));
|
assertTrue(json.contains("5"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testArrayOfPrimitivesAsObjectsDeserialization() throws Exception {
|
public void testArrayOfPrimitivesAsObjectsDeserialization() throws Exception {
|
||||||
String json = "[1,\"abc\",0.3,1.1,5]";
|
String json = "[1,\"abc\",0.3,1.1,5]";
|
||||||
Object[] objs = gson.fromJson(json, Object[].class);
|
Object[] objs = gson.fromJson(json, Object[].class);
|
||||||
assertEquals(1, ((Number)objs[0]).intValue());
|
assertEquals(1, ((Number)objs[0]).intValue());
|
||||||
assertEquals("abc", objs[1]);
|
assertEquals("abc", objs[1]);
|
||||||
assertEquals(0.3, ((Number)objs[2]).doubleValue());
|
assertEquals(0.3, ((Number)objs[2]).doubleValue(), 0);
|
||||||
assertEquals(new BigDecimal("1.1"), new BigDecimal(objs[3].toString()));
|
assertEquals(new BigDecimal("1.1"), new BigDecimal(objs[3].toString()));
|
||||||
assertEquals(5, ((Number)objs[4]).shortValue());
|
assertEquals(5, ((Number)objs[4]).shortValue());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testObjectArrayWithNonPrimitivesSerialization() throws Exception {
|
public void testObjectArrayWithNonPrimitivesSerialization() throws Exception {
|
||||||
ClassWithObjects classWithObjects = new ClassWithObjects();
|
ClassWithObjects classWithObjects = new ClassWithObjects();
|
||||||
BagOfPrimitives bagOfPrimitives = new BagOfPrimitives();
|
BagOfPrimitives bagOfPrimitives = new BagOfPrimitives();
|
||||||
|
@ -207,12 +230,14 @@ public class ArrayTest extends TestCase {
|
||||||
assertTrue(json.contains(bagOfPrimitivesJson));
|
assertTrue(json.contains(bagOfPrimitivesJson));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testArrayOfNullSerialization() {
|
public void testArrayOfNullSerialization() {
|
||||||
Object[] array = {null};
|
Object[] array = {null};
|
||||||
String json = gson.toJson(array);
|
String json = gson.toJson(array);
|
||||||
assertEquals("[null]", json);
|
assertEquals("[null]", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testArrayOfNullDeserialization() {
|
public void testArrayOfNullDeserialization() {
|
||||||
String[] values = gson.fromJson("[null]", String[].class);
|
String[] values = gson.fromJson("[null]", String[].class);
|
||||||
assertNull(values[0]);
|
assertNull(values[0]);
|
||||||
|
@ -221,6 +246,7 @@ public class ArrayTest extends TestCase {
|
||||||
/**
|
/**
|
||||||
* Regression tests for Issue 272
|
* Regression tests for Issue 272
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testMultidimensionalArraysSerialization() {
|
public void testMultidimensionalArraysSerialization() {
|
||||||
String[][] items = {
|
String[][] items = {
|
||||||
{"3m Co", "71.72", "0.02", "0.03", "4/2 12:00am", "Manufacturing"},
|
{"3m Co", "71.72", "0.02", "0.03", "4/2 12:00am", "Manufacturing"},
|
||||||
|
@ -231,11 +257,13 @@ public class ArrayTest extends TestCase {
|
||||||
assertTrue(json.contains("Manufacturing\"]]"));
|
assertTrue(json.contains("Manufacturing\"]]"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testMultidimensionalObjectArraysSerialization() {
|
public void testMultidimensionalObjectArraysSerialization() {
|
||||||
Object[][] array = {new Object[] { 1, 2 }};
|
Object[][] array = {new Object[] { 1, 2 }};
|
||||||
assertEquals("[[1,2]]", gson.toJson(array));
|
assertEquals("[[1,2]]", gson.toJson(array));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testMultidimensionalPrimitiveArraysSerialization() {
|
public void testMultidimensionalPrimitiveArraysSerialization() {
|
||||||
int[][] array = {{1, 2}, {3, 4}};
|
int[][] array = {{1, 2}, {3, 4}};
|
||||||
assertEquals("[[1,2],[3,4]]", gson.toJson(array));
|
assertEquals("[[1,2],[3,4]]", gson.toJson(array));
|
||||||
|
@ -244,6 +272,7 @@ public class ArrayTest extends TestCase {
|
||||||
/**
|
/**
|
||||||
* Regression test for Issue 205
|
* Regression test for Issue 205
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testMixingTypesInObjectArraySerialization() {
|
public void testMixingTypesInObjectArraySerialization() {
|
||||||
Object[] array = {1, 2, new Object[] {"one", "two", 3}};
|
Object[] array = {1, 2, new Object[] {"one", "two", 3}};
|
||||||
assertEquals("[1,2,[\"one\",\"two\",3]]", gson.toJson(array));
|
assertEquals("[1,2,[\"one\",\"two\",3]]", gson.toJson(array));
|
||||||
|
@ -252,6 +281,7 @@ public class ArrayTest extends TestCase {
|
||||||
/**
|
/**
|
||||||
* Regression tests for Issue 272
|
* Regression tests for Issue 272
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testMultidimensionalArraysDeserialization() {
|
public void testMultidimensionalArraysDeserialization() {
|
||||||
String json = "[[\"3m Co\",\"71.72\",\"0.02\",\"0.03\",\"4/2 12:00am\",\"Manufacturing\"],"
|
String json = "[[\"3m Co\",\"71.72\",\"0.02\",\"0.03\",\"4/2 12:00am\",\"Manufacturing\"],"
|
||||||
+ "[\"Alcoa Inc\",\"29.01\",\"0.42\",\"1.47\",\"4/1 12:00am\",\"Manufacturing\"]]";
|
+ "[\"Alcoa Inc\",\"29.01\",\"0.42\",\"1.47\",\"4/1 12:00am\",\"Manufacturing\"]]";
|
||||||
|
@ -260,6 +290,7 @@ public class ArrayTest extends TestCase {
|
||||||
assertEquals("Manufacturing", items[1][5]);
|
assertEquals("Manufacturing", items[1][5]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testMultidimensionalPrimitiveArraysDeserialization() {
|
public void testMultidimensionalPrimitiveArraysDeserialization() {
|
||||||
String json = "[[1,2],[3,4]]";
|
String json = "[[1,2],[3,4]]";
|
||||||
int[][] expected = {{1, 2}, {3, 4}};
|
int[][] expected = {{1, 2}, {3, 4}};
|
||||||
|
@ -267,6 +298,7 @@ public class ArrayTest extends TestCase {
|
||||||
}
|
}
|
||||||
|
|
||||||
/** http://code.google.com/p/google-gson/issues/detail?id=342 */
|
/** http://code.google.com/p/google-gson/issues/detail?id=342 */
|
||||||
|
@Test
|
||||||
public void testArrayElementsAreArrays() {
|
public void testArrayElementsAreArrays() {
|
||||||
Object[] stringArrays = {
|
Object[] stringArrays = {
|
||||||
new String[] {"test1", "test2"},
|
new String[] {"test1", "test2"},
|
||||||
|
|
|
@ -15,11 +15,10 @@
|
||||||
*/
|
*/
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
import java.lang.reflect.Type;
|
import static org.junit.Assert.assertEquals;
|
||||||
import java.util.ArrayList;
|
import static org.junit.Assert.assertFalse;
|
||||||
import java.util.Collection;
|
import static org.junit.Assert.assertNotNull;
|
||||||
|
import static org.junit.Assert.fail;
|
||||||
import junit.framework.TestCase;
|
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.GsonBuilder;
|
import com.google.gson.GsonBuilder;
|
||||||
|
@ -28,6 +27,11 @@ import com.google.gson.JsonObject;
|
||||||
import com.google.gson.JsonSerializationContext;
|
import com.google.gson.JsonSerializationContext;
|
||||||
import com.google.gson.JsonSerializer;
|
import com.google.gson.JsonSerializer;
|
||||||
import com.google.gson.common.TestTypes.ClassOverridingEquals;
|
import com.google.gson.common.TestTypes.ClassOverridingEquals;
|
||||||
|
import java.lang.reflect.Type;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collection;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Functional tests related to circular reference detection and error reporting.
|
* Functional tests related to circular reference detection and error reporting.
|
||||||
|
@ -35,15 +39,15 @@ import com.google.gson.common.TestTypes.ClassOverridingEquals;
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
* @author Joel Leitch
|
* @author Joel Leitch
|
||||||
*/
|
*/
|
||||||
public class CircularReferenceTest extends TestCase {
|
public class CircularReferenceTest {
|
||||||
private Gson gson;
|
private Gson gson;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
gson = new Gson();
|
gson = new Gson();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testCircularSerialization() throws Exception {
|
public void testCircularSerialization() throws Exception {
|
||||||
ContainsReferenceToSelfType a = new ContainsReferenceToSelfType();
|
ContainsReferenceToSelfType a = new ContainsReferenceToSelfType();
|
||||||
ContainsReferenceToSelfType b = new ContainsReferenceToSelfType();
|
ContainsReferenceToSelfType b = new ContainsReferenceToSelfType();
|
||||||
|
@ -56,6 +60,7 @@ public class CircularReferenceTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSelfReferenceIgnoredInSerialization() throws Exception {
|
public void testSelfReferenceIgnoredInSerialization() throws Exception {
|
||||||
ClassOverridingEquals objA = new ClassOverridingEquals();
|
ClassOverridingEquals objA = new ClassOverridingEquals();
|
||||||
objA.ref = objA;
|
objA.ref = objA;
|
||||||
|
@ -64,6 +69,7 @@ public class CircularReferenceTest extends TestCase {
|
||||||
assertFalse(json.contains("ref")); // self-reference is ignored
|
assertFalse(json.contains("ref")); // self-reference is ignored
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSelfReferenceArrayFieldSerialization() throws Exception {
|
public void testSelfReferenceArrayFieldSerialization() throws Exception {
|
||||||
ClassWithSelfReferenceArray objA = new ClassWithSelfReferenceArray();
|
ClassWithSelfReferenceArray objA = new ClassWithSelfReferenceArray();
|
||||||
objA.children = new ClassWithSelfReferenceArray[]{objA};
|
objA.children = new ClassWithSelfReferenceArray[]{objA};
|
||||||
|
@ -75,6 +81,7 @@ public class CircularReferenceTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSelfReferenceCustomHandlerSerialization() throws Exception {
|
public void testSelfReferenceCustomHandlerSerialization() throws Exception {
|
||||||
ClassWithSelfReference obj = new ClassWithSelfReference();
|
ClassWithSelfReference obj = new ClassWithSelfReference();
|
||||||
obj.child = obj;
|
obj.child = obj;
|
||||||
|
@ -94,6 +101,7 @@ public class CircularReferenceTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDirectedAcyclicGraphSerialization() throws Exception {
|
public void testDirectedAcyclicGraphSerialization() throws Exception {
|
||||||
ContainsReferenceToSelfType a = new ContainsReferenceToSelfType();
|
ContainsReferenceToSelfType a = new ContainsReferenceToSelfType();
|
||||||
ContainsReferenceToSelfType b = new ContainsReferenceToSelfType();
|
ContainsReferenceToSelfType b = new ContainsReferenceToSelfType();
|
||||||
|
@ -104,6 +112,7 @@ public class CircularReferenceTest extends TestCase {
|
||||||
assertNotNull(gson.toJson(a));
|
assertNotNull(gson.toJson(a));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDirectedAcyclicGraphDeserialization() throws Exception {
|
public void testDirectedAcyclicGraphDeserialization() throws Exception {
|
||||||
String json = "{\"children\":[{\"children\":[{\"children\":[]}]},{\"children\":[]}]}";
|
String json = "{\"children\":[{\"children\":[{\"children\":[]}]},{\"children\":[]}]}";
|
||||||
ContainsReferenceToSelfType target = gson.fromJson(json, ContainsReferenceToSelfType.class);
|
ContainsReferenceToSelfType target = gson.fromJson(json, ContainsReferenceToSelfType.class);
|
||||||
|
|
|
@ -17,6 +17,9 @@
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
import static org.junit.Assert.assertArrayEquals;
|
import static org.junit.Assert.assertArrayEquals;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertNotNull;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.GsonBuilder;
|
import com.google.gson.GsonBuilder;
|
||||||
|
@ -40,7 +43,8 @@ import java.util.Queue;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.Stack;
|
import java.util.Stack;
|
||||||
import java.util.Vector;
|
import java.util.Vector;
|
||||||
import junit.framework.TestCase;
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Functional tests for Json serialization and deserialization of collections.
|
* Functional tests for Json serialization and deserialization of collections.
|
||||||
|
@ -48,15 +52,15 @@ import junit.framework.TestCase;
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
* @author Joel Leitch
|
* @author Joel Leitch
|
||||||
*/
|
*/
|
||||||
public class CollectionTest extends TestCase {
|
public class CollectionTest {
|
||||||
private Gson gson;
|
private Gson gson;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
gson = new Gson();
|
gson = new Gson();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testTopLevelCollectionOfIntegersSerialization() {
|
public void testTopLevelCollectionOfIntegersSerialization() {
|
||||||
Collection<Integer> target = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
|
Collection<Integer> target = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
|
||||||
Type targetType = new TypeToken<Collection<Integer>>() {}.getType();
|
Type targetType = new TypeToken<Collection<Integer>>() {}.getType();
|
||||||
|
@ -64,6 +68,7 @@ public class CollectionTest extends TestCase {
|
||||||
assertEquals("[1,2,3,4,5,6,7,8,9]", json);
|
assertEquals("[1,2,3,4,5,6,7,8,9]", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testTopLevelCollectionOfIntegersDeserialization() {
|
public void testTopLevelCollectionOfIntegersDeserialization() {
|
||||||
String json = "[0,1,2,3,4,5,6,7,8,9]";
|
String json = "[0,1,2,3,4,5,6,7,8,9]";
|
||||||
Type collectionType = new TypeToken<Collection<Integer>>() { }.getType();
|
Type collectionType = new TypeToken<Collection<Integer>>() { }.getType();
|
||||||
|
@ -72,6 +77,7 @@ public class CollectionTest extends TestCase {
|
||||||
assertArrayEquals(expected, toIntArray(target));
|
assertArrayEquals(expected, toIntArray(target));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testTopLevelListOfIntegerCollectionsDeserialization() throws Exception {
|
public void testTopLevelListOfIntegerCollectionsDeserialization() throws Exception {
|
||||||
String json = "[[1,2,3],[4,5,6],[7,8,9]]";
|
String json = "[[1,2,3],[4,5,6],[7,8,9]]";
|
||||||
Type collectionType = new TypeToken<Collection<Collection<Integer>>>() {}.getType();
|
Type collectionType = new TypeToken<Collection<Collection<Integer>>>() {}.getType();
|
||||||
|
@ -89,6 +95,7 @@ public class CollectionTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testLinkedListSerialization() {
|
public void testLinkedListSerialization() {
|
||||||
List<String> list = new LinkedList<>();
|
List<String> list = new LinkedList<>();
|
||||||
list.add("a1");
|
list.add("a1");
|
||||||
|
@ -99,6 +106,7 @@ public class CollectionTest extends TestCase {
|
||||||
assertTrue(json.contains("a2"));
|
assertTrue(json.contains("a2"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testLinkedListDeserialization() {
|
public void testLinkedListDeserialization() {
|
||||||
String json = "[\"a1\",\"a2\"]";
|
String json = "[\"a1\",\"a2\"]";
|
||||||
Type linkedListType = new TypeToken<LinkedList<String>>() {}.getType();
|
Type linkedListType = new TypeToken<LinkedList<String>>() {}.getType();
|
||||||
|
@ -107,6 +115,7 @@ public class CollectionTest extends TestCase {
|
||||||
assertEquals("a2", list.get(1));
|
assertEquals("a2", list.get(1));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testQueueSerialization() {
|
public void testQueueSerialization() {
|
||||||
Queue<String> queue = new LinkedList<>();
|
Queue<String> queue = new LinkedList<>();
|
||||||
queue.add("a1");
|
queue.add("a1");
|
||||||
|
@ -117,6 +126,7 @@ public class CollectionTest extends TestCase {
|
||||||
assertTrue(json.contains("a2"));
|
assertTrue(json.contains("a2"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testQueueDeserialization() {
|
public void testQueueDeserialization() {
|
||||||
String json = "[\"a1\",\"a2\"]";
|
String json = "[\"a1\",\"a2\"]";
|
||||||
Type queueType = new TypeToken<Queue<String>>() {}.getType();
|
Type queueType = new TypeToken<Queue<String>>() {}.getType();
|
||||||
|
@ -126,6 +136,7 @@ public class CollectionTest extends TestCase {
|
||||||
assertEquals("a2", queue.element());
|
assertEquals("a2", queue.element());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testPriorityQueue() throws Exception {
|
public void testPriorityQueue() throws Exception {
|
||||||
Type type = new TypeToken<PriorityQueue<Integer>>(){}.getType();
|
Type type = new TypeToken<PriorityQueue<Integer>>(){}.getType();
|
||||||
PriorityQueue<Integer> queue = gson.fromJson("[10, 20, 22]", type);
|
PriorityQueue<Integer> queue = gson.fromJson("[10, 20, 22]", type);
|
||||||
|
@ -137,6 +148,7 @@ public class CollectionTest extends TestCase {
|
||||||
assertEquals("[10,20,22]", json);
|
assertEquals("[10,20,22]", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testVector() {
|
public void testVector() {
|
||||||
Type type = new TypeToken<Vector<Integer>>(){}.getType();
|
Type type = new TypeToken<Vector<Integer>>(){}.getType();
|
||||||
Vector<Integer> target = gson.fromJson("[10, 20, 31]", type);
|
Vector<Integer> target = gson.fromJson("[10, 20, 31]", type);
|
||||||
|
@ -148,6 +160,7 @@ public class CollectionTest extends TestCase {
|
||||||
assertEquals("[10,20,31]", json);
|
assertEquals("[10,20,31]", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testStack() {
|
public void testStack() {
|
||||||
Type type = new TypeToken<Stack<Integer>>(){}.getType();
|
Type type = new TypeToken<Stack<Integer>>(){}.getType();
|
||||||
Stack<Integer> target = gson.fromJson("[11, 13, 17]", type);
|
Stack<Integer> target = gson.fromJson("[11, 13, 17]", type);
|
||||||
|
@ -159,6 +172,7 @@ public class CollectionTest extends TestCase {
|
||||||
assertEquals("[11,13,17]", json);
|
assertEquals("[11,13,17]", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNullsInListSerialization() {
|
public void testNullsInListSerialization() {
|
||||||
List<String> list = new ArrayList<>();
|
List<String> list = new ArrayList<>();
|
||||||
list.add("foo");
|
list.add("foo");
|
||||||
|
@ -170,6 +184,7 @@ public class CollectionTest extends TestCase {
|
||||||
assertEquals(expected, json);
|
assertEquals(expected, json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNullsInListDeserialization() {
|
public void testNullsInListDeserialization() {
|
||||||
List<String> expected = new ArrayList<>();
|
List<String> expected = new ArrayList<>();
|
||||||
expected.add("foo");
|
expected.add("foo");
|
||||||
|
@ -183,6 +198,7 @@ public class CollectionTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testCollectionOfObjectSerialization() {
|
public void testCollectionOfObjectSerialization() {
|
||||||
List<Object> target = new ArrayList<>();
|
List<Object> target = new ArrayList<>();
|
||||||
target.add("Hello");
|
target.add("Hello");
|
||||||
|
@ -193,6 +209,7 @@ public class CollectionTest extends TestCase {
|
||||||
assertEquals("[\"Hello\",\"World\"]", gson.toJson(target, type));
|
assertEquals("[\"Hello\",\"World\"]", gson.toJson(target, type));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testCollectionOfObjectWithNullSerialization() {
|
public void testCollectionOfObjectWithNullSerialization() {
|
||||||
List<Object> target = new ArrayList<>();
|
List<Object> target = new ArrayList<>();
|
||||||
target.add("Hello");
|
target.add("Hello");
|
||||||
|
@ -204,6 +221,7 @@ public class CollectionTest extends TestCase {
|
||||||
assertEquals("[\"Hello\",null,\"World\"]", gson.toJson(target, type));
|
assertEquals("[\"Hello\",null,\"World\"]", gson.toJson(target, type));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testCollectionOfStringsSerialization() {
|
public void testCollectionOfStringsSerialization() {
|
||||||
List<String> target = new ArrayList<>();
|
List<String> target = new ArrayList<>();
|
||||||
target.add("Hello");
|
target.add("Hello");
|
||||||
|
@ -211,6 +229,7 @@ public class CollectionTest extends TestCase {
|
||||||
assertEquals("[\"Hello\",\"World\"]", gson.toJson(target));
|
assertEquals("[\"Hello\",\"World\"]", gson.toJson(target));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testCollectionOfBagOfPrimitivesSerialization() {
|
public void testCollectionOfBagOfPrimitivesSerialization() {
|
||||||
List<BagOfPrimitives> target = new ArrayList<>();
|
List<BagOfPrimitives> target = new ArrayList<>();
|
||||||
BagOfPrimitives objA = new BagOfPrimitives(3L, 1, true, "blah");
|
BagOfPrimitives objA = new BagOfPrimitives(3L, 1, true, "blah");
|
||||||
|
@ -226,6 +245,7 @@ public class CollectionTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testCollectionOfStringsDeserialization() {
|
public void testCollectionOfStringsDeserialization() {
|
||||||
String json = "[\"Hello\",\"World\"]";
|
String json = "[\"Hello\",\"World\"]";
|
||||||
Type collectionType = new TypeToken<Collection<String>>() { }.getType();
|
Type collectionType = new TypeToken<Collection<String>>() { }.getType();
|
||||||
|
@ -235,11 +255,13 @@ public class CollectionTest extends TestCase {
|
||||||
assertTrue(target.contains("World"));
|
assertTrue(target.contains("World"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testRawCollectionOfIntegersSerialization() {
|
public void testRawCollectionOfIntegersSerialization() {
|
||||||
Collection<Integer> target = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
|
Collection<Integer> target = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
|
||||||
assertEquals("[1,2,3,4,5,6,7,8,9]", gson.toJson(target));
|
assertEquals("[1,2,3,4,5,6,7,8,9]", gson.toJson(target));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testObjectCollectionSerialization() {
|
public void testObjectCollectionSerialization() {
|
||||||
BagOfPrimitives bag1 = new BagOfPrimitives();
|
BagOfPrimitives bag1 = new BagOfPrimitives();
|
||||||
Collection<?> target = Arrays.asList(bag1, bag1, "test");
|
Collection<?> target = Arrays.asList(bag1, bag1, "test");
|
||||||
|
@ -247,6 +269,7 @@ public class CollectionTest extends TestCase {
|
||||||
assertTrue(json.contains(bag1.getExpectedJson()));
|
assertTrue(json.contains(bag1.getExpectedJson()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testRawCollectionDeserializationNotAlllowed() {
|
public void testRawCollectionDeserializationNotAlllowed() {
|
||||||
String json = "[0,1,2,3,4,5,6,7,8,9]";
|
String json = "[0,1,2,3,4,5,6,7,8,9]";
|
||||||
Collection<?> integers = gson.fromJson(json, Collection.class);
|
Collection<?> integers = gson.fromJson(json, Collection.class);
|
||||||
|
@ -259,6 +282,7 @@ public class CollectionTest extends TestCase {
|
||||||
assertTrue(strings.contains("World"));
|
assertTrue(strings.contains("World"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testRawCollectionOfBagOfPrimitivesNotAllowed() {
|
public void testRawCollectionOfBagOfPrimitivesNotAllowed() {
|
||||||
BagOfPrimitives bag = new BagOfPrimitives(10, 20, false, "stringValue");
|
BagOfPrimitives bag = new BagOfPrimitives(10, 20, false, "stringValue");
|
||||||
String json = '[' + bag.getExpectedJson() + ',' + bag.getExpectedJson() + ']';
|
String json = '[' + bag.getExpectedJson() + ',' + bag.getExpectedJson() + ']';
|
||||||
|
@ -274,6 +298,7 @@ public class CollectionTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testWildcardPrimitiveCollectionSerilaization() throws Exception {
|
public void testWildcardPrimitiveCollectionSerilaization() throws Exception {
|
||||||
Collection<? extends Integer> target = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
|
Collection<? extends Integer> target = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
|
||||||
Type collectionType = new TypeToken<Collection<? extends Integer>>() { }.getType();
|
Type collectionType = new TypeToken<Collection<? extends Integer>>() { }.getType();
|
||||||
|
@ -284,6 +309,7 @@ public class CollectionTest extends TestCase {
|
||||||
assertEquals("[1,2,3,4,5,6,7,8,9]", json);
|
assertEquals("[1,2,3,4,5,6,7,8,9]", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testWildcardPrimitiveCollectionDeserilaization() throws Exception {
|
public void testWildcardPrimitiveCollectionDeserilaization() throws Exception {
|
||||||
String json = "[1,2,3,4,5,6,7,8,9]";
|
String json = "[1,2,3,4,5,6,7,8,9]";
|
||||||
Type collectionType = new TypeToken<Collection<? extends Integer>>() { }.getType();
|
Type collectionType = new TypeToken<Collection<? extends Integer>>() { }.getType();
|
||||||
|
@ -293,6 +319,7 @@ public class CollectionTest extends TestCase {
|
||||||
assertTrue(target.contains(9));
|
assertTrue(target.contains(9));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testWildcardCollectionField() throws Exception {
|
public void testWildcardCollectionField() throws Exception {
|
||||||
Collection<BagOfPrimitives> collection = new ArrayList<>();
|
Collection<BagOfPrimitives> collection = new ArrayList<>();
|
||||||
BagOfPrimitives objA = new BagOfPrimitives(3L, 1, true, "blah");
|
BagOfPrimitives objA = new BagOfPrimitives(3L, 1, true, "blah");
|
||||||
|
@ -312,6 +339,7 @@ public class CollectionTest extends TestCase {
|
||||||
assertTrue(deserializedCollection.contains(objB));
|
assertTrue(deserializedCollection.contains(objB));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testFieldIsArrayList() {
|
public void testFieldIsArrayList() {
|
||||||
HasArrayListField object = new HasArrayListField();
|
HasArrayListField object = new HasArrayListField();
|
||||||
object.longs.add(1L);
|
object.longs.add(1L);
|
||||||
|
@ -322,6 +350,7 @@ public class CollectionTest extends TestCase {
|
||||||
assertEquals(Arrays.asList(1L, 3L), copy.longs);
|
assertEquals(Arrays.asList(1L, 3L), copy.longs);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testUserCollectionTypeAdapter() {
|
public void testUserCollectionTypeAdapter() {
|
||||||
Type listOfString = new TypeToken<List<String>>() {}.getType();
|
Type listOfString = new TypeToken<List<String>>() {}.getType();
|
||||||
Object stringListSerializer = new JsonSerializer<List<String>>() {
|
Object stringListSerializer = new JsonSerializer<List<String>>() {
|
||||||
|
@ -372,6 +401,7 @@ public class CollectionTest extends TestCase {
|
||||||
this.value = value;
|
this.value = value;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@Test
|
||||||
public void testSetSerialization() {
|
public void testSetSerialization() {
|
||||||
Set<Entry> set = new HashSet<>();
|
Set<Entry> set = new HashSet<>();
|
||||||
set.add(new Entry(1));
|
set.add(new Entry(1));
|
||||||
|
@ -380,6 +410,7 @@ public class CollectionTest extends TestCase {
|
||||||
assertTrue(json.contains("1"));
|
assertTrue(json.contains("1"));
|
||||||
assertTrue(json.contains("2"));
|
assertTrue(json.contains("2"));
|
||||||
}
|
}
|
||||||
|
@Test
|
||||||
public void testSetDeserialization() {
|
public void testSetDeserialization() {
|
||||||
String json = "[{\"value\":1},{\"value\":2}]";
|
String json = "[{\"value\":1},{\"value\":2}]";
|
||||||
Type type = new TypeToken<Set<Entry>>() {}.getType();
|
Type type = new TypeToken<Set<Entry>>() {}.getType();
|
||||||
|
@ -394,6 +425,7 @@ public class CollectionTest extends TestCase {
|
||||||
|
|
||||||
private class SmallClass { private String inSmall; }
|
private class SmallClass { private String inSmall; }
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testIssue1107() {
|
public void testIssue1107() {
|
||||||
String json = "{\n" +
|
String json = "{\n" +
|
||||||
" \"inBig\": {\n" +
|
" \"inBig\": {\n" +
|
||||||
|
|
|
@ -15,14 +15,15 @@
|
||||||
*/
|
*/
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
|
||||||
|
import com.google.gson.Gson;
|
||||||
import java.util.concurrent.CountDownLatch;
|
import java.util.concurrent.CountDownLatch;
|
||||||
import java.util.concurrent.ExecutorService;
|
import java.util.concurrent.ExecutorService;
|
||||||
import java.util.concurrent.Executors;
|
import java.util.concurrent.Executors;
|
||||||
import java.util.concurrent.atomic.AtomicBoolean;
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
import org.junit.Before;
|
||||||
import junit.framework.TestCase;
|
import org.junit.Test;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests for ensuring Gson thread-safety.
|
* Tests for ensuring Gson thread-safety.
|
||||||
|
@ -30,12 +31,11 @@ import com.google.gson.Gson;
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
* @author Joel Leitch
|
* @author Joel Leitch
|
||||||
*/
|
*/
|
||||||
public class ConcurrencyTest extends TestCase {
|
public class ConcurrencyTest {
|
||||||
private Gson gson;
|
private Gson gson;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
gson = new Gson();
|
gson = new Gson();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -43,6 +43,7 @@ public class ConcurrencyTest extends TestCase {
|
||||||
* Source-code based on
|
* Source-code based on
|
||||||
* http://groups.google.com/group/google-gson/browse_thread/thread/563bb51ee2495081
|
* http://groups.google.com/group/google-gson/browse_thread/thread/563bb51ee2495081
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testSingleThreadSerialization() {
|
public void testSingleThreadSerialization() {
|
||||||
MyObject myObj = new MyObject();
|
MyObject myObj = new MyObject();
|
||||||
for (int i = 0; i < 10; i++) {
|
for (int i = 0; i < 10; i++) {
|
||||||
|
@ -54,6 +55,7 @@ public class ConcurrencyTest extends TestCase {
|
||||||
* Source-code based on
|
* Source-code based on
|
||||||
* http://groups.google.com/group/google-gson/browse_thread/thread/563bb51ee2495081
|
* http://groups.google.com/group/google-gson/browse_thread/thread/563bb51ee2495081
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testSingleThreadDeserialization() {
|
public void testSingleThreadDeserialization() {
|
||||||
for (int i = 0; i < 10; i++) {
|
for (int i = 0; i < 10; i++) {
|
||||||
gson.fromJson("{\"a\":\"hello\",\"b\":\"world\",\"i\":1}", MyObject.class);
|
gson.fromJson("{\"a\":\"hello\",\"b\":\"world\",\"i\":1}", MyObject.class);
|
||||||
|
@ -64,6 +66,7 @@ public class ConcurrencyTest extends TestCase {
|
||||||
* Source-code based on
|
* Source-code based on
|
||||||
* http://groups.google.com/group/google-gson/browse_thread/thread/563bb51ee2495081
|
* http://groups.google.com/group/google-gson/browse_thread/thread/563bb51ee2495081
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testMultiThreadSerialization() throws InterruptedException {
|
public void testMultiThreadSerialization() throws InterruptedException {
|
||||||
final CountDownLatch startLatch = new CountDownLatch(1);
|
final CountDownLatch startLatch = new CountDownLatch(1);
|
||||||
final CountDownLatch finishedLatch = new CountDownLatch(10);
|
final CountDownLatch finishedLatch = new CountDownLatch(10);
|
||||||
|
@ -95,6 +98,7 @@ public class ConcurrencyTest extends TestCase {
|
||||||
* Source-code based on
|
* Source-code based on
|
||||||
* http://groups.google.com/group/google-gson/browse_thread/thread/563bb51ee2495081
|
* http://groups.google.com/group/google-gson/browse_thread/thread/563bb51ee2495081
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testMultiThreadDeserialization() throws InterruptedException {
|
public void testMultiThreadDeserialization() throws InterruptedException {
|
||||||
final CountDownLatch startLatch = new CountDownLatch(1);
|
final CountDownLatch startLatch = new CountDownLatch(1);
|
||||||
final CountDownLatch finishedLatch = new CountDownLatch(10);
|
final CountDownLatch finishedLatch = new CountDownLatch(10);
|
||||||
|
|
|
@ -16,6 +16,9 @@
|
||||||
|
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertNull;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.GsonBuilder;
|
import com.google.gson.GsonBuilder;
|
||||||
import com.google.gson.JsonDeserializationContext;
|
import com.google.gson.JsonDeserializationContext;
|
||||||
|
@ -25,10 +28,9 @@ import com.google.gson.JsonObject;
|
||||||
import com.google.gson.JsonParseException;
|
import com.google.gson.JsonParseException;
|
||||||
import com.google.gson.common.TestTypes.Base;
|
import com.google.gson.common.TestTypes.Base;
|
||||||
import com.google.gson.common.TestTypes.ClassWithBaseField;
|
import com.google.gson.common.TestTypes.ClassWithBaseField;
|
||||||
|
|
||||||
import junit.framework.TestCase;
|
|
||||||
|
|
||||||
import java.lang.reflect.Type;
|
import java.lang.reflect.Type;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Functional Test exercising custom deserialization only. When test applies to both
|
* Functional Test exercising custom deserialization only. When test applies to both
|
||||||
|
@ -36,18 +38,18 @@ import java.lang.reflect.Type;
|
||||||
*
|
*
|
||||||
* @author Joel Leitch
|
* @author Joel Leitch
|
||||||
*/
|
*/
|
||||||
public class CustomDeserializerTest extends TestCase {
|
public class CustomDeserializerTest {
|
||||||
private static final String DEFAULT_VALUE = "test123";
|
private static final String DEFAULT_VALUE = "test123";
|
||||||
private static final String SUFFIX = "blah";
|
private static final String SUFFIX = "blah";
|
||||||
|
|
||||||
private Gson gson;
|
private Gson gson;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
gson = new GsonBuilder().registerTypeAdapter(DataHolder.class, new DataHolderDeserializer()).create();
|
gson = new GsonBuilder().registerTypeAdapter(DataHolder.class, new DataHolderDeserializer()).create();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDefaultConstructorNotCalledOnObject() throws Exception {
|
public void testDefaultConstructorNotCalledOnObject() throws Exception {
|
||||||
DataHolder data = new DataHolder(DEFAULT_VALUE);
|
DataHolder data = new DataHolder(DEFAULT_VALUE);
|
||||||
String json = gson.toJson(data);
|
String json = gson.toJson(data);
|
||||||
|
@ -56,6 +58,7 @@ public class CustomDeserializerTest extends TestCase {
|
||||||
assertEquals(DEFAULT_VALUE + SUFFIX, actual.getData());
|
assertEquals(DEFAULT_VALUE + SUFFIX, actual.getData());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDefaultConstructorNotCalledOnField() throws Exception {
|
public void testDefaultConstructorNotCalledOnField() throws Exception {
|
||||||
DataHolderWrapper dataWrapper = new DataHolderWrapper(new DataHolder(DEFAULT_VALUE));
|
DataHolderWrapper dataWrapper = new DataHolderWrapper(new DataHolder(DEFAULT_VALUE));
|
||||||
String json = gson.toJson(dataWrapper);
|
String json = gson.toJson(dataWrapper);
|
||||||
|
@ -110,6 +113,7 @@ public class CustomDeserializerTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testJsonTypeFieldBasedDeserialization() {
|
public void testJsonTypeFieldBasedDeserialization() {
|
||||||
String json = "{field1:'abc',field2:'def',__type__:'SUB_TYPE1'}";
|
String json = "{field1:'abc',field2:'def',__type__:'SUB_TYPE1'}";
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
|
@ -147,6 +151,7 @@ public class CustomDeserializerTest extends TestCase {
|
||||||
String field2;
|
String field2;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testCustomDeserializerReturnsNullForTopLevelObject() {
|
public void testCustomDeserializerReturnsNullForTopLevelObject() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.setLenient()
|
.setLenient()
|
||||||
|
@ -156,6 +161,7 @@ public class CustomDeserializerTest extends TestCase {
|
||||||
assertNull(target);
|
assertNull(target);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testCustomDeserializerReturnsNull() {
|
public void testCustomDeserializerReturnsNull() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.setLenient()
|
.setLenient()
|
||||||
|
@ -165,6 +171,7 @@ public class CustomDeserializerTest extends TestCase {
|
||||||
assertNull(target.base);
|
assertNull(target.base);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testCustomDeserializerReturnsNullForArrayElements() {
|
public void testCustomDeserializerReturnsNullForArrayElements() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.setLenient()
|
.setLenient()
|
||||||
|
@ -175,6 +182,7 @@ public class CustomDeserializerTest extends TestCase {
|
||||||
assertNull(target[1]);
|
assertNull(target[1]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testCustomDeserializerReturnsNullForArrayElementsForArrayField() {
|
public void testCustomDeserializerReturnsNullForArrayElementsForArrayField() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.setLenient()
|
.setLenient()
|
||||||
|
|
|
@ -16,6 +16,9 @@
|
||||||
|
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.GsonBuilder;
|
import com.google.gson.GsonBuilder;
|
||||||
import com.google.gson.JsonArray;
|
import com.google.gson.JsonArray;
|
||||||
|
@ -29,10 +32,8 @@ import com.google.gson.common.TestTypes.ClassWithBaseArrayField;
|
||||||
import com.google.gson.common.TestTypes.ClassWithBaseField;
|
import com.google.gson.common.TestTypes.ClassWithBaseField;
|
||||||
import com.google.gson.common.TestTypes.Sub;
|
import com.google.gson.common.TestTypes.Sub;
|
||||||
import com.google.gson.common.TestTypes.SubSerializer;
|
import com.google.gson.common.TestTypes.SubSerializer;
|
||||||
|
|
||||||
import junit.framework.TestCase;
|
|
||||||
|
|
||||||
import java.lang.reflect.Type;
|
import java.lang.reflect.Type;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Functional Test exercising custom serialization only. When test applies to both
|
* Functional Test exercising custom serialization only. When test applies to both
|
||||||
|
@ -40,8 +41,9 @@ import java.lang.reflect.Type;
|
||||||
*
|
*
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
*/
|
*/
|
||||||
public class CustomSerializerTest extends TestCase {
|
public class CustomSerializerTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBaseClassSerializerInvokedForBaseClassFields() {
|
public void testBaseClassSerializerInvokedForBaseClassFields() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.registerTypeAdapter(Base.class, new BaseSerializer())
|
.registerTypeAdapter(Base.class, new BaseSerializer())
|
||||||
|
@ -53,6 +55,7 @@ public class CustomSerializerTest extends TestCase {
|
||||||
assertEquals(BaseSerializer.NAME, base.get(Base.SERIALIZER_KEY).getAsString());
|
assertEquals(BaseSerializer.NAME, base.get(Base.SERIALIZER_KEY).getAsString());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSubClassSerializerInvokedForBaseClassFieldsHoldingSubClassInstances() {
|
public void testSubClassSerializerInvokedForBaseClassFieldsHoldingSubClassInstances() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.registerTypeAdapter(Base.class, new BaseSerializer())
|
.registerTypeAdapter(Base.class, new BaseSerializer())
|
||||||
|
@ -64,6 +67,7 @@ public class CustomSerializerTest extends TestCase {
|
||||||
assertEquals(SubSerializer.NAME, base.get(Base.SERIALIZER_KEY).getAsString());
|
assertEquals(SubSerializer.NAME, base.get(Base.SERIALIZER_KEY).getAsString());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSubClassSerializerInvokedForBaseClassFieldsHoldingArrayOfSubClassInstances() {
|
public void testSubClassSerializerInvokedForBaseClassFieldsHoldingArrayOfSubClassInstances() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.registerTypeAdapter(Base.class, new BaseSerializer())
|
.registerTypeAdapter(Base.class, new BaseSerializer())
|
||||||
|
@ -78,6 +82,7 @@ public class CustomSerializerTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBaseClassSerializerInvokedForBaseClassFieldsHoldingSubClassInstances() {
|
public void testBaseClassSerializerInvokedForBaseClassFieldsHoldingSubClassInstances() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.registerTypeAdapter(Base.class, new BaseSerializer())
|
.registerTypeAdapter(Base.class, new BaseSerializer())
|
||||||
|
@ -88,6 +93,7 @@ public class CustomSerializerTest extends TestCase {
|
||||||
assertEquals(BaseSerializer.NAME, base.get(Base.SERIALIZER_KEY).getAsString());
|
assertEquals(BaseSerializer.NAME, base.get(Base.SERIALIZER_KEY).getAsString());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSerializerReturnsNull() {
|
public void testSerializerReturnsNull() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.registerTypeAdapter(Base.class, new JsonSerializer<Base>() {
|
.registerTypeAdapter(Base.class, new JsonSerializer<Base>() {
|
||||||
|
|
|
@ -15,6 +15,11 @@
|
||||||
*/
|
*/
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertNull;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.GsonBuilder;
|
import com.google.gson.GsonBuilder;
|
||||||
import com.google.gson.InstanceCreator;
|
import com.google.gson.InstanceCreator;
|
||||||
|
@ -35,7 +40,9 @@ import java.util.HashMap;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import junit.framework.TestCase;
|
import org.junit.Before;
|
||||||
|
import org.junit.Ignore;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Functional tests for the support of custom serializer and deserializers.
|
* Functional tests for the support of custom serializer and deserializers.
|
||||||
|
@ -43,15 +50,15 @@ import junit.framework.TestCase;
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
* @author Joel Leitch
|
* @author Joel Leitch
|
||||||
*/
|
*/
|
||||||
public class CustomTypeAdaptersTest extends TestCase {
|
public class CustomTypeAdaptersTest {
|
||||||
private GsonBuilder builder;
|
private GsonBuilder builder;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
builder = new GsonBuilder();
|
builder = new GsonBuilder();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testCustomSerializers() {
|
public void testCustomSerializers() {
|
||||||
Gson gson = builder.registerTypeAdapter(
|
Gson gson = builder.registerTypeAdapter(
|
||||||
ClassWithCustomTypeConverter.class, new JsonSerializer<ClassWithCustomTypeConverter>() {
|
ClassWithCustomTypeConverter.class, new JsonSerializer<ClassWithCustomTypeConverter>() {
|
||||||
|
@ -67,6 +74,7 @@ public class CustomTypeAdaptersTest extends TestCase {
|
||||||
assertEquals("{\"bag\":5,\"value\":25}", gson.toJson(target));
|
assertEquals("{\"bag\":5,\"value\":25}", gson.toJson(target));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testCustomDeserializers() {
|
public void testCustomDeserializers() {
|
||||||
Gson gson = new GsonBuilder().registerTypeAdapter(
|
Gson gson = new GsonBuilder().registerTypeAdapter(
|
||||||
ClassWithCustomTypeConverter.class, new JsonDeserializer<ClassWithCustomTypeConverter>() {
|
ClassWithCustomTypeConverter.class, new JsonDeserializer<ClassWithCustomTypeConverter>() {
|
||||||
|
@ -83,6 +91,8 @@ public class CustomTypeAdaptersTest extends TestCase {
|
||||||
assertEquals(5, target.getBag().getIntValue());
|
assertEquals(5, target.getBag().getIntValue());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@Ignore
|
||||||
public void disable_testCustomSerializersOfSelf() {
|
public void disable_testCustomSerializersOfSelf() {
|
||||||
Gson gson = createGsonObjectWithFooTypeAdapter();
|
Gson gson = createGsonObjectWithFooTypeAdapter();
|
||||||
Gson basicGson = new Gson();
|
Gson basicGson = new Gson();
|
||||||
|
@ -93,6 +103,8 @@ public class CustomTypeAdaptersTest extends TestCase {
|
||||||
assertEquals(jsonFromGson, jsonFromCustomSerializer);
|
assertEquals(jsonFromGson, jsonFromCustomSerializer);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@Ignore
|
||||||
public void disable_testCustomDeserializersOfSelf() {
|
public void disable_testCustomDeserializersOfSelf() {
|
||||||
Gson gson = createGsonObjectWithFooTypeAdapter();
|
Gson gson = createGsonObjectWithFooTypeAdapter();
|
||||||
Gson basicGson = new Gson();
|
Gson basicGson = new Gson();
|
||||||
|
@ -104,6 +116,7 @@ public class CustomTypeAdaptersTest extends TestCase {
|
||||||
assertEquals(expectedFoo.value, newFooObject.value);
|
assertEquals(expectedFoo.value, newFooObject.value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testCustomNestedSerializers() {
|
public void testCustomNestedSerializers() {
|
||||||
Gson gson = new GsonBuilder().registerTypeAdapter(
|
Gson gson = new GsonBuilder().registerTypeAdapter(
|
||||||
BagOfPrimitives.class, new JsonSerializer<BagOfPrimitives>() {
|
BagOfPrimitives.class, new JsonSerializer<BagOfPrimitives>() {
|
||||||
|
@ -116,6 +129,7 @@ public class CustomTypeAdaptersTest extends TestCase {
|
||||||
assertEquals("{\"bag\":6,\"value\":10}", gson.toJson(target));
|
assertEquals("{\"bag\":6,\"value\":10}", gson.toJson(target));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testCustomNestedDeserializers() {
|
public void testCustomNestedDeserializers() {
|
||||||
Gson gson = new GsonBuilder().registerTypeAdapter(
|
Gson gson = new GsonBuilder().registerTypeAdapter(
|
||||||
BagOfPrimitives.class, new JsonDeserializer<BagOfPrimitives>() {
|
BagOfPrimitives.class, new JsonDeserializer<BagOfPrimitives>() {
|
||||||
|
@ -130,6 +144,7 @@ public class CustomTypeAdaptersTest extends TestCase {
|
||||||
assertEquals(7, target.getBag().getIntValue());
|
assertEquals(7, target.getBag().getIntValue());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testCustomTypeAdapterDoesNotAppliesToSubClasses() {
|
public void testCustomTypeAdapterDoesNotAppliesToSubClasses() {
|
||||||
Gson gson = new GsonBuilder().registerTypeAdapter(Base.class, new JsonSerializer<Base> () {
|
Gson gson = new GsonBuilder().registerTypeAdapter(Base.class, new JsonSerializer<Base> () {
|
||||||
@Override
|
@Override
|
||||||
|
@ -147,6 +162,7 @@ public class CustomTypeAdaptersTest extends TestCase {
|
||||||
assertTrue(json.contains("derivedValue"));
|
assertTrue(json.contains("derivedValue"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testCustomTypeAdapterAppliesToSubClassesSerializedAsBaseClass() {
|
public void testCustomTypeAdapterAppliesToSubClassesSerializedAsBaseClass() {
|
||||||
Gson gson = new GsonBuilder().registerTypeAdapter(Base.class, new JsonSerializer<Base> () {
|
Gson gson = new GsonBuilder().registerTypeAdapter(Base.class, new JsonSerializer<Base> () {
|
||||||
@Override
|
@Override
|
||||||
|
@ -206,6 +222,7 @@ public class CustomTypeAdaptersTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testCustomSerializerInvokedForPrimitives() {
|
public void testCustomSerializerInvokedForPrimitives() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.registerTypeAdapter(boolean.class, new JsonSerializer<Boolean>() {
|
.registerTypeAdapter(boolean.class, new JsonSerializer<Boolean>() {
|
||||||
|
@ -218,6 +235,7 @@ public class CustomTypeAdaptersTest extends TestCase {
|
||||||
assertEquals("true", gson.toJson(true, Boolean.class));
|
assertEquals("true", gson.toJson(true, Boolean.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testCustomDeserializerInvokedForPrimitives() {
|
public void testCustomDeserializerInvokedForPrimitives() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.registerTypeAdapter(boolean.class, new JsonDeserializer<Boolean>() {
|
.registerTypeAdapter(boolean.class, new JsonDeserializer<Boolean>() {
|
||||||
|
@ -231,6 +249,7 @@ public class CustomTypeAdaptersTest extends TestCase {
|
||||||
assertEquals(Boolean.TRUE, gson.fromJson("true", Boolean.class));
|
assertEquals(Boolean.TRUE, gson.fromJson("true", Boolean.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testCustomByteArraySerializer() {
|
public void testCustomByteArraySerializer() {
|
||||||
Gson gson = new GsonBuilder().registerTypeAdapter(byte[].class, new JsonSerializer<byte[]>() {
|
Gson gson = new GsonBuilder().registerTypeAdapter(byte[].class, new JsonSerializer<byte[]>() {
|
||||||
@Override
|
@Override
|
||||||
|
@ -247,6 +266,7 @@ public class CustomTypeAdaptersTest extends TestCase {
|
||||||
assertEquals("\"0123456789\"", json);
|
assertEquals("\"0123456789\"", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testCustomByteArrayDeserializerAndInstanceCreator() {
|
public void testCustomByteArrayDeserializerAndInstanceCreator() {
|
||||||
GsonBuilder gsonBuilder = new GsonBuilder().registerTypeAdapter(byte[].class,
|
GsonBuilder gsonBuilder = new GsonBuilder().registerTypeAdapter(byte[].class,
|
||||||
new JsonDeserializer<byte[]>() {
|
new JsonDeserializer<byte[]>() {
|
||||||
|
@ -305,6 +325,7 @@ public class CustomTypeAdaptersTest extends TestCase {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Test created from Issue 70
|
// Test created from Issue 70
|
||||||
|
@Test
|
||||||
public void testCustomAdapterInvokedForCollectionElementSerializationWithType() {
|
public void testCustomAdapterInvokedForCollectionElementSerializationWithType() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.registerTypeAdapter(StringHolder.class, new StringHolderTypeAdapter())
|
.registerTypeAdapter(StringHolder.class, new StringHolderTypeAdapter())
|
||||||
|
@ -318,6 +339,7 @@ public class CustomTypeAdaptersTest extends TestCase {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Test created from Issue 70
|
// Test created from Issue 70
|
||||||
|
@Test
|
||||||
public void testCustomAdapterInvokedForCollectionElementSerialization() {
|
public void testCustomAdapterInvokedForCollectionElementSerialization() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.registerTypeAdapter(StringHolder.class, new StringHolderTypeAdapter())
|
.registerTypeAdapter(StringHolder.class, new StringHolderTypeAdapter())
|
||||||
|
@ -330,6 +352,7 @@ public class CustomTypeAdaptersTest extends TestCase {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Test created from Issue 70
|
// Test created from Issue 70
|
||||||
|
@Test
|
||||||
public void testCustomAdapterInvokedForCollectionElementDeserialization() {
|
public void testCustomAdapterInvokedForCollectionElementDeserialization() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.registerTypeAdapter(StringHolder.class, new StringHolderTypeAdapter())
|
.registerTypeAdapter(StringHolder.class, new StringHolderTypeAdapter())
|
||||||
|
@ -343,6 +366,7 @@ public class CustomTypeAdaptersTest extends TestCase {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Test created from Issue 70
|
// Test created from Issue 70
|
||||||
|
@Test
|
||||||
public void testCustomAdapterInvokedForMapElementSerializationWithType() {
|
public void testCustomAdapterInvokedForMapElementSerializationWithType() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.registerTypeAdapter(StringHolder.class, new StringHolderTypeAdapter())
|
.registerTypeAdapter(StringHolder.class, new StringHolderTypeAdapter())
|
||||||
|
@ -356,6 +380,7 @@ public class CustomTypeAdaptersTest extends TestCase {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Test created from Issue 70
|
// Test created from Issue 70
|
||||||
|
@Test
|
||||||
public void testCustomAdapterInvokedForMapElementSerialization() {
|
public void testCustomAdapterInvokedForMapElementSerialization() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.registerTypeAdapter(StringHolder.class, new StringHolderTypeAdapter())
|
.registerTypeAdapter(StringHolder.class, new StringHolderTypeAdapter())
|
||||||
|
@ -368,6 +393,7 @@ public class CustomTypeAdaptersTest extends TestCase {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Test created from Issue 70
|
// Test created from Issue 70
|
||||||
|
@Test
|
||||||
public void testCustomAdapterInvokedForMapElementDeserialization() {
|
public void testCustomAdapterInvokedForMapElementDeserialization() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.registerTypeAdapter(StringHolder.class, new StringHolderTypeAdapter())
|
.registerTypeAdapter(StringHolder.class, new StringHolderTypeAdapter())
|
||||||
|
@ -380,6 +406,7 @@ public class CustomTypeAdaptersTest extends TestCase {
|
||||||
assertEquals("Tomaw", foo.part2);
|
assertEquals("Tomaw", foo.part2);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testEnsureCustomSerializerNotInvokedForNullValues() {
|
public void testEnsureCustomSerializerNotInvokedForNullValues() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.registerTypeAdapter(DataHolder.class, new DataHolderSerializer())
|
.registerTypeAdapter(DataHolder.class, new DataHolderSerializer())
|
||||||
|
@ -389,6 +416,7 @@ public class CustomTypeAdaptersTest extends TestCase {
|
||||||
assertEquals("{\"wrappedData\":{\"myData\":\"abc\"}}", json);
|
assertEquals("{\"wrappedData\":{\"myData\":\"abc\"}}", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testEnsureCustomDeserializerNotInvokedForNullValues() {
|
public void testEnsureCustomDeserializerNotInvokedForNullValues() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.setLenient()
|
.setLenient()
|
||||||
|
@ -400,6 +428,7 @@ public class CustomTypeAdaptersTest extends TestCase {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Test created from Issue 352
|
// Test created from Issue 352
|
||||||
|
@Test
|
||||||
public void testRegisterHierarchyAdapterForDate() {
|
public void testRegisterHierarchyAdapterForDate() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.registerTypeHierarchyAdapter(Date.class, new DateTypeAdapter())
|
.registerTypeHierarchyAdapter(Date.class, new DateTypeAdapter())
|
||||||
|
|
|
@ -15,6 +15,11 @@
|
||||||
*/
|
*/
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertNull;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
import static org.junit.Assert.fail;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.GsonBuilder;
|
import com.google.gson.GsonBuilder;
|
||||||
import com.google.gson.JsonArray;
|
import com.google.gson.JsonArray;
|
||||||
|
@ -54,7 +59,9 @@ import java.util.Set;
|
||||||
import java.util.TimeZone;
|
import java.util.TimeZone;
|
||||||
import java.util.TreeSet;
|
import java.util.TreeSet;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
import junit.framework.TestCase;
|
import org.junit.After;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Functional test for Json serialization and deserialization for common classes for which default
|
* Functional test for Json serialization and deserialization for common classes for which default
|
||||||
|
@ -63,14 +70,13 @@ import junit.framework.TestCase;
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
* @author Joel Leitch
|
* @author Joel Leitch
|
||||||
*/
|
*/
|
||||||
public class DefaultTypeAdaptersTest extends TestCase {
|
public class DefaultTypeAdaptersTest {
|
||||||
private Gson gson;
|
private Gson gson;
|
||||||
private TimeZone oldTimeZone;
|
private TimeZone oldTimeZone;
|
||||||
private Locale oldLocale;
|
private Locale oldLocale;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
this.oldTimeZone = TimeZone.getDefault();
|
this.oldTimeZone = TimeZone.getDefault();
|
||||||
TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles"));
|
TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles"));
|
||||||
this.oldLocale = Locale.getDefault();
|
this.oldLocale = Locale.getDefault();
|
||||||
|
@ -78,13 +84,13 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
gson = new Gson();
|
gson = new Gson();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@After
|
||||||
protected void tearDown() throws Exception {
|
public void tearDown() throws Exception {
|
||||||
TimeZone.setDefault(oldTimeZone);
|
TimeZone.setDefault(oldTimeZone);
|
||||||
Locale.setDefault(oldLocale);
|
Locale.setDefault(oldLocale);
|
||||||
super.tearDown();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testClassSerialization() {
|
public void testClassSerialization() {
|
||||||
try {
|
try {
|
||||||
gson.toJson(String.class);
|
gson.toJson(String.class);
|
||||||
|
@ -96,6 +102,7 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
assertEquals("\"java.lang.String\"", gson.toJson(String.class));
|
assertEquals("\"java.lang.String\"", gson.toJson(String.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testClassDeserialization() {
|
public void testClassDeserialization() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("String.class", String.class.getClass());
|
gson.fromJson("String.class", String.class.getClass());
|
||||||
|
@ -107,12 +114,14 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
assertEquals(String.class, gson.fromJson("java.lang.String", Class.class));
|
assertEquals(String.class, gson.fromJson("java.lang.String", Class.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testUrlSerialization() throws Exception {
|
public void testUrlSerialization() throws Exception {
|
||||||
String urlValue = "http://google.com/";
|
String urlValue = "http://google.com/";
|
||||||
URL url = new URL(urlValue);
|
URL url = new URL(urlValue);
|
||||||
assertEquals("\"http://google.com/\"", gson.toJson(url));
|
assertEquals("\"http://google.com/\"", gson.toJson(url));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testUrlDeserialization() {
|
public void testUrlDeserialization() {
|
||||||
String urlValue = "http://google.com/";
|
String urlValue = "http://google.com/";
|
||||||
String json = "'http:\\/\\/google.com\\/'";
|
String json = "'http:\\/\\/google.com\\/'";
|
||||||
|
@ -123,11 +132,13 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
assertEquals(urlValue, target.toExternalForm());
|
assertEquals(urlValue, target.toExternalForm());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testUrlNullSerialization() throws Exception {
|
public void testUrlNullSerialization() throws Exception {
|
||||||
ClassWithUrlField target = new ClassWithUrlField();
|
ClassWithUrlField target = new ClassWithUrlField();
|
||||||
assertEquals("{}", gson.toJson(target));
|
assertEquals("{}", gson.toJson(target));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testUrlNullDeserialization() {
|
public void testUrlNullDeserialization() {
|
||||||
String json = "{}";
|
String json = "{}";
|
||||||
ClassWithUrlField target = gson.fromJson(json, ClassWithUrlField.class);
|
ClassWithUrlField target = gson.fromJson(json, ClassWithUrlField.class);
|
||||||
|
@ -138,12 +149,14 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
URL url;
|
URL url;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testUriSerialization() throws Exception {
|
public void testUriSerialization() throws Exception {
|
||||||
String uriValue = "http://google.com/";
|
String uriValue = "http://google.com/";
|
||||||
URI uri = new URI(uriValue);
|
URI uri = new URI(uriValue);
|
||||||
assertEquals("\"http://google.com/\"", gson.toJson(uri));
|
assertEquals("\"http://google.com/\"", gson.toJson(uri));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testUriDeserialization() {
|
public void testUriDeserialization() {
|
||||||
String uriValue = "http://google.com/";
|
String uriValue = "http://google.com/";
|
||||||
String json = '"' + uriValue + '"';
|
String json = '"' + uriValue + '"';
|
||||||
|
@ -151,6 +164,7 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
assertEquals(uriValue, target.toASCIIString());
|
assertEquals(uriValue, target.toASCIIString());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNullSerialization() throws Exception {
|
public void testNullSerialization() throws Exception {
|
||||||
testNullSerializationAndDeserialization(Boolean.class);
|
testNullSerializationAndDeserialization(Boolean.class);
|
||||||
testNullSerializationAndDeserialization(Byte.class);
|
testNullSerializationAndDeserialization(Byte.class);
|
||||||
|
@ -191,12 +205,14 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
assertEquals(null, gson.fromJson("null", c));
|
assertEquals(null, gson.fromJson("null", c));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testUuidSerialization() throws Exception {
|
public void testUuidSerialization() throws Exception {
|
||||||
String uuidValue = "c237bec1-19ef-4858-a98e-521cf0aad4c0";
|
String uuidValue = "c237bec1-19ef-4858-a98e-521cf0aad4c0";
|
||||||
UUID uuid = UUID.fromString(uuidValue);
|
UUID uuid = UUID.fromString(uuidValue);
|
||||||
assertEquals('"' + uuidValue + '"', gson.toJson(uuid));
|
assertEquals('"' + uuidValue + '"', gson.toJson(uuid));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testUuidDeserialization() {
|
public void testUuidDeserialization() {
|
||||||
String uuidValue = "c237bec1-19ef-4858-a98e-521cf0aad4c0";
|
String uuidValue = "c237bec1-19ef-4858-a98e-521cf0aad4c0";
|
||||||
String json = '"' + uuidValue + '"';
|
String json = '"' + uuidValue + '"';
|
||||||
|
@ -204,34 +220,40 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
assertEquals(uuidValue, target.toString());
|
assertEquals(uuidValue, target.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testLocaleSerializationWithLanguage() {
|
public void testLocaleSerializationWithLanguage() {
|
||||||
Locale target = new Locale("en");
|
Locale target = new Locale("en");
|
||||||
assertEquals("\"en\"", gson.toJson(target));
|
assertEquals("\"en\"", gson.toJson(target));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testLocaleDeserializationWithLanguage() {
|
public void testLocaleDeserializationWithLanguage() {
|
||||||
String json = "\"en\"";
|
String json = "\"en\"";
|
||||||
Locale locale = gson.fromJson(json, Locale.class);
|
Locale locale = gson.fromJson(json, Locale.class);
|
||||||
assertEquals("en", locale.getLanguage());
|
assertEquals("en", locale.getLanguage());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testLocaleSerializationWithLanguageCountry() {
|
public void testLocaleSerializationWithLanguageCountry() {
|
||||||
Locale target = Locale.CANADA_FRENCH;
|
Locale target = Locale.CANADA_FRENCH;
|
||||||
assertEquals("\"fr_CA\"", gson.toJson(target));
|
assertEquals("\"fr_CA\"", gson.toJson(target));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testLocaleDeserializationWithLanguageCountry() {
|
public void testLocaleDeserializationWithLanguageCountry() {
|
||||||
String json = "\"fr_CA\"";
|
String json = "\"fr_CA\"";
|
||||||
Locale locale = gson.fromJson(json, Locale.class);
|
Locale locale = gson.fromJson(json, Locale.class);
|
||||||
assertEquals(Locale.CANADA_FRENCH, locale);
|
assertEquals(Locale.CANADA_FRENCH, locale);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testLocaleSerializationWithLanguageCountryVariant() {
|
public void testLocaleSerializationWithLanguageCountryVariant() {
|
||||||
Locale target = new Locale("de", "DE", "EURO");
|
Locale target = new Locale("de", "DE", "EURO");
|
||||||
String json = gson.toJson(target);
|
String json = gson.toJson(target);
|
||||||
assertEquals("\"de_DE_EURO\"", json);
|
assertEquals("\"de_DE_EURO\"", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testLocaleDeserializationWithLanguageCountryVariant() {
|
public void testLocaleDeserializationWithLanguageCountryVariant() {
|
||||||
String json = "\"de_DE_EURO\"";
|
String json = "\"de_DE_EURO\"";
|
||||||
Locale locale = gson.fromJson(json, Locale.class);
|
Locale locale = gson.fromJson(json, Locale.class);
|
||||||
|
@ -240,6 +262,7 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
assertEquals("EURO", locale.getVariant());
|
assertEquals("EURO", locale.getVariant());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBigDecimalFieldSerialization() {
|
public void testBigDecimalFieldSerialization() {
|
||||||
ClassWithBigDecimal target = new ClassWithBigDecimal("-122.01e-21");
|
ClassWithBigDecimal target = new ClassWithBigDecimal("-122.01e-21");
|
||||||
String json = gson.toJson(target);
|
String json = gson.toJson(target);
|
||||||
|
@ -247,6 +270,7 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
assertEquals(target.value, new BigDecimal(actual));
|
assertEquals(target.value, new BigDecimal(actual));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBigDecimalFieldDeserialization() {
|
public void testBigDecimalFieldDeserialization() {
|
||||||
ClassWithBigDecimal expected = new ClassWithBigDecimal("-122.01e-21");
|
ClassWithBigDecimal expected = new ClassWithBigDecimal("-122.01e-21");
|
||||||
String json = expected.getExpectedJson();
|
String json = expected.getExpectedJson();
|
||||||
|
@ -254,6 +278,7 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
assertEquals(expected.value, actual.value);
|
assertEquals(expected.value, actual.value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBadValueForBigDecimalDeserialization() {
|
public void testBadValueForBigDecimalDeserialization() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("{\"value\"=1.5e-1.0031}", ClassWithBigDecimal.class);
|
gson.fromJson("{\"value\"=1.5e-1.0031}", ClassWithBigDecimal.class);
|
||||||
|
@ -261,12 +286,14 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
} catch (JsonParseException expected) { }
|
} catch (JsonParseException expected) { }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBigIntegerFieldSerialization() {
|
public void testBigIntegerFieldSerialization() {
|
||||||
ClassWithBigInteger target = new ClassWithBigInteger("23232323215323234234324324324324324324");
|
ClassWithBigInteger target = new ClassWithBigInteger("23232323215323234234324324324324324324");
|
||||||
String json = gson.toJson(target);
|
String json = gson.toJson(target);
|
||||||
assertEquals(target.getExpectedJson(), json);
|
assertEquals(target.getExpectedJson(), json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBigIntegerFieldDeserialization() {
|
public void testBigIntegerFieldDeserialization() {
|
||||||
ClassWithBigInteger expected = new ClassWithBigInteger("879697697697697697697697697697697697");
|
ClassWithBigInteger expected = new ClassWithBigInteger("879697697697697697697697697697697697");
|
||||||
String json = expected.getExpectedJson();
|
String json = expected.getExpectedJson();
|
||||||
|
@ -274,6 +301,7 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
assertEquals(expected.value, actual.value);
|
assertEquals(expected.value, actual.value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testOverrideBigIntegerTypeAdapter() throws Exception {
|
public void testOverrideBigIntegerTypeAdapter() throws Exception {
|
||||||
gson = new GsonBuilder()
|
gson = new GsonBuilder()
|
||||||
.registerTypeAdapter(BigInteger.class, new NumberAsStringAdapter(BigInteger.class))
|
.registerTypeAdapter(BigInteger.class, new NumberAsStringAdapter(BigInteger.class))
|
||||||
|
@ -282,6 +310,7 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
assertEquals(new BigInteger("123"), gson.fromJson("\"123\"", BigInteger.class));
|
assertEquals(new BigInteger("123"), gson.fromJson("\"123\"", BigInteger.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testOverrideBigDecimalTypeAdapter() throws Exception {
|
public void testOverrideBigDecimalTypeAdapter() throws Exception {
|
||||||
gson = new GsonBuilder()
|
gson = new GsonBuilder()
|
||||||
.registerTypeAdapter(BigDecimal.class, new NumberAsStringAdapter(BigDecimal.class))
|
.registerTypeAdapter(BigDecimal.class, new NumberAsStringAdapter(BigDecimal.class))
|
||||||
|
@ -290,6 +319,7 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
assertEquals(new BigDecimal("1.1"), gson.fromJson("\"1.1\"", BigDecimal.class));
|
assertEquals(new BigDecimal("1.1"), gson.fromJson("\"1.1\"", BigDecimal.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSetSerialization() throws Exception {
|
public void testSetSerialization() throws Exception {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
HashSet<String> s = new HashSet<>();
|
HashSet<String> s = new HashSet<>();
|
||||||
|
@ -301,6 +331,7 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
assertEquals("[\"blah\"]", json);
|
assertEquals("[\"blah\"]", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBitSetSerialization() throws Exception {
|
public void testBitSetSerialization() throws Exception {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
BitSet bits = new BitSet();
|
BitSet bits = new BitSet();
|
||||||
|
@ -311,6 +342,7 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
assertEquals("[0,1,0,1,1,1,0,0,0,1]", json);
|
assertEquals("[0,1,0,1,1,1,0,0,0,1]", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBitSetDeserialization() throws Exception {
|
public void testBitSetDeserialization() throws Exception {
|
||||||
BitSet expected = new BitSet();
|
BitSet expected = new BitSet();
|
||||||
expected.set(0);
|
expected.set(0);
|
||||||
|
@ -345,6 +377,7 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDefaultDateSerialization() {
|
public void testDefaultDateSerialization() {
|
||||||
Date now = new Date(1315806903103L);
|
Date now = new Date(1315806903103L);
|
||||||
String json = gson.toJson(now);
|
String json = gson.toJson(now);
|
||||||
|
@ -355,6 +388,7 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDefaultDateDeserialization() {
|
public void testDefaultDateDeserialization() {
|
||||||
String json = "'Dec 13, 2009 07:18:02 AM'";
|
String json = "'Dec 13, 2009 07:18:02 AM'";
|
||||||
Date extracted = gson.fromJson(json, Date.class);
|
Date extracted = gson.fromJson(json, Date.class);
|
||||||
|
@ -378,6 +412,7 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
assertEquals(seconds, date.getSeconds());
|
assertEquals(seconds, date.getSeconds());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDefaultDateSerializationUsingBuilder() throws Exception {
|
public void testDefaultDateSerializationUsingBuilder() throws Exception {
|
||||||
Gson gson = new GsonBuilder().create();
|
Gson gson = new GsonBuilder().create();
|
||||||
Date now = new Date(1315806903103L);
|
Date now = new Date(1315806903103L);
|
||||||
|
@ -389,6 +424,7 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDefaultDateDeserializationUsingBuilder() throws Exception {
|
public void testDefaultDateDeserializationUsingBuilder() throws Exception {
|
||||||
Gson gson = new GsonBuilder().create();
|
Gson gson = new GsonBuilder().create();
|
||||||
Date now = new Date(1315806903103L);
|
Date now = new Date(1315806903103L);
|
||||||
|
@ -397,6 +433,7 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
assertEquals(now.toString(), extracted.toString());
|
assertEquals(now.toString(), extracted.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDefaultCalendarSerialization() throws Exception {
|
public void testDefaultCalendarSerialization() throws Exception {
|
||||||
Gson gson = new GsonBuilder().create();
|
Gson gson = new GsonBuilder().create();
|
||||||
String json = gson.toJson(Calendar.getInstance());
|
String json = gson.toJson(Calendar.getInstance());
|
||||||
|
@ -408,6 +445,7 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
assertTrue(json.contains("second"));
|
assertTrue(json.contains("second"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDefaultCalendarDeserialization() throws Exception {
|
public void testDefaultCalendarDeserialization() throws Exception {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
String json = "{year:2009,month:2,dayOfMonth:11,hourOfDay:14,minute:29,second:23}";
|
String json = "{year:2009,month:2,dayOfMonth:11,hourOfDay:14,minute:29,second:23}";
|
||||||
|
@ -420,6 +458,7 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
assertEquals(23, cal.get(Calendar.SECOND));
|
assertEquals(23, cal.get(Calendar.SECOND));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDefaultGregorianCalendarSerialization() throws Exception {
|
public void testDefaultGregorianCalendarSerialization() throws Exception {
|
||||||
Gson gson = new GsonBuilder().create();
|
Gson gson = new GsonBuilder().create();
|
||||||
GregorianCalendar cal = new GregorianCalendar();
|
GregorianCalendar cal = new GregorianCalendar();
|
||||||
|
@ -432,6 +471,7 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
assertTrue(json.contains("second"));
|
assertTrue(json.contains("second"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDefaultGregorianCalendarDeserialization() throws Exception {
|
public void testDefaultGregorianCalendarDeserialization() throws Exception {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
String json = "{year:2009,month:2,dayOfMonth:11,hourOfDay:14,minute:29,second:23}";
|
String json = "{year:2009,month:2,dayOfMonth:11,hourOfDay:14,minute:29,second:23}";
|
||||||
|
@ -444,6 +484,7 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
assertEquals(23, cal.get(Calendar.SECOND));
|
assertEquals(23, cal.get(Calendar.SECOND));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDateSerializationWithPattern() throws Exception {
|
public void testDateSerializationWithPattern() throws Exception {
|
||||||
String pattern = "yyyy-MM-dd";
|
String pattern = "yyyy-MM-dd";
|
||||||
Gson gson = new GsonBuilder().setDateFormat(DateFormat.FULL).setDateFormat(pattern).create();
|
Gson gson = new GsonBuilder().setDateFormat(DateFormat.FULL).setDateFormat(pattern).create();
|
||||||
|
@ -453,6 +494,7 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings("deprecation")
|
@SuppressWarnings("deprecation")
|
||||||
|
@Test
|
||||||
public void testDateDeserializationWithPattern() throws Exception {
|
public void testDateDeserializationWithPattern() throws Exception {
|
||||||
String pattern = "yyyy-MM-dd";
|
String pattern = "yyyy-MM-dd";
|
||||||
Gson gson = new GsonBuilder().setDateFormat(DateFormat.FULL).setDateFormat(pattern).create();
|
Gson gson = new GsonBuilder().setDateFormat(DateFormat.FULL).setDateFormat(pattern).create();
|
||||||
|
@ -464,6 +506,7 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
assertEquals(now.getDay(), extracted.getDay());
|
assertEquals(now.getDay(), extracted.getDay());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDateSerializationWithPatternNotOverridenByTypeAdapter() throws Exception {
|
public void testDateSerializationWithPatternNotOverridenByTypeAdapter() throws Exception {
|
||||||
String pattern = "yyyy-MM-dd";
|
String pattern = "yyyy-MM-dd";
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
|
@ -483,6 +526,7 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
}
|
}
|
||||||
|
|
||||||
// http://code.google.com/p/google-gson/issues/detail?id=230
|
// http://code.google.com/p/google-gson/issues/detail?id=230
|
||||||
|
@Test
|
||||||
public void testDateSerializationInCollection() throws Exception {
|
public void testDateSerializationInCollection() throws Exception {
|
||||||
Type listOfDates = new TypeToken<List<Date>>() {}.getType();
|
Type listOfDates = new TypeToken<List<Date>>() {}.getType();
|
||||||
TimeZone defaultTimeZone = TimeZone.getDefault();
|
TimeZone defaultTimeZone = TimeZone.getDefault();
|
||||||
|
@ -501,6 +545,7 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testJsonPrimitiveSerialization() {
|
public void testJsonPrimitiveSerialization() {
|
||||||
assertEquals("5", gson.toJson(new JsonPrimitive(5), JsonElement.class));
|
assertEquals("5", gson.toJson(new JsonPrimitive(5), JsonElement.class));
|
||||||
assertEquals("true", gson.toJson(new JsonPrimitive(true), JsonElement.class));
|
assertEquals("true", gson.toJson(new JsonPrimitive(true), JsonElement.class));
|
||||||
|
@ -508,6 +553,7 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
assertEquals("\"a\"", gson.toJson(new JsonPrimitive('a'), JsonElement.class));
|
assertEquals("\"a\"", gson.toJson(new JsonPrimitive('a'), JsonElement.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testJsonPrimitiveDeserialization() {
|
public void testJsonPrimitiveDeserialization() {
|
||||||
assertEquals(new JsonPrimitive(5), gson.fromJson("5", JsonElement.class));
|
assertEquals(new JsonPrimitive(5), gson.fromJson("5", JsonElement.class));
|
||||||
assertEquals(new JsonPrimitive(5), gson.fromJson("5", JsonPrimitive.class));
|
assertEquals(new JsonPrimitive(5), gson.fromJson("5", JsonPrimitive.class));
|
||||||
|
@ -519,16 +565,19 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
assertEquals(new JsonPrimitive('a'), gson.fromJson("\"a\"", JsonPrimitive.class));
|
assertEquals(new JsonPrimitive('a'), gson.fromJson("\"a\"", JsonPrimitive.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testJsonNullSerialization() {
|
public void testJsonNullSerialization() {
|
||||||
assertEquals("null", gson.toJson(JsonNull.INSTANCE, JsonElement.class));
|
assertEquals("null", gson.toJson(JsonNull.INSTANCE, JsonElement.class));
|
||||||
assertEquals("null", gson.toJson(JsonNull.INSTANCE, JsonNull.class));
|
assertEquals("null", gson.toJson(JsonNull.INSTANCE, JsonNull.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNullJsonElementSerialization() {
|
public void testNullJsonElementSerialization() {
|
||||||
assertEquals("null", gson.toJson(null, JsonElement.class));
|
assertEquals("null", gson.toJson(null, JsonElement.class));
|
||||||
assertEquals("null", gson.toJson(null, JsonNull.class));
|
assertEquals("null", gson.toJson(null, JsonNull.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testJsonArraySerialization() {
|
public void testJsonArraySerialization() {
|
||||||
JsonArray array = new JsonArray();
|
JsonArray array = new JsonArray();
|
||||||
array.add(new JsonPrimitive(1));
|
array.add(new JsonPrimitive(1));
|
||||||
|
@ -537,6 +586,7 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
assertEquals("[1,2,3]", gson.toJson(array, JsonElement.class));
|
assertEquals("[1,2,3]", gson.toJson(array, JsonElement.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testJsonArrayDeserialization() {
|
public void testJsonArrayDeserialization() {
|
||||||
JsonArray array = new JsonArray();
|
JsonArray array = new JsonArray();
|
||||||
array.add(new JsonPrimitive(1));
|
array.add(new JsonPrimitive(1));
|
||||||
|
@ -548,6 +598,7 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
assertEquals(array, gson.fromJson(json, JsonArray.class));
|
assertEquals(array, gson.fromJson(json, JsonArray.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testJsonObjectSerialization() {
|
public void testJsonObjectSerialization() {
|
||||||
JsonObject object = new JsonObject();
|
JsonObject object = new JsonObject();
|
||||||
object.add("foo", new JsonPrimitive(1));
|
object.add("foo", new JsonPrimitive(1));
|
||||||
|
@ -555,6 +606,7 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
assertEquals("{\"foo\":1,\"bar\":2}", gson.toJson(object, JsonElement.class));
|
assertEquals("{\"foo\":1,\"bar\":2}", gson.toJson(object, JsonElement.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testJsonObjectDeserialization() {
|
public void testJsonObjectDeserialization() {
|
||||||
JsonObject object = new JsonObject();
|
JsonObject object = new JsonObject();
|
||||||
object.add("foo", new JsonPrimitive(1));
|
object.add("foo", new JsonPrimitive(1));
|
||||||
|
@ -568,11 +620,13 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
assertEquals(object, actualObj);
|
assertEquals(object, actualObj);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testJsonNullDeserialization() {
|
public void testJsonNullDeserialization() {
|
||||||
assertEquals(JsonNull.INSTANCE, gson.fromJson("null", JsonElement.class));
|
assertEquals(JsonNull.INSTANCE, gson.fromJson("null", JsonElement.class));
|
||||||
assertEquals(JsonNull.INSTANCE, gson.fromJson("null", JsonNull.class));
|
assertEquals(JsonNull.INSTANCE, gson.fromJson("null", JsonNull.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testJsonElementTypeMismatch() {
|
public void testJsonElementTypeMismatch() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("\"abc\"", JsonObject.class);
|
gson.fromJson("\"abc\"", JsonObject.class);
|
||||||
|
@ -603,6 +657,7 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testPropertiesSerialization() {
|
public void testPropertiesSerialization() {
|
||||||
Properties props = new Properties();
|
Properties props = new Properties();
|
||||||
props.setProperty("foo", "bar");
|
props.setProperty("foo", "bar");
|
||||||
|
@ -611,12 +666,14 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
assertEquals(expected, json);
|
assertEquals(expected, json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testPropertiesDeserialization() {
|
public void testPropertiesDeserialization() {
|
||||||
String json = "{foo:'bar'}";
|
String json = "{foo:'bar'}";
|
||||||
Properties props = gson.fromJson(json, Properties.class);
|
Properties props = gson.fromJson(json, Properties.class);
|
||||||
assertEquals("bar", props.getProperty("foo"));
|
assertEquals("bar", props.getProperty("foo"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testTreeSetSerialization() {
|
public void testTreeSetSerialization() {
|
||||||
TreeSet<String> treeSet = new TreeSet<>();
|
TreeSet<String> treeSet = new TreeSet<>();
|
||||||
treeSet.add("Value1");
|
treeSet.add("Value1");
|
||||||
|
@ -624,6 +681,7 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
assertEquals("[\"Value1\"]", json);
|
assertEquals("[\"Value1\"]", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testTreeSetDeserialization() {
|
public void testTreeSetDeserialization() {
|
||||||
String json = "['Value1']";
|
String json = "['Value1']";
|
||||||
Type type = new TypeToken<TreeSet<String>>() {}.getType();
|
Type type = new TypeToken<TreeSet<String>>() {}.getType();
|
||||||
|
@ -631,23 +689,27 @@ public class DefaultTypeAdaptersTest extends TestCase {
|
||||||
assertTrue(treeSet.contains("Value1"));
|
assertTrue(treeSet.contains("Value1"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testStringBuilderSerialization() {
|
public void testStringBuilderSerialization() {
|
||||||
StringBuilder sb = new StringBuilder("abc");
|
StringBuilder sb = new StringBuilder("abc");
|
||||||
String json = gson.toJson(sb);
|
String json = gson.toJson(sb);
|
||||||
assertEquals("\"abc\"", json);
|
assertEquals("\"abc\"", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testStringBuilderDeserialization() {
|
public void testStringBuilderDeserialization() {
|
||||||
StringBuilder sb = gson.fromJson("'abc'", StringBuilder.class);
|
StringBuilder sb = gson.fromJson("'abc'", StringBuilder.class);
|
||||||
assertEquals("abc", sb.toString());
|
assertEquals("abc", sb.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testStringBufferSerialization() {
|
public void testStringBufferSerialization() {
|
||||||
StringBuffer sb = new StringBuffer("abc");
|
StringBuffer sb = new StringBuffer("abc");
|
||||||
String json = gson.toJson(sb);
|
String json = gson.toJson(sb);
|
||||||
assertEquals("\"abc\"", json);
|
assertEquals("\"abc\"", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testStringBufferDeserialization() {
|
public void testStringBufferDeserialization() {
|
||||||
StringBuffer sb = gson.fromJson("'abc'", StringBuffer.class);
|
StringBuffer sb = gson.fromJson("'abc'", StringBuffer.class);
|
||||||
assertEquals("abc", sb.toString());
|
assertEquals("abc", sb.toString());
|
||||||
|
|
|
@ -15,11 +15,7 @@
|
||||||
*/
|
*/
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
import java.io.IOException;
|
import static org.junit.Assert.assertEquals;
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import junit.framework.TestCase;
|
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.GsonBuilder;
|
import com.google.gson.GsonBuilder;
|
||||||
|
@ -29,26 +25,31 @@ import com.google.gson.common.TestTypes.BagOfPrimitives;
|
||||||
import com.google.gson.reflect.TypeToken;
|
import com.google.gson.reflect.TypeToken;
|
||||||
import com.google.gson.stream.JsonReader;
|
import com.google.gson.stream.JsonReader;
|
||||||
import com.google.gson.stream.JsonWriter;
|
import com.google.gson.stream.JsonWriter;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Functional tests for {@link Gson#getDelegateAdapter(TypeAdapterFactory, TypeToken)} method.
|
* Functional tests for {@link Gson#getDelegateAdapter(TypeAdapterFactory, TypeToken)} method.
|
||||||
*
|
*
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
*/
|
*/
|
||||||
public class DelegateTypeAdapterTest extends TestCase {
|
public class DelegateTypeAdapterTest {
|
||||||
|
|
||||||
private StatsTypeAdapterFactory stats;
|
private StatsTypeAdapterFactory stats;
|
||||||
private Gson gson;
|
private Gson gson;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
stats = new StatsTypeAdapterFactory();
|
stats = new StatsTypeAdapterFactory();
|
||||||
gson = new GsonBuilder()
|
gson = new GsonBuilder()
|
||||||
.registerTypeAdapterFactory(stats)
|
.registerTypeAdapterFactory(stats)
|
||||||
.create();
|
.create();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDelegateInvoked() {
|
public void testDelegateInvoked() {
|
||||||
List<BagOfPrimitives> bags = new ArrayList<>();
|
List<BagOfPrimitives> bags = new ArrayList<>();
|
||||||
for (int i = 0; i < 10; ++i) {
|
for (int i = 0; i < 10; ++i) {
|
||||||
|
@ -61,6 +62,7 @@ public class DelegateTypeAdapterTest extends TestCase {
|
||||||
assertEquals(51, stats.numWrites);
|
assertEquals(51, stats.numWrites);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDelegateInvokedOnStrings() {
|
public void testDelegateInvokedOnStrings() {
|
||||||
String[] bags = {"1", "2", "3", "4"};
|
String[] bags = {"1", "2", "3", "4"};
|
||||||
String json = gson.toJson(bags);
|
String json = gson.toJson(bags);
|
||||||
|
|
|
@ -16,6 +16,11 @@
|
||||||
|
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertNull;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.GsonBuilder;
|
import com.google.gson.GsonBuilder;
|
||||||
import com.google.gson.JsonDeserializationContext;
|
import com.google.gson.JsonDeserializationContext;
|
||||||
|
@ -36,7 +41,8 @@ import java.util.EnumMap;
|
||||||
import java.util.EnumSet;
|
import java.util.EnumSet;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import junit.framework.TestCase;
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Functional tests for Java 5.0 enums.
|
* Functional tests for Java 5.0 enums.
|
||||||
|
@ -44,26 +50,28 @@ import junit.framework.TestCase;
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
* @author Joel Leitch
|
* @author Joel Leitch
|
||||||
*/
|
*/
|
||||||
public class EnumTest extends TestCase {
|
public class EnumTest {
|
||||||
|
|
||||||
private Gson gson;
|
private Gson gson;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
gson = new Gson();
|
gson = new Gson();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testTopLevelEnumSerialization() throws Exception {
|
public void testTopLevelEnumSerialization() throws Exception {
|
||||||
String result = gson.toJson(MyEnum.VALUE1);
|
String result = gson.toJson(MyEnum.VALUE1);
|
||||||
assertEquals('"' + MyEnum.VALUE1.toString() + '"', result);
|
assertEquals('"' + MyEnum.VALUE1.toString() + '"', result);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testTopLevelEnumDeserialization() throws Exception {
|
public void testTopLevelEnumDeserialization() throws Exception {
|
||||||
MyEnum result = gson.fromJson('"' + MyEnum.VALUE1.toString() + '"', MyEnum.class);
|
MyEnum result = gson.fromJson('"' + MyEnum.VALUE1.toString() + '"', MyEnum.class);
|
||||||
assertEquals(MyEnum.VALUE1, result);
|
assertEquals(MyEnum.VALUE1, result);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testCollectionOfEnumsSerialization() {
|
public void testCollectionOfEnumsSerialization() {
|
||||||
Type type = new TypeToken<Collection<MyEnum>>() {}.getType();
|
Type type = new TypeToken<Collection<MyEnum>>() {}.getType();
|
||||||
Collection<MyEnum> target = new ArrayList<>();
|
Collection<MyEnum> target = new ArrayList<>();
|
||||||
|
@ -76,6 +84,7 @@ public class EnumTest extends TestCase {
|
||||||
assertEquals(expectedJson, actualJson);
|
assertEquals(expectedJson, actualJson);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testCollectionOfEnumsDeserialization() {
|
public void testCollectionOfEnumsDeserialization() {
|
||||||
Type type = new TypeToken<Collection<MyEnum>>() {}.getType();
|
Type type = new TypeToken<Collection<MyEnum>>() {}.getType();
|
||||||
String json = "[\"VALUE1\",\"VALUE2\"]";
|
String json = "[\"VALUE1\",\"VALUE2\"]";
|
||||||
|
@ -84,11 +93,13 @@ public class EnumTest extends TestCase {
|
||||||
MoreAsserts.assertContains(target, MyEnum.VALUE2);
|
MoreAsserts.assertContains(target, MyEnum.VALUE2);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testClassWithEnumFieldSerialization() throws Exception {
|
public void testClassWithEnumFieldSerialization() throws Exception {
|
||||||
ClassWithEnumFields target = new ClassWithEnumFields();
|
ClassWithEnumFields target = new ClassWithEnumFields();
|
||||||
assertEquals(target.getExpectedJson(), gson.toJson(target));
|
assertEquals(target.getExpectedJson(), gson.toJson(target));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testClassWithEnumFieldDeserialization() throws Exception {
|
public void testClassWithEnumFieldDeserialization() throws Exception {
|
||||||
String json = "{value1:'VALUE1',value2:'VALUE2'}";
|
String json = "{value1:'VALUE1',value2:'VALUE2'}";
|
||||||
ClassWithEnumFields target = gson.fromJson(json, ClassWithEnumFields.class);
|
ClassWithEnumFields target = gson.fromJson(json, ClassWithEnumFields.class);
|
||||||
|
@ -111,6 +122,7 @@ public class EnumTest extends TestCase {
|
||||||
/**
|
/**
|
||||||
* Test for issue 226.
|
* Test for issue 226.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testEnumSubclass() {
|
public void testEnumSubclass() {
|
||||||
assertFalse(Roshambo.class == Roshambo.ROCK.getClass());
|
assertFalse(Roshambo.class == Roshambo.ROCK.getClass());
|
||||||
assertEquals("\"ROCK\"", gson.toJson(Roshambo.ROCK));
|
assertEquals("\"ROCK\"", gson.toJson(Roshambo.ROCK));
|
||||||
|
@ -120,6 +132,7 @@ public class EnumTest extends TestCase {
|
||||||
gson.fromJson("[\"ROCK\",\"PAPER\",\"SCISSORS\"]", new TypeToken<Set<Roshambo>>() {}.getType()));
|
gson.fromJson("[\"ROCK\",\"PAPER\",\"SCISSORS\"]", new TypeToken<Set<Roshambo>>() {}.getType()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testEnumSubclassWithRegisteredTypeAdapter() {
|
public void testEnumSubclassWithRegisteredTypeAdapter() {
|
||||||
gson = new GsonBuilder()
|
gson = new GsonBuilder()
|
||||||
.registerTypeHierarchyAdapter(Roshambo.class, new MyEnumTypeAdapter())
|
.registerTypeHierarchyAdapter(Roshambo.class, new MyEnumTypeAdapter())
|
||||||
|
@ -132,6 +145,7 @@ public class EnumTest extends TestCase {
|
||||||
gson.fromJson("[\"123ROCK\",\"123PAPER\",\"123SCISSORS\"]", new TypeToken<Set<Roshambo>>() {}.getType()));
|
gson.fromJson("[\"123ROCK\",\"123PAPER\",\"123SCISSORS\"]", new TypeToken<Set<Roshambo>>() {}.getType()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testEnumSubclassAsParameterizedType() {
|
public void testEnumSubclassAsParameterizedType() {
|
||||||
Collection<Roshambo> list = new ArrayList<>();
|
Collection<Roshambo> list = new ArrayList<>();
|
||||||
list.add(Roshambo.ROCK);
|
list.add(Roshambo.ROCK);
|
||||||
|
@ -146,11 +160,13 @@ public class EnumTest extends TestCase {
|
||||||
MoreAsserts.assertContains(actualJsonList, Roshambo.PAPER);
|
MoreAsserts.assertContains(actualJsonList, Roshambo.PAPER);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testEnumCaseMapping() {
|
public void testEnumCaseMapping() {
|
||||||
assertEquals(Gender.MALE, gson.fromJson("\"boy\"", Gender.class));
|
assertEquals(Gender.MALE, gson.fromJson("\"boy\"", Gender.class));
|
||||||
assertEquals("\"boy\"", gson.toJson(Gender.MALE, Gender.class));
|
assertEquals("\"boy\"", gson.toJson(Gender.MALE, Gender.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testEnumSet() {
|
public void testEnumSet() {
|
||||||
EnumSet<Roshambo> foo = EnumSet.of(Roshambo.ROCK, Roshambo.PAPER);
|
EnumSet<Roshambo> foo = EnumSet.of(Roshambo.ROCK, Roshambo.PAPER);
|
||||||
String json = gson.toJson(foo);
|
String json = gson.toJson(foo);
|
||||||
|
@ -163,6 +179,7 @@ public class EnumTest extends TestCase {
|
||||||
assertFalse(bar.contains(Roshambo.SCISSORS));
|
assertFalse(bar.contains(Roshambo.SCISSORS));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testEnumMap() throws Exception {
|
public void testEnumMap() throws Exception {
|
||||||
EnumMap<MyEnum, String> map = new EnumMap<>(MyEnum.class);
|
EnumMap<MyEnum, String> map = new EnumMap<>(MyEnum.class);
|
||||||
map.put(MyEnum.VALUE1, "test");
|
map.put(MyEnum.VALUE1, "test");
|
||||||
|
@ -215,6 +232,7 @@ public class EnumTest extends TestCase {
|
||||||
FEMALE
|
FEMALE
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testEnumClassWithFields() {
|
public void testEnumClassWithFields() {
|
||||||
assertEquals("\"RED\"", gson.toJson(Color.RED));
|
assertEquals("\"RED\"", gson.toJson(Color.RED));
|
||||||
assertEquals("red", gson.fromJson("RED", Color.class).value);
|
assertEquals("red", gson.fromJson("RED", Color.class).value);
|
||||||
|
@ -231,6 +249,7 @@ public class EnumTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testEnumToStringRead() {
|
public void testEnumToStringRead() {
|
||||||
// Should still be able to read constant name
|
// Should still be able to read constant name
|
||||||
assertEquals(CustomToString.A, gson.fromJson("\"A\"", CustomToString.class));
|
assertEquals(CustomToString.A, gson.fromJson("\"A\"", CustomToString.class));
|
||||||
|
@ -253,6 +272,7 @@ public class EnumTest extends TestCase {
|
||||||
* Test that enum constant names have higher precedence than {@code toString()}
|
* Test that enum constant names have higher precedence than {@code toString()}
|
||||||
* result.
|
* result.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testEnumToStringReadInterchanged() {
|
public void testEnumToStringReadInterchanged() {
|
||||||
assertEquals(InterchangedToString.A, gson.fromJson("\"A\"", InterchangedToString.class));
|
assertEquals(InterchangedToString.A, gson.fromJson("\"A\"", InterchangedToString.class));
|
||||||
assertEquals(InterchangedToString.B, gson.fromJson("\"B\"", InterchangedToString.class));
|
assertEquals(InterchangedToString.B, gson.fromJson("\"B\"", InterchangedToString.class));
|
||||||
|
|
|
@ -16,12 +16,17 @@
|
||||||
|
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.GsonBuilder;
|
import com.google.gson.GsonBuilder;
|
||||||
import com.google.gson.common.TestTypes.BagOfPrimitives;
|
import com.google.gson.common.TestTypes.BagOfPrimitives;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import junit.framework.TestCase;
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Performs some functional test involving JSON output escaping.
|
* Performs some functional test involving JSON output escaping.
|
||||||
|
@ -29,15 +34,15 @@ import junit.framework.TestCase;
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
* @author Joel Leitch
|
* @author Joel Leitch
|
||||||
*/
|
*/
|
||||||
public class EscapingTest extends TestCase {
|
public class EscapingTest {
|
||||||
private Gson gson;
|
private Gson gson;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
gson = new Gson();
|
gson = new Gson();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testEscapingQuotesInStringArray() throws Exception {
|
public void testEscapingQuotesInStringArray() throws Exception {
|
||||||
String[] valueWithQuotes = { "beforeQuote\"afterQuote" };
|
String[] valueWithQuotes = { "beforeQuote\"afterQuote" };
|
||||||
String jsonRepresentation = gson.toJson(valueWithQuotes);
|
String jsonRepresentation = gson.toJson(valueWithQuotes);
|
||||||
|
@ -46,6 +51,7 @@ public class EscapingTest extends TestCase {
|
||||||
assertEquals(valueWithQuotes[0], target[0]);
|
assertEquals(valueWithQuotes[0], target[0]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testEscapeAllHtmlCharacters() {
|
public void testEscapeAllHtmlCharacters() {
|
||||||
List<String> strings = new ArrayList<>();
|
List<String> strings = new ArrayList<>();
|
||||||
strings.add("<");
|
strings.add("<");
|
||||||
|
@ -58,6 +64,7 @@ public class EscapingTest extends TestCase {
|
||||||
gson.toJson(strings));
|
gson.toJson(strings));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testEscapingObjectFields() throws Exception {
|
public void testEscapingObjectFields() throws Exception {
|
||||||
BagOfPrimitives objWithPrimitives = new BagOfPrimitives(1L, 1, true, "test with\" <script>");
|
BagOfPrimitives objWithPrimitives = new BagOfPrimitives(1L, 1, true, "test with\" <script>");
|
||||||
String jsonRepresentation = gson.toJson(objWithPrimitives);
|
String jsonRepresentation = gson.toJson(objWithPrimitives);
|
||||||
|
@ -69,6 +76,7 @@ public class EscapingTest extends TestCase {
|
||||||
assertEquals(objWithPrimitives.getExpectedJson(), expectedObject.getExpectedJson());
|
assertEquals(objWithPrimitives.getExpectedJson(), expectedObject.getExpectedJson());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testGsonAcceptsEscapedAndNonEscapedJsonDeserialization() throws Exception {
|
public void testGsonAcceptsEscapedAndNonEscapedJsonDeserialization() throws Exception {
|
||||||
Gson escapeHtmlGson = new GsonBuilder().create();
|
Gson escapeHtmlGson = new GsonBuilder().create();
|
||||||
Gson noEscapeHtmlGson = new GsonBuilder().disableHtmlEscaping().create();
|
Gson noEscapeHtmlGson = new GsonBuilder().disableHtmlEscaping().create();
|
||||||
|
@ -82,6 +90,7 @@ public class EscapingTest extends TestCase {
|
||||||
assertEquals(target, escapeHtmlGson.fromJson(nonEscapedJsonForm, BagOfPrimitives.class));
|
assertEquals(target, escapeHtmlGson.fromJson(nonEscapedJsonForm, BagOfPrimitives.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testGsonDoubleDeserialization() {
|
public void testGsonDoubleDeserialization() {
|
||||||
BagOfPrimitives expected = new BagOfPrimitives(3L, 4, true, "value1");
|
BagOfPrimitives expected = new BagOfPrimitives(3L, 4, true, "value1");
|
||||||
String json = gson.toJson(gson.toJson(expected));
|
String json = gson.toJson(gson.toJson(expected));
|
||||||
|
|
|
@ -16,6 +16,11 @@
|
||||||
|
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertNull;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
import com.google.gson.ExclusionStrategy;
|
import com.google.gson.ExclusionStrategy;
|
||||||
import com.google.gson.FieldAttributes;
|
import com.google.gson.FieldAttributes;
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
|
@ -26,7 +31,8 @@ import java.lang.annotation.ElementType;
|
||||||
import java.lang.annotation.Retention;
|
import java.lang.annotation.Retention;
|
||||||
import java.lang.annotation.RetentionPolicy;
|
import java.lang.annotation.RetentionPolicy;
|
||||||
import java.lang.annotation.Target;
|
import java.lang.annotation.Target;
|
||||||
import junit.framework.TestCase;
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Performs some functional tests when Gson is instantiated with some common user defined
|
* Performs some functional tests when Gson is instantiated with some common user defined
|
||||||
|
@ -35,7 +41,7 @@ import junit.framework.TestCase;
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
* @author Joel Leitch
|
* @author Joel Leitch
|
||||||
*/
|
*/
|
||||||
public class ExclusionStrategyFunctionalTest extends TestCase {
|
public class ExclusionStrategyFunctionalTest {
|
||||||
private static final ExclusionStrategy EXCLUDE_SAMPLE_OBJECT_FOR_TEST = new ExclusionStrategy() {
|
private static final ExclusionStrategy EXCLUDE_SAMPLE_OBJECT_FOR_TEST = new ExclusionStrategy() {
|
||||||
@Override public boolean shouldSkipField(FieldAttributes f) {
|
@Override public boolean shouldSkipField(FieldAttributes f) {
|
||||||
return false;
|
return false;
|
||||||
|
@ -47,12 +53,12 @@ public class ExclusionStrategyFunctionalTest extends TestCase {
|
||||||
|
|
||||||
private SampleObjectForTest src;
|
private SampleObjectForTest src;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
src = new SampleObjectForTest();
|
src = new SampleObjectForTest();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testExclusionStrategySerialization() throws Exception {
|
public void testExclusionStrategySerialization() throws Exception {
|
||||||
Gson gson = createGson(new MyExclusionStrategy(String.class), true);
|
Gson gson = createGson(new MyExclusionStrategy(String.class), true);
|
||||||
String json = gson.toJson(src);
|
String json = gson.toJson(src);
|
||||||
|
@ -61,6 +67,7 @@ public class ExclusionStrategyFunctionalTest extends TestCase {
|
||||||
assertTrue(json.contains("\"longField\""));
|
assertTrue(json.contains("\"longField\""));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testExclusionStrategySerializationDoesNotImpactDeserialization() {
|
public void testExclusionStrategySerializationDoesNotImpactDeserialization() {
|
||||||
String json = "{\"annotatedField\":1,\"stringField\":\"x\",\"longField\":2}";
|
String json = "{\"annotatedField\":1,\"stringField\":\"x\",\"longField\":2}";
|
||||||
Gson gson = createGson(new MyExclusionStrategy(String.class), true);
|
Gson gson = createGson(new MyExclusionStrategy(String.class), true);
|
||||||
|
@ -70,6 +77,7 @@ public class ExclusionStrategyFunctionalTest extends TestCase {
|
||||||
assertEquals(2, value.longField);
|
assertEquals(2, value.longField);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testExclusionStrategyDeserialization() throws Exception {
|
public void testExclusionStrategyDeserialization() throws Exception {
|
||||||
Gson gson = createGson(new MyExclusionStrategy(String.class), false);
|
Gson gson = createGson(new MyExclusionStrategy(String.class), false);
|
||||||
JsonObject json = new JsonObject();
|
JsonObject json = new JsonObject();
|
||||||
|
@ -85,6 +93,7 @@ public class ExclusionStrategyFunctionalTest extends TestCase {
|
||||||
assertEquals(src.stringField, target.stringField);
|
assertEquals(src.stringField, target.stringField);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testExclusionStrategySerializationDoesNotImpactSerialization() throws Exception {
|
public void testExclusionStrategySerializationDoesNotImpactSerialization() throws Exception {
|
||||||
Gson gson = createGson(new MyExclusionStrategy(String.class), false);
|
Gson gson = createGson(new MyExclusionStrategy(String.class), false);
|
||||||
String json = gson.toJson(src);
|
String json = gson.toJson(src);
|
||||||
|
@ -93,6 +102,7 @@ public class ExclusionStrategyFunctionalTest extends TestCase {
|
||||||
assertTrue(json.contains("\"longField\""));
|
assertTrue(json.contains("\"longField\""));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testExclusionStrategyWithMode() throws Exception {
|
public void testExclusionStrategyWithMode() throws Exception {
|
||||||
SampleObjectForTest testObj = new SampleObjectForTest(
|
SampleObjectForTest testObj = new SampleObjectForTest(
|
||||||
src.annotatedField + 5, src.stringField + "blah,blah",
|
src.annotatedField + 5, src.stringField + "blah,blah",
|
||||||
|
@ -112,6 +122,7 @@ public class ExclusionStrategyFunctionalTest extends TestCase {
|
||||||
assertEquals(src.stringField, target.stringField);
|
assertEquals(src.stringField, target.stringField);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testExcludeTopLevelClassSerialization() {
|
public void testExcludeTopLevelClassSerialization() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.addSerializationExclusionStrategy(EXCLUDE_SAMPLE_OBJECT_FOR_TEST)
|
.addSerializationExclusionStrategy(EXCLUDE_SAMPLE_OBJECT_FOR_TEST)
|
||||||
|
@ -119,6 +130,7 @@ public class ExclusionStrategyFunctionalTest extends TestCase {
|
||||||
assertEquals("null", gson.toJson(new SampleObjectForTest(), SampleObjectForTest.class));
|
assertEquals("null", gson.toJson(new SampleObjectForTest(), SampleObjectForTest.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testExcludeTopLevelClassSerializationDoesNotImpactDeserialization() {
|
public void testExcludeTopLevelClassSerializationDoesNotImpactDeserialization() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.addSerializationExclusionStrategy(EXCLUDE_SAMPLE_OBJECT_FOR_TEST)
|
.addSerializationExclusionStrategy(EXCLUDE_SAMPLE_OBJECT_FOR_TEST)
|
||||||
|
@ -130,6 +142,7 @@ public class ExclusionStrategyFunctionalTest extends TestCase {
|
||||||
assertEquals(2, value.longField);
|
assertEquals(2, value.longField);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testExcludeTopLevelClassDeserialization() {
|
public void testExcludeTopLevelClassDeserialization() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.addDeserializationExclusionStrategy(EXCLUDE_SAMPLE_OBJECT_FOR_TEST)
|
.addDeserializationExclusionStrategy(EXCLUDE_SAMPLE_OBJECT_FOR_TEST)
|
||||||
|
@ -139,6 +152,7 @@ public class ExclusionStrategyFunctionalTest extends TestCase {
|
||||||
assertNull(value);
|
assertNull(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testExcludeTopLevelClassDeserializationDoesNotImpactSerialization() {
|
public void testExcludeTopLevelClassDeserializationDoesNotImpactSerialization() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.addDeserializationExclusionStrategy(EXCLUDE_SAMPLE_OBJECT_FOR_TEST)
|
.addDeserializationExclusionStrategy(EXCLUDE_SAMPLE_OBJECT_FOR_TEST)
|
||||||
|
|
|
@ -16,27 +16,30 @@
|
||||||
|
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
import java.lang.reflect.Type;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertNotNull;
|
||||||
|
import static org.junit.Assert.assertNull;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.GsonBuilder;
|
import com.google.gson.GsonBuilder;
|
||||||
import com.google.gson.InstanceCreator;
|
import com.google.gson.InstanceCreator;
|
||||||
import com.google.gson.annotations.Expose;
|
import com.google.gson.annotations.Expose;
|
||||||
|
import java.lang.reflect.Type;
|
||||||
import junit.framework.TestCase;
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Unit tests for the regarding functional "@Expose" type tests.
|
* Unit tests for the regarding functional "@Expose" type tests.
|
||||||
*
|
*
|
||||||
* @author Joel Leitch
|
* @author Joel Leitch
|
||||||
*/
|
*/
|
||||||
public class ExposeFieldsTest extends TestCase {
|
public class ExposeFieldsTest {
|
||||||
|
|
||||||
private Gson gson;
|
private Gson gson;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
gson = new GsonBuilder()
|
gson = new GsonBuilder()
|
||||||
.setLenient()
|
.setLenient()
|
||||||
.excludeFieldsWithoutExposeAnnotation()
|
.excludeFieldsWithoutExposeAnnotation()
|
||||||
|
@ -44,6 +47,7 @@ public class ExposeFieldsTest extends TestCase {
|
||||||
.create();
|
.create();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNullExposeFieldSerialization() throws Exception {
|
public void testNullExposeFieldSerialization() throws Exception {
|
||||||
ClassWithExposedFields object = new ClassWithExposedFields(null, 1);
|
ClassWithExposedFields object = new ClassWithExposedFields(null, 1);
|
||||||
String json = gson.toJson(object);
|
String json = gson.toJson(object);
|
||||||
|
@ -51,6 +55,7 @@ public class ExposeFieldsTest extends TestCase {
|
||||||
assertEquals(object.getExpectedJson(), json);
|
assertEquals(object.getExpectedJson(), json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testArrayWithOneNullExposeFieldObjectSerialization() throws Exception {
|
public void testArrayWithOneNullExposeFieldObjectSerialization() throws Exception {
|
||||||
ClassWithExposedFields object1 = new ClassWithExposedFields(1, 1);
|
ClassWithExposedFields object1 = new ClassWithExposedFields(1, 1);
|
||||||
ClassWithExposedFields object2 = new ClassWithExposedFields(null, 1);
|
ClassWithExposedFields object2 = new ClassWithExposedFields(null, 1);
|
||||||
|
@ -67,11 +72,13 @@ public class ExposeFieldsTest extends TestCase {
|
||||||
assertEquals(expected, json);
|
assertEquals(expected, json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testExposeAnnotationSerialization() throws Exception {
|
public void testExposeAnnotationSerialization() throws Exception {
|
||||||
ClassWithExposedFields target = new ClassWithExposedFields(1, 2);
|
ClassWithExposedFields target = new ClassWithExposedFields(1, 2);
|
||||||
assertEquals(target.getExpectedJson(), gson.toJson(target));
|
assertEquals(target.getExpectedJson(), gson.toJson(target));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testExposeAnnotationDeserialization() throws Exception {
|
public void testExposeAnnotationDeserialization() throws Exception {
|
||||||
String json = "{a:3,b:4,d:20.0}";
|
String json = "{a:3,b:4,d:20.0}";
|
||||||
ClassWithExposedFields target = gson.fromJson(json, ClassWithExposedFields.class);
|
ClassWithExposedFields target = gson.fromJson(json, ClassWithExposedFields.class);
|
||||||
|
@ -81,6 +88,7 @@ public class ExposeFieldsTest extends TestCase {
|
||||||
assertFalse(target.d == 20);
|
assertFalse(target.d == 20);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNoExposedFieldSerialization() throws Exception {
|
public void testNoExposedFieldSerialization() throws Exception {
|
||||||
ClassWithNoExposedFields obj = new ClassWithNoExposedFields();
|
ClassWithNoExposedFields obj = new ClassWithNoExposedFields();
|
||||||
String json = gson.toJson(obj);
|
String json = gson.toJson(obj);
|
||||||
|
@ -88,6 +96,7 @@ public class ExposeFieldsTest extends TestCase {
|
||||||
assertEquals("{}", json);
|
assertEquals("{}", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNoExposedFieldDeserialization() throws Exception {
|
public void testNoExposedFieldDeserialization() throws Exception {
|
||||||
String json = "{a:4,b:5}";
|
String json = "{a:4,b:5}";
|
||||||
ClassWithNoExposedFields obj = gson.fromJson(json, ClassWithNoExposedFields.class);
|
ClassWithNoExposedFields obj = gson.fromJson(json, ClassWithNoExposedFields.class);
|
||||||
|
@ -96,6 +105,7 @@ public class ExposeFieldsTest extends TestCase {
|
||||||
assertEquals(1, obj.b);
|
assertEquals(1, obj.b);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testExposedInterfaceFieldSerialization() throws Exception {
|
public void testExposedInterfaceFieldSerialization() throws Exception {
|
||||||
String expected = "{\"interfaceField\":{}}";
|
String expected = "{\"interfaceField\":{}}";
|
||||||
ClassWithInterfaceField target = new ClassWithInterfaceField(new SomeObject());
|
ClassWithInterfaceField target = new ClassWithInterfaceField(new SomeObject());
|
||||||
|
@ -104,6 +114,7 @@ public class ExposeFieldsTest extends TestCase {
|
||||||
assertEquals(expected, actual);
|
assertEquals(expected, actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testExposedInterfaceFieldDeserialization() throws Exception {
|
public void testExposedInterfaceFieldDeserialization() throws Exception {
|
||||||
String json = "{\"interfaceField\":{}}";
|
String json = "{\"interfaceField\":{}}";
|
||||||
ClassWithInterfaceField obj = gson.fromJson(json, ClassWithInterfaceField.class);
|
ClassWithInterfaceField obj = gson.fromJson(json, ClassWithInterfaceField.class);
|
||||||
|
|
|
@ -16,10 +16,12 @@
|
||||||
|
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.GsonBuilder;
|
import com.google.gson.GsonBuilder;
|
||||||
|
import org.junit.Before;
|
||||||
import junit.framework.TestCase;
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Performs some functional testing to ensure GSON infrastructure properly serializes/deserializes
|
* Performs some functional testing to ensure GSON infrastructure properly serializes/deserializes
|
||||||
|
@ -28,17 +30,17 @@ import junit.framework.TestCase;
|
||||||
*
|
*
|
||||||
* @author Joel Leitch
|
* @author Joel Leitch
|
||||||
*/
|
*/
|
||||||
public class FieldExclusionTest extends TestCase {
|
public class FieldExclusionTest {
|
||||||
private static final String VALUE = "blah_1234";
|
private static final String VALUE = "blah_1234";
|
||||||
|
|
||||||
private Outer outer;
|
private Outer outer;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
outer = new Outer();
|
outer = new Outer();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDefaultInnerClassExclusion() throws Exception {
|
public void testDefaultInnerClassExclusion() throws Exception {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
Outer.Inner target = outer.new Inner(VALUE);
|
Outer.Inner target = outer.new Inner(VALUE);
|
||||||
|
@ -51,6 +53,7 @@ public class FieldExclusionTest extends TestCase {
|
||||||
assertEquals(target.toJson(), result);
|
assertEquals(target.toJson(), result);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testInnerClassExclusion() throws Exception {
|
public void testInnerClassExclusion() throws Exception {
|
||||||
Gson gson = new GsonBuilder().disableInnerClassSerialization().create();
|
Gson gson = new GsonBuilder().disableInnerClassSerialization().create();
|
||||||
Outer.Inner target = outer.new Inner(VALUE);
|
Outer.Inner target = outer.new Inner(VALUE);
|
||||||
|
@ -58,6 +61,7 @@ public class FieldExclusionTest extends TestCase {
|
||||||
assertEquals("null", result);
|
assertEquals("null", result);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDefaultNestedStaticClassIncluded() throws Exception {
|
public void testDefaultNestedStaticClassIncluded() throws Exception {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
Outer.Inner target = outer.new Inner(VALUE);
|
Outer.Inner target = outer.new Inner(VALUE);
|
||||||
|
|
|
@ -22,14 +22,16 @@ import static com.google.gson.FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES;
|
||||||
import static com.google.gson.FieldNamingPolicy.UPPER_CAMEL_CASE;
|
import static com.google.gson.FieldNamingPolicy.UPPER_CAMEL_CASE;
|
||||||
import static com.google.gson.FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES;
|
import static com.google.gson.FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES;
|
||||||
import static com.google.gson.FieldNamingPolicy.UPPER_CASE_WITH_UNDERSCORES;
|
import static com.google.gson.FieldNamingPolicy.UPPER_CASE_WITH_UNDERSCORES;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
import com.google.gson.FieldNamingPolicy;
|
import com.google.gson.FieldNamingPolicy;
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.GsonBuilder;
|
import com.google.gson.GsonBuilder;
|
||||||
import com.google.gson.annotations.SerializedName;
|
import com.google.gson.annotations.SerializedName;
|
||||||
import junit.framework.TestCase;
|
import org.junit.Test;
|
||||||
|
|
||||||
public final class FieldNamingTest extends TestCase {
|
public final class FieldNamingTest {
|
||||||
|
@Test
|
||||||
public void testIdentity() {
|
public void testIdentity() {
|
||||||
Gson gson = getGsonWithNamingPolicy(IDENTITY);
|
Gson gson = getGsonWithNamingPolicy(IDENTITY);
|
||||||
assertEquals("{'lowerCamel':1,'UpperCamel':2,'_lowerCamelLeadingUnderscore':3," +
|
assertEquals("{'lowerCamel':1,'UpperCamel':2,'_lowerCamelLeadingUnderscore':3," +
|
||||||
|
@ -38,6 +40,7 @@ public final class FieldNamingTest extends TestCase {
|
||||||
gson.toJson(new TestNames()).replace('\"', '\''));
|
gson.toJson(new TestNames()).replace('\"', '\''));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testUpperCamelCase() {
|
public void testUpperCamelCase() {
|
||||||
Gson gson = getGsonWithNamingPolicy(UPPER_CAMEL_CASE);
|
Gson gson = getGsonWithNamingPolicy(UPPER_CAMEL_CASE);
|
||||||
assertEquals("{'LowerCamel':1,'UpperCamel':2,'_LowerCamelLeadingUnderscore':3," +
|
assertEquals("{'LowerCamel':1,'UpperCamel':2,'_LowerCamelLeadingUnderscore':3," +
|
||||||
|
@ -46,6 +49,7 @@ public final class FieldNamingTest extends TestCase {
|
||||||
gson.toJson(new TestNames()).replace('\"', '\''));
|
gson.toJson(new TestNames()).replace('\"', '\''));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testUpperCamelCaseWithSpaces() {
|
public void testUpperCamelCaseWithSpaces() {
|
||||||
Gson gson = getGsonWithNamingPolicy(UPPER_CAMEL_CASE_WITH_SPACES);
|
Gson gson = getGsonWithNamingPolicy(UPPER_CAMEL_CASE_WITH_SPACES);
|
||||||
assertEquals("{'Lower Camel':1,'Upper Camel':2,'_Lower Camel Leading Underscore':3," +
|
assertEquals("{'Lower Camel':1,'Upper Camel':2,'_Lower Camel Leading Underscore':3," +
|
||||||
|
@ -54,6 +58,7 @@ public final class FieldNamingTest extends TestCase {
|
||||||
gson.toJson(new TestNames()).replace('\"', '\''));
|
gson.toJson(new TestNames()).replace('\"', '\''));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testUpperCaseWithUnderscores() {
|
public void testUpperCaseWithUnderscores() {
|
||||||
Gson gson = getGsonWithNamingPolicy(UPPER_CASE_WITH_UNDERSCORES);
|
Gson gson = getGsonWithNamingPolicy(UPPER_CASE_WITH_UNDERSCORES);
|
||||||
assertEquals("{'LOWER_CAMEL':1,'UPPER_CAMEL':2,'_LOWER_CAMEL_LEADING_UNDERSCORE':3," +
|
assertEquals("{'LOWER_CAMEL':1,'UPPER_CAMEL':2,'_LOWER_CAMEL_LEADING_UNDERSCORE':3," +
|
||||||
|
@ -62,6 +67,7 @@ public final class FieldNamingTest extends TestCase {
|
||||||
gson.toJson(new TestNames()).replace('\"', '\''));
|
gson.toJson(new TestNames()).replace('\"', '\''));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testLowerCaseWithUnderscores() {
|
public void testLowerCaseWithUnderscores() {
|
||||||
Gson gson = getGsonWithNamingPolicy(LOWER_CASE_WITH_UNDERSCORES);
|
Gson gson = getGsonWithNamingPolicy(LOWER_CASE_WITH_UNDERSCORES);
|
||||||
assertEquals("{'lower_camel':1,'upper_camel':2,'_lower_camel_leading_underscore':3," +
|
assertEquals("{'lower_camel':1,'upper_camel':2,'_lower_camel_leading_underscore':3," +
|
||||||
|
@ -70,6 +76,7 @@ public final class FieldNamingTest extends TestCase {
|
||||||
gson.toJson(new TestNames()).replace('\"', '\''));
|
gson.toJson(new TestNames()).replace('\"', '\''));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testLowerCaseWithDashes() {
|
public void testLowerCaseWithDashes() {
|
||||||
Gson gson = getGsonWithNamingPolicy(LOWER_CASE_WITH_DASHES);
|
Gson gson = getGsonWithNamingPolicy(LOWER_CASE_WITH_DASHES);
|
||||||
assertEquals("{'lower-camel':1,'upper-camel':2,'_lower-camel-leading-underscore':3," +
|
assertEquals("{'lower-camel':1,'upper-camel':2,'_lower-camel-leading-underscore':3," +
|
||||||
|
|
|
@ -15,26 +15,25 @@
|
||||||
*/
|
*/
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
import java.io.IOException;
|
import static org.junit.Assert.assertTrue;
|
||||||
import java.util.regex.Pattern;
|
import static org.junit.Assert.fail;
|
||||||
|
|
||||||
import org.junit.Before;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.GsonBuilder;
|
import com.google.gson.GsonBuilder;
|
||||||
import com.google.gson.TypeAdapter;
|
import com.google.gson.TypeAdapter;
|
||||||
import com.google.gson.stream.JsonReader;
|
import com.google.gson.stream.JsonReader;
|
||||||
import com.google.gson.stream.JsonWriter;
|
import com.google.gson.stream.JsonWriter;
|
||||||
|
import java.io.IOException;
|
||||||
import junit.framework.TestCase;
|
import java.util.regex.Pattern;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Functional tests to validate printing of Gson version on AssertionErrors
|
* Functional tests to validate printing of Gson version on AssertionErrors
|
||||||
*
|
*
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
*/
|
*/
|
||||||
public class GsonVersionDiagnosticsTest extends TestCase {
|
public class GsonVersionDiagnosticsTest {
|
||||||
// We require a patch number, even if it is .0, consistent with https://semver.org/#spec-item-2.
|
// We require a patch number, even if it is .0, consistent with https://semver.org/#spec-item-2.
|
||||||
private static final Pattern GSON_VERSION_PATTERN =
|
private static final Pattern GSON_VERSION_PATTERN =
|
||||||
Pattern.compile("(\\(GSON \\d\\.\\d+\\.\\d)(?:[-.][A-Z]+)?\\)$");
|
Pattern.compile("(\\(GSON \\d\\.\\d+\\.\\d)(?:[-.][A-Z]+)?\\)$");
|
||||||
|
@ -42,7 +41,6 @@ public class GsonVersionDiagnosticsTest extends TestCase {
|
||||||
private Gson gson;
|
private Gson gson;
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
@Override
|
|
||||||
public void setUp() {
|
public void setUp() {
|
||||||
gson = new GsonBuilder().registerTypeAdapter(TestType.class, new TypeAdapter<TestType>() {
|
gson = new GsonBuilder().registerTypeAdapter(TestType.class, new TypeAdapter<TestType>() {
|
||||||
@Override public void write(JsonWriter out, TestType value) {
|
@Override public void write(JsonWriter out, TestType value) {
|
||||||
|
|
|
@ -15,6 +15,11 @@
|
||||||
*/
|
*/
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertNull;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.JsonArray;
|
import com.google.gson.JsonArray;
|
||||||
import com.google.gson.JsonElement;
|
import com.google.gson.JsonElement;
|
||||||
|
@ -26,9 +31,6 @@ import com.google.gson.common.TestTypes.ClassWithBaseCollectionField;
|
||||||
import com.google.gson.common.TestTypes.ClassWithBaseField;
|
import com.google.gson.common.TestTypes.ClassWithBaseField;
|
||||||
import com.google.gson.common.TestTypes.Nested;
|
import com.google.gson.common.TestTypes.Nested;
|
||||||
import com.google.gson.common.TestTypes.Sub;
|
import com.google.gson.common.TestTypes.Sub;
|
||||||
|
|
||||||
import junit.framework.TestCase;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
import java.util.LinkedList;
|
import java.util.LinkedList;
|
||||||
|
@ -37,6 +39,8 @@ import java.util.Queue;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.SortedSet;
|
import java.util.SortedSet;
|
||||||
import java.util.TreeSet;
|
import java.util.TreeSet;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Functional tests for Json serialization and deserialization of classes with
|
* Functional tests for Json serialization and deserialization of classes with
|
||||||
|
@ -45,21 +49,22 @@ import java.util.TreeSet;
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
* @author Joel Leitch
|
* @author Joel Leitch
|
||||||
*/
|
*/
|
||||||
public class InheritanceTest extends TestCase {
|
public class InheritanceTest {
|
||||||
private Gson gson;
|
private Gson gson;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
gson = new Gson();
|
gson = new Gson();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSubClassSerialization() throws Exception {
|
public void testSubClassSerialization() throws Exception {
|
||||||
SubTypeOfNested target = new SubTypeOfNested(new BagOfPrimitives(10, 20, false, "stringValue"),
|
SubTypeOfNested target = new SubTypeOfNested(new BagOfPrimitives(10, 20, false, "stringValue"),
|
||||||
new BagOfPrimitives(30, 40, true, "stringValue"));
|
new BagOfPrimitives(30, 40, true, "stringValue"));
|
||||||
assertEquals(target.getExpectedJson(), gson.toJson(target));
|
assertEquals(target.getExpectedJson(), gson.toJson(target));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSubClassDeserialization() throws Exception {
|
public void testSubClassDeserialization() throws Exception {
|
||||||
String json = "{\"value\":5,\"primitive1\":{\"longValue\":10,\"intValue\":20,"
|
String json = "{\"value\":5,\"primitive1\":{\"longValue\":10,\"intValue\":20,"
|
||||||
+ "\"booleanValue\":false,\"stringValue\":\"stringValue\"},\"primitive2\":"
|
+ "\"booleanValue\":false,\"stringValue\":\"stringValue\"},\"primitive2\":"
|
||||||
|
@ -69,6 +74,7 @@ public class InheritanceTest extends TestCase {
|
||||||
assertEquals(json, target.getExpectedJson());
|
assertEquals(json, target.getExpectedJson());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testClassWithBaseFieldSerialization() {
|
public void testClassWithBaseFieldSerialization() {
|
||||||
ClassWithBaseField sub = new ClassWithBaseField(new Sub());
|
ClassWithBaseField sub = new ClassWithBaseField(new Sub());
|
||||||
JsonObject json = (JsonObject) gson.toJsonTree(sub);
|
JsonObject json = (JsonObject) gson.toJsonTree(sub);
|
||||||
|
@ -76,6 +82,7 @@ public class InheritanceTest extends TestCase {
|
||||||
assertEquals(Sub.SUB_NAME, base.getAsJsonObject().get(Sub.SUB_FIELD_KEY).getAsString());
|
assertEquals(Sub.SUB_NAME, base.getAsJsonObject().get(Sub.SUB_FIELD_KEY).getAsString());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testClassWithBaseArrayFieldSerialization() {
|
public void testClassWithBaseArrayFieldSerialization() {
|
||||||
Base[] baseClasses = new Base[]{ new Sub(), new Sub()};
|
Base[] baseClasses = new Base[]{ new Sub(), new Sub()};
|
||||||
ClassWithBaseArrayField sub = new ClassWithBaseArrayField(baseClasses);
|
ClassWithBaseArrayField sub = new ClassWithBaseArrayField(baseClasses);
|
||||||
|
@ -86,6 +93,7 @@ public class InheritanceTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testClassWithBaseCollectionFieldSerialization() {
|
public void testClassWithBaseCollectionFieldSerialization() {
|
||||||
Collection<Base> baseClasses = new ArrayList<>();
|
Collection<Base> baseClasses = new ArrayList<>();
|
||||||
baseClasses.add(new Sub());
|
baseClasses.add(new Sub());
|
||||||
|
@ -98,18 +106,21 @@ public class InheritanceTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBaseSerializedAsSub() {
|
public void testBaseSerializedAsSub() {
|
||||||
Base base = new Sub();
|
Base base = new Sub();
|
||||||
JsonObject json = gson.toJsonTree(base).getAsJsonObject();
|
JsonObject json = gson.toJsonTree(base).getAsJsonObject();
|
||||||
assertEquals(Sub.SUB_NAME, json.get(Sub.SUB_FIELD_KEY).getAsString());
|
assertEquals(Sub.SUB_NAME, json.get(Sub.SUB_FIELD_KEY).getAsString());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBaseSerializedAsSubForToJsonMethod() {
|
public void testBaseSerializedAsSubForToJsonMethod() {
|
||||||
Base base = new Sub();
|
Base base = new Sub();
|
||||||
String json = gson.toJson(base);
|
String json = gson.toJson(base);
|
||||||
assertTrue(json.contains(Sub.SUB_NAME));
|
assertTrue(json.contains(Sub.SUB_NAME));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBaseSerializedAsBaseWhenSpecifiedWithExplicitType() {
|
public void testBaseSerializedAsBaseWhenSpecifiedWithExplicitType() {
|
||||||
Base base = new Sub();
|
Base base = new Sub();
|
||||||
JsonObject json = gson.toJsonTree(base, Base.class).getAsJsonObject();
|
JsonObject json = gson.toJsonTree(base, Base.class).getAsJsonObject();
|
||||||
|
@ -117,6 +128,7 @@ public class InheritanceTest extends TestCase {
|
||||||
assertNull(json.get(Sub.SUB_FIELD_KEY));
|
assertNull(json.get(Sub.SUB_FIELD_KEY));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBaseSerializedAsBaseWhenSpecifiedWithExplicitTypeForToJsonMethod() {
|
public void testBaseSerializedAsBaseWhenSpecifiedWithExplicitTypeForToJsonMethod() {
|
||||||
Base base = new Sub();
|
Base base = new Sub();
|
||||||
String json = gson.toJson(base, Base.class);
|
String json = gson.toJson(base, Base.class);
|
||||||
|
@ -124,12 +136,14 @@ public class InheritanceTest extends TestCase {
|
||||||
assertFalse(json.contains(Sub.SUB_FIELD_KEY));
|
assertFalse(json.contains(Sub.SUB_FIELD_KEY));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBaseSerializedAsSubWhenSpecifiedWithExplicitType() {
|
public void testBaseSerializedAsSubWhenSpecifiedWithExplicitType() {
|
||||||
Base base = new Sub();
|
Base base = new Sub();
|
||||||
JsonObject json = gson.toJsonTree(base, Sub.class).getAsJsonObject();
|
JsonObject json = gson.toJsonTree(base, Sub.class).getAsJsonObject();
|
||||||
assertEquals(Sub.SUB_NAME, json.get(Sub.SUB_FIELD_KEY).getAsString());
|
assertEquals(Sub.SUB_NAME, json.get(Sub.SUB_FIELD_KEY).getAsString());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBaseSerializedAsSubWhenSpecifiedWithExplicitTypeForToJsonMethod() {
|
public void testBaseSerializedAsSubWhenSpecifiedWithExplicitTypeForToJsonMethod() {
|
||||||
Base base = new Sub();
|
Base base = new Sub();
|
||||||
String json = gson.toJson(base, Sub.class);
|
String json = gson.toJson(base, Sub.class);
|
||||||
|
@ -150,6 +164,7 @@ public class InheritanceTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSubInterfacesOfCollectionSerialization() throws Exception {
|
public void testSubInterfacesOfCollectionSerialization() throws Exception {
|
||||||
List<Integer> list = new LinkedList<>();
|
List<Integer> list = new LinkedList<>();
|
||||||
list.add(0);
|
list.add(0);
|
||||||
|
@ -176,6 +191,7 @@ public class InheritanceTest extends TestCase {
|
||||||
assertEquals(target.getExpectedJson(), gson.toJson(target));
|
assertEquals(target.getExpectedJson(), gson.toJson(target));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSubInterfacesOfCollectionDeserialization() throws Exception {
|
public void testSubInterfacesOfCollectionDeserialization() throws Exception {
|
||||||
String json = "{\"list\":[0,1,2,3],\"queue\":[0,1,2,3],\"set\":[0.1,0.2,0.3,0.4],"
|
String json = "{\"list\":[0,1,2,3],\"queue\":[0,1,2,3],\"set\":[0.1,0.2,0.3,0.4],"
|
||||||
+ "\"sortedSet\":[\"a\",\"b\",\"c\",\"d\"]"
|
+ "\"sortedSet\":[\"a\",\"b\",\"c\",\"d\"]"
|
||||||
|
|
|
@ -16,6 +16,10 @@
|
||||||
|
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.GsonBuilder;
|
import com.google.gson.GsonBuilder;
|
||||||
import com.google.gson.InstanceCreator;
|
import com.google.gson.InstanceCreator;
|
||||||
|
@ -28,7 +32,7 @@ import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.SortedSet;
|
import java.util.SortedSet;
|
||||||
import java.util.TreeSet;
|
import java.util.TreeSet;
|
||||||
import junit.framework.TestCase;
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Functional Test exercising custom serialization only. When test applies to both
|
* Functional Test exercising custom serialization only. When test applies to both
|
||||||
|
@ -36,8 +40,9 @@ import junit.framework.TestCase;
|
||||||
*
|
*
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
*/
|
*/
|
||||||
public class InstanceCreatorTest extends TestCase {
|
public class InstanceCreatorTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testInstanceCreatorReturnsBaseType() {
|
public void testInstanceCreatorReturnsBaseType() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.setLenient()
|
.setLenient()
|
||||||
|
@ -48,6 +53,7 @@ public class InstanceCreatorTest extends TestCase {
|
||||||
assertEquals("BaseRevised", base.baseName);
|
assertEquals("BaseRevised", base.baseName);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testInstanceCreatorReturnsSubTypeForTopLevelObject() {
|
public void testInstanceCreatorReturnsSubTypeForTopLevelObject() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.setLenient()
|
.setLenient()
|
||||||
|
@ -63,6 +69,7 @@ public class InstanceCreatorTest extends TestCase {
|
||||||
assertEquals(Sub.SUB_NAME, sub.subName);
|
assertEquals(Sub.SUB_NAME, sub.subName);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testInstanceCreatorReturnsSubTypeForField() {
|
public void testInstanceCreatorReturnsSubTypeForField() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.setLenient()
|
.setLenient()
|
||||||
|
@ -75,6 +82,7 @@ public class InstanceCreatorTest extends TestCase {
|
||||||
}
|
}
|
||||||
|
|
||||||
// This regressed in Gson 2.0 and 2.1
|
// This regressed in Gson 2.0 and 2.1
|
||||||
|
@Test
|
||||||
public void testInstanceCreatorForCollectionType() {
|
public void testInstanceCreatorForCollectionType() {
|
||||||
@SuppressWarnings("serial")
|
@SuppressWarnings("serial")
|
||||||
class SubArrayList<T> extends ArrayList<T> {}
|
class SubArrayList<T> extends ArrayList<T> {}
|
||||||
|
@ -92,6 +100,7 @@ public class InstanceCreatorTest extends TestCase {
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
|
@Test
|
||||||
public void testInstanceCreatorForParametrizedType() throws Exception {
|
public void testInstanceCreatorForParametrizedType() throws Exception {
|
||||||
@SuppressWarnings("serial")
|
@SuppressWarnings("serial")
|
||||||
class SubTreeSet<T> extends TreeSet<T> {}
|
class SubTreeSet<T> extends TreeSet<T> {}
|
||||||
|
|
|
@ -16,9 +16,11 @@
|
||||||
|
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
import junit.framework.TestCase;
|
import com.google.gson.Gson;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Functional tests involving interfaces.
|
* Functional tests involving interfaces.
|
||||||
|
@ -26,23 +28,24 @@ import junit.framework.TestCase;
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
* @author Joel Leitch
|
* @author Joel Leitch
|
||||||
*/
|
*/
|
||||||
public class InterfaceTest extends TestCase {
|
public class InterfaceTest {
|
||||||
private static final String OBJ_JSON = "{\"someStringValue\":\"StringValue\"}";
|
private static final String OBJ_JSON = "{\"someStringValue\":\"StringValue\"}";
|
||||||
|
|
||||||
private Gson gson;
|
private Gson gson;
|
||||||
private TestObject obj;
|
private TestObject obj;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
gson = new Gson();
|
gson = new Gson();
|
||||||
obj = new TestObject("StringValue");
|
obj = new TestObject("StringValue");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSerializingObjectImplementingInterface() throws Exception {
|
public void testSerializingObjectImplementingInterface() throws Exception {
|
||||||
assertEquals(OBJ_JSON, gson.toJson(obj));
|
assertEquals(OBJ_JSON, gson.toJson(obj));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSerializingInterfaceObjectField() throws Exception {
|
public void testSerializingInterfaceObjectField() throws Exception {
|
||||||
TestObjectWrapper objWrapper = new TestObjectWrapper(obj);
|
TestObjectWrapper objWrapper = new TestObjectWrapper(obj);
|
||||||
assertEquals("{\"obj\":" + OBJ_JSON + "}", gson.toJson(objWrapper));
|
assertEquals("{\"obj\":" + OBJ_JSON + "}", gson.toJson(objWrapper));
|
||||||
|
|
|
@ -16,23 +16,26 @@
|
||||||
|
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import junit.framework.TestCase;
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Functional tests for internationalized strings.
|
* Functional tests for internationalized strings.
|
||||||
*
|
*
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
*/
|
*/
|
||||||
public class InternationalizationTest extends TestCase {
|
public class InternationalizationTest {
|
||||||
private Gson gson;
|
private Gson gson;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
gson = new Gson();
|
gson = new Gson();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testStringsWithUnicodeChineseCharactersSerialization() throws Exception {
|
public void testStringsWithUnicodeChineseCharactersSerialization() throws Exception {
|
||||||
String target = "\u597d\u597d\u597d";
|
String target = "\u597d\u597d\u597d";
|
||||||
String json = gson.toJson(target);
|
String json = gson.toJson(target);
|
||||||
|
@ -40,6 +43,7 @@ public class InternationalizationTest extends TestCase {
|
||||||
assertEquals(expected, json);
|
assertEquals(expected, json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testStringsWithUnicodeChineseCharactersDeserialization() throws Exception {
|
public void testStringsWithUnicodeChineseCharactersDeserialization() throws Exception {
|
||||||
String expected = "\u597d\u597d\u597d";
|
String expected = "\u597d\u597d\u597d";
|
||||||
String json = '"' + expected + '"';
|
String json = '"' + expected + '"';
|
||||||
|
@ -47,11 +51,13 @@ public class InternationalizationTest extends TestCase {
|
||||||
assertEquals(expected, actual);
|
assertEquals(expected, actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testStringsWithUnicodeChineseCharactersEscapedDeserialization() throws Exception {
|
public void testStringsWithUnicodeChineseCharactersEscapedDeserialization() throws Exception {
|
||||||
String actual = gson.fromJson("\"\\u597d\\u597d\\u597d\"", String.class);
|
String actual = gson.fromJson("\"\\u597d\\u597d\\u597d\"", String.class);
|
||||||
assertEquals("\u597d\u597d\u597d", actual);
|
assertEquals("\u597d\u597d\u597d", actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSupplementaryUnicodeSerialization() throws Exception {
|
public void testSupplementaryUnicodeSerialization() throws Exception {
|
||||||
// Supplementary code point U+1F60A
|
// Supplementary code point U+1F60A
|
||||||
String supplementaryCodePoint = new String(new int[] {0x1F60A}, 0, 1);
|
String supplementaryCodePoint = new String(new int[] {0x1F60A}, 0, 1);
|
||||||
|
@ -59,6 +65,7 @@ public class InternationalizationTest extends TestCase {
|
||||||
assertEquals('"' + supplementaryCodePoint + '"', json);
|
assertEquals('"' + supplementaryCodePoint + '"', json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSupplementaryUnicodeDeserialization() throws Exception {
|
public void testSupplementaryUnicodeDeserialization() throws Exception {
|
||||||
// Supplementary code point U+1F60A
|
// Supplementary code point U+1F60A
|
||||||
String supplementaryCodePoint = new String(new int[] {0x1F60A}, 0, 1);
|
String supplementaryCodePoint = new String(new int[] {0x1F60A}, 0, 1);
|
||||||
|
@ -66,6 +73,7 @@ public class InternationalizationTest extends TestCase {
|
||||||
assertEquals(supplementaryCodePoint, actual);
|
assertEquals(supplementaryCodePoint, actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSupplementaryUnicodeEscapedDeserialization() throws Exception {
|
public void testSupplementaryUnicodeEscapedDeserialization() throws Exception {
|
||||||
// Supplementary code point U+1F60A
|
// Supplementary code point U+1F60A
|
||||||
String supplementaryCodePoint = new String(new int[] {0x1F60A}, 0, 1);
|
String supplementaryCodePoint = new String(new int[] {0x1F60A}, 0, 1);
|
||||||
|
|
|
@ -16,30 +16,32 @@
|
||||||
|
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import com.google.gson.Gson;
|
||||||
|
import com.google.gson.GsonBuilder;
|
||||||
|
import com.google.gson.LongSerializationPolicy;
|
||||||
import java.util.concurrent.atomic.AtomicBoolean;
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
import java.util.concurrent.atomic.AtomicInteger;
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
import java.util.concurrent.atomic.AtomicIntegerArray;
|
import java.util.concurrent.atomic.AtomicIntegerArray;
|
||||||
import java.util.concurrent.atomic.AtomicLong;
|
import java.util.concurrent.atomic.AtomicLong;
|
||||||
import java.util.concurrent.atomic.AtomicLongArray;
|
import java.util.concurrent.atomic.AtomicLongArray;
|
||||||
|
import org.junit.Before;
|
||||||
import com.google.gson.Gson;
|
import org.junit.Test;
|
||||||
import com.google.gson.GsonBuilder;
|
|
||||||
import com.google.gson.LongSerializationPolicy;
|
|
||||||
|
|
||||||
import junit.framework.TestCase;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Functional test for Json serialization and deserialization for classes in java.util.concurrent.atomic
|
* Functional test for Json serialization and deserialization for classes in java.util.concurrent.atomic
|
||||||
*/
|
*/
|
||||||
public class JavaUtilConcurrentAtomicTest extends TestCase {
|
public class JavaUtilConcurrentAtomicTest {
|
||||||
private Gson gson;
|
private Gson gson;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
gson = new Gson();
|
gson = new Gson();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testAtomicBoolean() throws Exception {
|
public void testAtomicBoolean() throws Exception {
|
||||||
AtomicBoolean target = gson.fromJson("true", AtomicBoolean.class);
|
AtomicBoolean target = gson.fromJson("true", AtomicBoolean.class);
|
||||||
assertTrue(target.get());
|
assertTrue(target.get());
|
||||||
|
@ -47,6 +49,7 @@ public class JavaUtilConcurrentAtomicTest extends TestCase {
|
||||||
assertEquals("true", json);
|
assertEquals("true", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testAtomicInteger() throws Exception {
|
public void testAtomicInteger() throws Exception {
|
||||||
AtomicInteger target = gson.fromJson("10", AtomicInteger.class);
|
AtomicInteger target = gson.fromJson("10", AtomicInteger.class);
|
||||||
assertEquals(10, target.get());
|
assertEquals(10, target.get());
|
||||||
|
@ -54,6 +57,7 @@ public class JavaUtilConcurrentAtomicTest extends TestCase {
|
||||||
assertEquals("10", json);
|
assertEquals("10", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testAtomicLong() throws Exception {
|
public void testAtomicLong() throws Exception {
|
||||||
AtomicLong target = gson.fromJson("10", AtomicLong.class);
|
AtomicLong target = gson.fromJson("10", AtomicLong.class);
|
||||||
assertEquals(10, target.get());
|
assertEquals(10, target.get());
|
||||||
|
@ -61,6 +65,7 @@ public class JavaUtilConcurrentAtomicTest extends TestCase {
|
||||||
assertEquals("10", json);
|
assertEquals("10", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testAtomicLongWithStringSerializationPolicy() throws Exception {
|
public void testAtomicLongWithStringSerializationPolicy() throws Exception {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.setLongSerializationPolicy(LongSerializationPolicy.STRING)
|
.setLongSerializationPolicy(LongSerializationPolicy.STRING)
|
||||||
|
@ -71,6 +76,7 @@ public class JavaUtilConcurrentAtomicTest extends TestCase {
|
||||||
assertEquals("{\"value\":\"10\"}", json);
|
assertEquals("{\"value\":\"10\"}", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testAtomicIntegerArray() throws Exception {
|
public void testAtomicIntegerArray() throws Exception {
|
||||||
AtomicIntegerArray target = gson.fromJson("[10, 13, 14]", AtomicIntegerArray.class);
|
AtomicIntegerArray target = gson.fromJson("[10, 13, 14]", AtomicIntegerArray.class);
|
||||||
assertEquals(3, target.length());
|
assertEquals(3, target.length());
|
||||||
|
@ -81,6 +87,7 @@ public class JavaUtilConcurrentAtomicTest extends TestCase {
|
||||||
assertEquals("[10,13,14]", json);
|
assertEquals("[10,13,14]", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testAtomicLongArray() throws Exception {
|
public void testAtomicLongArray() throws Exception {
|
||||||
AtomicLongArray target = gson.fromJson("[10, 13, 14]", AtomicLongArray.class);
|
AtomicLongArray target = gson.fromJson("[10, 13, 14]", AtomicLongArray.class);
|
||||||
assertEquals(3, target.length());
|
assertEquals(3, target.length());
|
||||||
|
@ -91,6 +98,7 @@ public class JavaUtilConcurrentAtomicTest extends TestCase {
|
||||||
assertEquals("[10,13,14]", json);
|
assertEquals("[10,13,14]", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testAtomicLongArrayWithStringSerializationPolicy() throws Exception {
|
public void testAtomicLongArrayWithStringSerializationPolicy() throws Exception {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.setLongSerializationPolicy(LongSerializationPolicy.STRING)
|
.setLongSerializationPolicy(LongSerializationPolicy.STRING)
|
||||||
|
|
|
@ -16,25 +16,28 @@
|
||||||
|
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
import java.util.Currency;
|
import static org.junit.Assert.assertEquals;
|
||||||
import java.util.Properties;
|
import static org.junit.Assert.assertNull;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
|
import java.util.Currency;
|
||||||
import junit.framework.TestCase;
|
import java.util.Properties;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Functional test for Json serialization and deserialization for classes in java.util
|
* Functional test for Json serialization and deserialization for classes in java.util
|
||||||
*/
|
*/
|
||||||
public class JavaUtilTest extends TestCase {
|
public class JavaUtilTest {
|
||||||
private Gson gson;
|
private Gson gson;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
gson = new Gson();
|
gson = new Gson();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testCurrency() throws Exception {
|
public void testCurrency() throws Exception {
|
||||||
CurrencyHolder target = gson.fromJson("{\"value\":\"USD\"}", CurrencyHolder.class);
|
CurrencyHolder target = gson.fromJson("{\"value\":\"USD\"}", CurrencyHolder.class);
|
||||||
assertEquals("USD", target.value.getCurrencyCode());
|
assertEquals("USD", target.value.getCurrencyCode());
|
||||||
|
@ -51,6 +54,7 @@ public class JavaUtilTest extends TestCase {
|
||||||
Currency value;
|
Currency value;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testProperties() {
|
public void testProperties() {
|
||||||
Properties props = gson.fromJson("{\"a\":\"v1\",\"b\":\"v2\"}", Properties.class);
|
Properties props = gson.fromJson("{\"a\":\"v1\",\"b\":\"v2\"}", Properties.class);
|
||||||
assertEquals("v1", props.getProperty("a"));
|
assertEquals("v1", props.getProperty("a"));
|
||||||
|
|
|
@ -16,6 +16,11 @@
|
||||||
|
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertNull;
|
||||||
|
import static org.junit.Assert.fail;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.GsonBuilder;
|
import com.google.gson.GsonBuilder;
|
||||||
import com.google.gson.JsonDeserializationContext;
|
import com.google.gson.JsonDeserializationContext;
|
||||||
|
@ -34,13 +39,14 @@ import com.google.gson.stream.JsonWriter;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.lang.reflect.Type;
|
import java.lang.reflect.Type;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
import junit.framework.TestCase;
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Functional tests for the {@link com.google.gson.annotations.JsonAdapter} annotation on classes.
|
* Functional tests for the {@link com.google.gson.annotations.JsonAdapter} annotation on classes.
|
||||||
*/
|
*/
|
||||||
public final class JsonAdapterAnnotationOnClassesTest extends TestCase {
|
public final class JsonAdapterAnnotationOnClassesTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testJsonAdapterInvoked() {
|
public void testJsonAdapterInvoked() {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
String json = gson.toJson(new A("bar"));
|
String json = gson.toJson(new A("bar"));
|
||||||
|
@ -59,6 +65,7 @@ public final class JsonAdapterAnnotationOnClassesTest extends TestCase {
|
||||||
assertEquals(Foo.BAZ, baz);
|
assertEquals(Foo.BAZ, baz);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testJsonAdapterFactoryInvoked() {
|
public void testJsonAdapterFactoryInvoked() {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
String json = gson.toJson(new C("bar"));
|
String json = gson.toJson(new C("bar"));
|
||||||
|
@ -67,6 +74,7 @@ public final class JsonAdapterAnnotationOnClassesTest extends TestCase {
|
||||||
assertEquals("jsonAdapterFactory", c.value);
|
assertEquals("jsonAdapterFactory", c.value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testRegisteredAdapterOverridesJsonAdapter() {
|
public void testRegisteredAdapterOverridesJsonAdapter() {
|
||||||
TypeAdapter<A> typeAdapter = new TypeAdapter<A>() {
|
TypeAdapter<A> typeAdapter = new TypeAdapter<A>() {
|
||||||
@Override public void write(JsonWriter out, A value) throws IOException {
|
@Override public void write(JsonWriter out, A value) throws IOException {
|
||||||
|
@ -86,6 +94,7 @@ public final class JsonAdapterAnnotationOnClassesTest extends TestCase {
|
||||||
/**
|
/**
|
||||||
* The serializer overrides field adapter, but for deserializer the fieldAdapter is used.
|
* The serializer overrides field adapter, but for deserializer the fieldAdapter is used.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testRegisteredSerializerOverridesJsonAdapter() {
|
public void testRegisteredSerializerOverridesJsonAdapter() {
|
||||||
JsonSerializer<A> serializer = new JsonSerializer<A>() {
|
JsonSerializer<A> serializer = new JsonSerializer<A>() {
|
||||||
@Override public JsonElement serialize(A src, Type typeOfSrc,
|
@Override public JsonElement serialize(A src, Type typeOfSrc,
|
||||||
|
@ -106,6 +115,7 @@ public final class JsonAdapterAnnotationOnClassesTest extends TestCase {
|
||||||
/**
|
/**
|
||||||
* The deserializer overrides Json adapter, but for serializer the jsonAdapter is used.
|
* The deserializer overrides Json adapter, but for serializer the jsonAdapter is used.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testRegisteredDeserializerOverridesJsonAdapter() {
|
public void testRegisteredDeserializerOverridesJsonAdapter() {
|
||||||
JsonDeserializer<A> deserializer = new JsonDeserializer<A>() {
|
JsonDeserializer<A> deserializer = new JsonDeserializer<A>() {
|
||||||
@Override public A deserialize(JsonElement json, Type typeOfT,
|
@Override public A deserialize(JsonElement json, Type typeOfT,
|
||||||
|
@ -123,6 +133,7 @@ public final class JsonAdapterAnnotationOnClassesTest extends TestCase {
|
||||||
assertEquals("registeredDeserializer", target.value);
|
assertEquals("registeredDeserializer", target.value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testIncorrectTypeAdapterFails() {
|
public void testIncorrectTypeAdapterFails() {
|
||||||
try {
|
try {
|
||||||
String json = new Gson().toJson(new ClassWithIncorrectJsonAdapter("bar"));
|
String json = new Gson().toJson(new ClassWithIncorrectJsonAdapter("bar"));
|
||||||
|
@ -130,11 +141,13 @@ public final class JsonAdapterAnnotationOnClassesTest extends TestCase {
|
||||||
} catch (ClassCastException expected) {}
|
} catch (ClassCastException expected) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSuperclassTypeAdapterNotInvoked() {
|
public void testSuperclassTypeAdapterNotInvoked() {
|
||||||
String json = new Gson().toJson(new B("bar"));
|
String json = new Gson().toJson(new B("bar"));
|
||||||
assertFalse(json.contains("jsonAdapter"));
|
assertFalse(json.contains("jsonAdapter"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNullSafeObjectFromJson() {
|
public void testNullSafeObjectFromJson() {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
NullableClass fromJson = gson.fromJson("null", NullableClass.class);
|
NullableClass fromJson = gson.fromJson("null", NullableClass.class);
|
||||||
|
@ -252,6 +265,7 @@ public final class JsonAdapterAnnotationOnClassesTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testIncorrectJsonAdapterType() {
|
public void testIncorrectJsonAdapterType() {
|
||||||
try {
|
try {
|
||||||
new Gson().toJson(new D());
|
new Gson().toJson(new D());
|
||||||
|
|
|
@ -16,9 +16,9 @@
|
||||||
|
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
import java.io.IOException;
|
import static org.junit.Assert.assertEquals;
|
||||||
import java.util.Arrays;
|
import static org.junit.Assert.assertFalse;
|
||||||
import java.util.List;
|
import static org.junit.Assert.assertNull;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.GsonBuilder;
|
import com.google.gson.GsonBuilder;
|
||||||
|
@ -28,13 +28,16 @@ import com.google.gson.annotations.JsonAdapter;
|
||||||
import com.google.gson.reflect.TypeToken;
|
import com.google.gson.reflect.TypeToken;
|
||||||
import com.google.gson.stream.JsonReader;
|
import com.google.gson.stream.JsonReader;
|
||||||
import com.google.gson.stream.JsonWriter;
|
import com.google.gson.stream.JsonWriter;
|
||||||
|
import java.io.IOException;
|
||||||
import junit.framework.TestCase;
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Functional tests for the {@link com.google.gson.annotations.JsonAdapter} annotation on fields.
|
* Functional tests for the {@link com.google.gson.annotations.JsonAdapter} annotation on fields.
|
||||||
*/
|
*/
|
||||||
public final class JsonAdapterAnnotationOnFieldsTest extends TestCase {
|
public final class JsonAdapterAnnotationOnFieldsTest {
|
||||||
|
@Test
|
||||||
public void testClassAnnotationAdapterTakesPrecedenceOverDefault() {
|
public void testClassAnnotationAdapterTakesPrecedenceOverDefault() {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
String json = gson.toJson(new Computer(new User("Inderjeet Singh")));
|
String json = gson.toJson(new Computer(new User("Inderjeet Singh")));
|
||||||
|
@ -43,6 +46,7 @@ public final class JsonAdapterAnnotationOnFieldsTest extends TestCase {
|
||||||
assertEquals("UserClassAnnotationAdapter", computer.user.name);
|
assertEquals("UserClassAnnotationAdapter", computer.user.name);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testClassAnnotationAdapterFactoryTakesPrecedenceOverDefault() {
|
public void testClassAnnotationAdapterFactoryTakesPrecedenceOverDefault() {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
String json = gson.toJson(new Gizmo(new Part("Part")));
|
String json = gson.toJson(new Gizmo(new Part("Part")));
|
||||||
|
@ -51,6 +55,7 @@ public final class JsonAdapterAnnotationOnFieldsTest extends TestCase {
|
||||||
assertEquals("GizmoPartTypeAdapterFactory", computer.part.name);
|
assertEquals("GizmoPartTypeAdapterFactory", computer.part.name);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testRegisteredTypeAdapterTakesPrecedenceOverClassAnnotationAdapter() {
|
public void testRegisteredTypeAdapterTakesPrecedenceOverClassAnnotationAdapter() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.registerTypeAdapter(User.class, new RegisteredUserAdapter())
|
.registerTypeAdapter(User.class, new RegisteredUserAdapter())
|
||||||
|
@ -61,6 +66,7 @@ public final class JsonAdapterAnnotationOnFieldsTest extends TestCase {
|
||||||
assertEquals("RegisteredUserAdapter", computer.user.name);
|
assertEquals("RegisteredUserAdapter", computer.user.name);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testFieldAnnotationTakesPrecedenceOverRegisteredTypeAdapter() {
|
public void testFieldAnnotationTakesPrecedenceOverRegisteredTypeAdapter() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.setLenient()
|
.setLenient()
|
||||||
|
@ -78,6 +84,7 @@ public final class JsonAdapterAnnotationOnFieldsTest extends TestCase {
|
||||||
assertEquals("PartJsonFieldAnnotationAdapter", gadget.part.name);
|
assertEquals("PartJsonFieldAnnotationAdapter", gadget.part.name);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testFieldAnnotationTakesPrecedenceOverClassAnnotation() {
|
public void testFieldAnnotationTakesPrecedenceOverClassAnnotation() {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
String json = gson.toJson(new Computer2(new User("Inderjeet Singh")));
|
String json = gson.toJson(new Computer2(new User("Inderjeet Singh")));
|
||||||
|
@ -188,6 +195,7 @@ public final class JsonAdapterAnnotationOnFieldsTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testJsonAdapterInvokedOnlyForAnnotatedFields() {
|
public void testJsonAdapterInvokedOnlyForAnnotatedFields() {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
String json = "{'part1':'name','part2':{'name':'name2'}}";
|
String json = "{'part1':'name','part2':{'name':'name2'}}";
|
||||||
|
@ -205,6 +213,7 @@ public final class JsonAdapterAnnotationOnFieldsTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testJsonAdapterWrappedInNullSafeAsRequested() {
|
public void testJsonAdapterWrappedInNullSafeAsRequested() {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
String fromJson = "{'part':null}";
|
String fromJson = "{'part':null}";
|
||||||
|
@ -226,6 +235,7 @@ public final class JsonAdapterAnnotationOnFieldsTest extends TestCase {
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Regression test contributed through https://github.com/google/gson/issues/831 */
|
/** Regression test contributed through https://github.com/google/gson/issues/831 */
|
||||||
|
@Test
|
||||||
public void testNonPrimitiveFieldAnnotationTakesPrecedenceOverDefault() {
|
public void testNonPrimitiveFieldAnnotationTakesPrecedenceOverDefault() {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
String json = gson.toJson(new GadgetWithOptionalPart(new Part("foo")));
|
String json = gson.toJson(new GadgetWithOptionalPart(new Part("foo")));
|
||||||
|
@ -235,6 +245,7 @@ public final class JsonAdapterAnnotationOnFieldsTest extends TestCase {
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Regression test contributed through https://github.com/google/gson/issues/831 */
|
/** Regression test contributed through https://github.com/google/gson/issues/831 */
|
||||||
|
@Test
|
||||||
public void testPrimitiveFieldAnnotationTakesPrecedenceOverDefault() {
|
public void testPrimitiveFieldAnnotationTakesPrecedenceOverDefault() {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
String json = gson.toJson(new GadgetWithPrimitivePart(42));
|
String json = gson.toJson(new GadgetWithPrimitivePart(42));
|
||||||
|
@ -274,6 +285,7 @@ public final class JsonAdapterAnnotationOnFieldsTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testFieldAnnotationWorksForParameterizedType() {
|
public void testFieldAnnotationWorksForParameterizedType() {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
String json = gson.toJson(new Gizmo2(Arrays.asList(new Part("Part"))));
|
String json = gson.toJson(new Gizmo2(Arrays.asList(new Part("Part"))));
|
||||||
|
|
|
@ -16,7 +16,9 @@
|
||||||
|
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
import java.lang.reflect.Type;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertNull;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.JsonDeserializationContext;
|
import com.google.gson.JsonDeserializationContext;
|
||||||
|
@ -27,15 +29,16 @@ import com.google.gson.JsonPrimitive;
|
||||||
import com.google.gson.JsonSerializationContext;
|
import com.google.gson.JsonSerializationContext;
|
||||||
import com.google.gson.JsonSerializer;
|
import com.google.gson.JsonSerializer;
|
||||||
import com.google.gson.annotations.JsonAdapter;
|
import com.google.gson.annotations.JsonAdapter;
|
||||||
|
import java.lang.reflect.Type;
|
||||||
import junit.framework.TestCase;
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Functional tests for the {@link JsonAdapter} annotation on fields where the value is of
|
* Functional tests for the {@link JsonAdapter} annotation on fields where the value is of
|
||||||
* type {@link JsonSerializer} or {@link JsonDeserializer}.
|
* type {@link JsonSerializer} or {@link JsonDeserializer}.
|
||||||
*/
|
*/
|
||||||
public final class JsonAdapterSerializerDeserializerTest extends TestCase {
|
public final class JsonAdapterSerializerDeserializerTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testJsonSerializerDeserializerBasedJsonAdapterOnFields() {
|
public void testJsonSerializerDeserializerBasedJsonAdapterOnFields() {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
String json = gson.toJson(new Computer(new User("Inderjeet Singh"), null, new User("Jesse Wilson")));
|
String json = gson.toJson(new Computer(new User("Inderjeet Singh"), null, new User("Jesse Wilson")));
|
||||||
|
@ -90,6 +93,7 @@ public final class JsonAdapterSerializerDeserializerTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testJsonSerializerDeserializerBasedJsonAdapterOnClass() {
|
public void testJsonSerializerDeserializerBasedJsonAdapterOnClass() {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
String json = gson.toJson(new Computer2(new User2("Inderjeet Singh")));
|
String json = gson.toJson(new Computer2(new User2("Inderjeet Singh")));
|
||||||
|
@ -125,6 +129,7 @@ public final class JsonAdapterSerializerDeserializerTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDifferentJsonAdaptersForGenericFieldsOfSameRawType() {
|
public void testDifferentJsonAdaptersForGenericFieldsOfSameRawType() {
|
||||||
Container c = new Container("Foo", 10);
|
Container c = new Container("Foo", 10);
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
|
@ -162,6 +167,7 @@ public final class JsonAdapterSerializerDeserializerTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testJsonAdapterNullSafe() {
|
public void testJsonAdapterNullSafe() {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
String json = gson.toJson(new Computer3(null, null));
|
String json = gson.toJson(new Computer3(null, null));
|
||||||
|
|
|
@ -16,18 +16,20 @@
|
||||||
|
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.fail;
|
||||||
|
|
||||||
import com.google.gson.*;
|
import com.google.gson.*;
|
||||||
import com.google.gson.common.TestTypes.BagOfPrimitives;
|
import com.google.gson.common.TestTypes.BagOfPrimitives;
|
||||||
import com.google.gson.common.TestTypes.Nested;
|
import com.google.gson.common.TestTypes.Nested;
|
||||||
import com.google.gson.reflect.TypeToken;
|
import com.google.gson.reflect.TypeToken;
|
||||||
|
|
||||||
import junit.framework.TestCase;
|
|
||||||
|
|
||||||
import java.io.StringReader;
|
import java.io.StringReader;
|
||||||
import java.lang.reflect.Type;
|
import java.lang.reflect.Type;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Functional tests for that use JsonParser and related Gson methods
|
* Functional tests for that use JsonParser and related Gson methods
|
||||||
|
@ -35,15 +37,15 @@ import java.util.Map;
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
* @author Joel Leitch
|
* @author Joel Leitch
|
||||||
*/
|
*/
|
||||||
public class JsonParserTest extends TestCase {
|
public class JsonParserTest {
|
||||||
private Gson gson;
|
private Gson gson;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
gson = new Gson();
|
gson = new Gson();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testParseInvalidJson() {
|
public void testParseInvalidJson() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("[[]", Object[].class);
|
gson.fromJson("[[]", Object[].class);
|
||||||
|
@ -51,6 +53,7 @@ public class JsonParserTest extends TestCase {
|
||||||
} catch (JsonSyntaxException expected) { }
|
} catch (JsonSyntaxException expected) { }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserializingCustomTree() {
|
public void testDeserializingCustomTree() {
|
||||||
JsonObject obj = new JsonObject();
|
JsonObject obj = new JsonObject();
|
||||||
obj.addProperty("stringValue", "foo");
|
obj.addProperty("stringValue", "foo");
|
||||||
|
@ -60,6 +63,7 @@ public class JsonParserTest extends TestCase {
|
||||||
assertEquals("foo", target.stringValue);
|
assertEquals("foo", target.stringValue);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBadTypeForDeserializingCustomTree() {
|
public void testBadTypeForDeserializingCustomTree() {
|
||||||
JsonObject obj = new JsonObject();
|
JsonObject obj = new JsonObject();
|
||||||
obj.addProperty("stringValue", "foo");
|
obj.addProperty("stringValue", "foo");
|
||||||
|
@ -72,6 +76,7 @@ public class JsonParserTest extends TestCase {
|
||||||
} catch (JsonParseException expected) { }
|
} catch (JsonParseException expected) { }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBadFieldTypeForCustomDeserializerCustomTree() {
|
public void testBadFieldTypeForCustomDeserializerCustomTree() {
|
||||||
JsonArray array = new JsonArray();
|
JsonArray array = new JsonArray();
|
||||||
array.add(new JsonPrimitive("blah"));
|
array.add(new JsonPrimitive("blah"));
|
||||||
|
@ -86,6 +91,7 @@ public class JsonParserTest extends TestCase {
|
||||||
} catch (JsonParseException expected) { }
|
} catch (JsonParseException expected) { }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBadFieldTypeForDeserializingCustomTree() {
|
public void testBadFieldTypeForDeserializingCustomTree() {
|
||||||
JsonArray array = new JsonArray();
|
JsonArray array = new JsonArray();
|
||||||
array.add(new JsonPrimitive("blah"));
|
array.add(new JsonPrimitive("blah"));
|
||||||
|
@ -103,6 +109,7 @@ public class JsonParserTest extends TestCase {
|
||||||
} catch (JsonParseException expected) { }
|
} catch (JsonParseException expected) { }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testChangingCustomTreeAndDeserializing() {
|
public void testChangingCustomTreeAndDeserializing() {
|
||||||
StringReader json =
|
StringReader json =
|
||||||
new StringReader("{'stringValue':'no message','intValue':10,'longValue':20}");
|
new StringReader("{'stringValue':'no message','intValue':10,'longValue':20}");
|
||||||
|
@ -115,6 +122,7 @@ public class JsonParserTest extends TestCase {
|
||||||
assertEquals("fooBar", target.stringValue);
|
assertEquals("fooBar", target.stringValue);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testExtraCommasInArrays() {
|
public void testExtraCommasInArrays() {
|
||||||
Type type = new TypeToken<List<String>>() {}.getType();
|
Type type = new TypeToken<List<String>>() {}.getType();
|
||||||
assertEquals(Arrays.asList("a", "b"), gson.fromJson("[a,,b,,]", type));
|
assertEquals(Arrays.asList("a", "b"), gson.fromJson("[a,,b,,]", type));
|
||||||
|
@ -122,6 +130,7 @@ public class JsonParserTest extends TestCase {
|
||||||
assertEquals(Arrays.asList("a"), gson.fromJson("[a,]", type));
|
assertEquals(Arrays.asList("a"), gson.fromJson("[a,]", type));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testExtraCommasInMaps() {
|
public void testExtraCommasInMaps() {
|
||||||
Type type = new TypeToken<Map<String, String>>() {}.getType();
|
Type type = new TypeToken<Map<String, String>>() {}.getType();
|
||||||
try {
|
try {
|
||||||
|
|
|
@ -1,5 +1,10 @@
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
import static org.junit.Assert.fail;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.JsonElement;
|
import com.google.gson.JsonElement;
|
||||||
import com.google.gson.JsonObject;
|
import com.google.gson.JsonObject;
|
||||||
|
@ -8,7 +13,8 @@ import com.google.gson.common.TestTypes.BagOfPrimitives;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Map.Entry;
|
import java.util.Map.Entry;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import junit.framework.TestCase;
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Functional tests for {@link Gson#toJsonTree(Object)} and
|
* Functional tests for {@link Gson#toJsonTree(Object)} and
|
||||||
|
@ -17,15 +23,15 @@ import junit.framework.TestCase;
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
* @author Joel Leitch
|
* @author Joel Leitch
|
||||||
*/
|
*/
|
||||||
public class JsonTreeTest extends TestCase {
|
public class JsonTreeTest {
|
||||||
private Gson gson;
|
private Gson gson;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
gson = new Gson();
|
gson = new Gson();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testToJsonTree() {
|
public void testToJsonTree() {
|
||||||
BagOfPrimitives bag = new BagOfPrimitives(10L, 5, false, "foo");
|
BagOfPrimitives bag = new BagOfPrimitives(10L, 5, false, "foo");
|
||||||
JsonElement json = gson.toJsonTree(bag);
|
JsonElement json = gson.toJsonTree(bag);
|
||||||
|
@ -39,6 +45,7 @@ public class JsonTreeTest extends TestCase {
|
||||||
assertContains(obj, new JsonPrimitive("foo"));
|
assertContains(obj, new JsonPrimitive("foo"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testToJsonTreeObjectType() {
|
public void testToJsonTreeObjectType() {
|
||||||
SubTypeOfBagOfPrimitives bag = new SubTypeOfBagOfPrimitives(10L, 5, false, "foo", 1.4F);
|
SubTypeOfBagOfPrimitives bag = new SubTypeOfBagOfPrimitives(10L, 5, false, "foo", 1.4F);
|
||||||
JsonElement json = gson.toJsonTree(bag, BagOfPrimitives.class);
|
JsonElement json = gson.toJsonTree(bag, BagOfPrimitives.class);
|
||||||
|
@ -52,6 +59,7 @@ public class JsonTreeTest extends TestCase {
|
||||||
assertContains(obj, new JsonPrimitive("foo"));
|
assertContains(obj, new JsonPrimitive("foo"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testJsonTreeToString() {
|
public void testJsonTreeToString() {
|
||||||
SubTypeOfBagOfPrimitives bag = new SubTypeOfBagOfPrimitives(10L, 5, false, "foo", 1.4F);
|
SubTypeOfBagOfPrimitives bag = new SubTypeOfBagOfPrimitives(10L, 5, false, "foo", 1.4F);
|
||||||
String json1 = gson.toJson(bag);
|
String json1 = gson.toJson(bag);
|
||||||
|
@ -60,6 +68,7 @@ public class JsonTreeTest extends TestCase {
|
||||||
assertEquals(json1, json2);
|
assertEquals(json1, json2);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testJsonTreeNull() {
|
public void testJsonTreeNull() {
|
||||||
BagOfPrimitives bag = new BagOfPrimitives(10L, 5, false, null);
|
BagOfPrimitives bag = new BagOfPrimitives(10L, 5, false, null);
|
||||||
JsonObject jsonElement = (JsonObject) gson.toJsonTree(bag, BagOfPrimitives.class);
|
JsonObject jsonElement = (JsonObject) gson.toJsonTree(bag, BagOfPrimitives.class);
|
||||||
|
|
|
@ -15,27 +15,29 @@
|
||||||
*/
|
*/
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
|
import static java.util.Collections.singletonList;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.GsonBuilder;
|
import com.google.gson.GsonBuilder;
|
||||||
import com.google.gson.reflect.TypeToken;
|
import com.google.gson.reflect.TypeToken;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import junit.framework.TestCase;
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
import static java.util.Collections.singletonList;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Functional tests for leniency option.
|
* Functional tests for leniency option.
|
||||||
*/
|
*/
|
||||||
public class LeniencyTest extends TestCase {
|
public class LeniencyTest {
|
||||||
|
|
||||||
private Gson gson;
|
private Gson gson;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
gson = new Gson();
|
gson = new Gson();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testLenientFromJson() {
|
public void testLenientFromJson() {
|
||||||
List<String> json = gson.fromJson(""
|
List<String> json = gson.fromJson(""
|
||||||
+ "[ # One!\n"
|
+ "[ # One!\n"
|
||||||
|
|
|
@ -16,6 +16,9 @@
|
||||||
|
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.fail;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.GsonBuilder;
|
import com.google.gson.GsonBuilder;
|
||||||
import com.google.gson.JsonSyntaxException;
|
import com.google.gson.JsonSyntaxException;
|
||||||
|
@ -24,10 +27,12 @@ import java.lang.reflect.Type;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import junit.framework.TestCase;
|
import org.junit.Ignore;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
public class MapAsArrayTypeAdapterTest extends TestCase {
|
public class MapAsArrayTypeAdapterTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSerializeComplexMapWithTypeAdapter() {
|
public void testSerializeComplexMapWithTypeAdapter() {
|
||||||
Type type = new TypeToken<Map<Point, String>>() {}.getType();
|
Type type = new TypeToken<Map<Point, String>>() {}.getType();
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
|
@ -53,6 +58,8 @@ public class MapAsArrayTypeAdapterTest extends TestCase {
|
||||||
new TypeToken<Map<String, Boolean>>() {}.getType()));
|
new TypeToken<Map<String, Boolean>>() {}.getType()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@Ignore
|
||||||
public void disabled_testTwoTypesCollapseToOneSerialize() {
|
public void disabled_testTwoTypesCollapseToOneSerialize() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.enableComplexMapKeySerialization()
|
.enableComplexMapKeySerialization()
|
||||||
|
@ -68,6 +75,7 @@ public class MapAsArrayTypeAdapterTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testTwoTypesCollapseToOneDeserialize() {
|
public void testTwoTypesCollapseToOneDeserialize() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.enableComplexMapKeySerialization()
|
.enableComplexMapKeySerialization()
|
||||||
|
@ -81,6 +89,7 @@ public class MapAsArrayTypeAdapterTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testMultipleEnableComplexKeyRegistrationHasNoEffect() throws Exception {
|
public void testMultipleEnableComplexKeyRegistrationHasNoEffect() throws Exception {
|
||||||
Type type = new TypeToken<Map<Point, String>>() {}.getType();
|
Type type = new TypeToken<Map<Point, String>>() {}.getType();
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
|
@ -96,6 +105,7 @@ public class MapAsArrayTypeAdapterTest extends TestCase {
|
||||||
assertEquals(original, gson.<Map<Point, String>>fromJson(json, type));
|
assertEquals(original, gson.<Map<Point, String>>fromJson(json, type));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testMapWithTypeVariableSerialization() {
|
public void testMapWithTypeVariableSerialization() {
|
||||||
Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
|
Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
|
||||||
PointWithProperty<Point> map = new PointWithProperty<>();
|
PointWithProperty<Point> map = new PointWithProperty<>();
|
||||||
|
@ -105,6 +115,7 @@ public class MapAsArrayTypeAdapterTest extends TestCase {
|
||||||
assertEquals("{\"map\":[[{\"x\":2,\"y\":3},{\"x\":4,\"y\":5}]]}", json);
|
assertEquals("{\"map\":[[{\"x\":2,\"y\":3},{\"x\":4,\"y\":5}]]}", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testMapWithTypeVariableDeserialization() {
|
public void testMapWithTypeVariableDeserialization() {
|
||||||
Gson gson = new GsonBuilder().setLenient().enableComplexMapKeySerialization().create();
|
Gson gson = new GsonBuilder().setLenient().enableComplexMapKeySerialization().create();
|
||||||
String json = "{map:[[{x:2,y:3},{x:4,y:5}]]}";
|
String json = "{map:[[{x:2,y:3},{x:4,y:5}]]}";
|
||||||
|
|
|
@ -16,6 +16,12 @@
|
||||||
|
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertNull;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
import static org.junit.Assert.fail;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.GsonBuilder;
|
import com.google.gson.GsonBuilder;
|
||||||
import com.google.gson.InstanceCreator;
|
import com.google.gson.InstanceCreator;
|
||||||
|
@ -41,7 +47,8 @@ import java.util.concurrent.ConcurrentHashMap;
|
||||||
import java.util.concurrent.ConcurrentMap;
|
import java.util.concurrent.ConcurrentMap;
|
||||||
import java.util.concurrent.ConcurrentNavigableMap;
|
import java.util.concurrent.ConcurrentNavigableMap;
|
||||||
import java.util.concurrent.ConcurrentSkipListMap;
|
import java.util.concurrent.ConcurrentSkipListMap;
|
||||||
import junit.framework.TestCase;
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Functional test for Json serialization and deserialization for Maps
|
* Functional test for Json serialization and deserialization for Maps
|
||||||
|
@ -49,15 +56,15 @@ import junit.framework.TestCase;
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
* @author Joel Leitch
|
* @author Joel Leitch
|
||||||
*/
|
*/
|
||||||
public class MapTest extends TestCase {
|
public class MapTest {
|
||||||
private Gson gson;
|
private Gson gson;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
gson = new Gson();
|
gson = new Gson();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testMapSerialization() {
|
public void testMapSerialization() {
|
||||||
Map<String, Integer> map = new LinkedHashMap<>();
|
Map<String, Integer> map = new LinkedHashMap<>();
|
||||||
map.put("a", 1);
|
map.put("a", 1);
|
||||||
|
@ -68,6 +75,7 @@ public class MapTest extends TestCase {
|
||||||
assertTrue(json.contains("\"b\":2"));
|
assertTrue(json.contains("\"b\":2"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testMapDeserialization() {
|
public void testMapDeserialization() {
|
||||||
String json = "{\"a\":1,\"b\":2}";
|
String json = "{\"a\":1,\"b\":2}";
|
||||||
Type typeOfMap = new TypeToken<Map<String,Integer>>(){}.getType();
|
Type typeOfMap = new TypeToken<Map<String,Integer>>(){}.getType();
|
||||||
|
@ -76,6 +84,7 @@ public class MapTest extends TestCase {
|
||||||
assertEquals(2, target.get("b").intValue());
|
assertEquals(2, target.get("b").intValue());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testMapDuplicateKeyDeserialization() {
|
public void testMapDuplicateKeyDeserialization() {
|
||||||
Gson gsonWithDuplicateKeys = new GsonBuilder()
|
Gson gsonWithDuplicateKeys = new GsonBuilder()
|
||||||
.enableDuplicateMapKeyDeserialization()
|
.enableDuplicateMapKeyDeserialization()
|
||||||
|
@ -87,6 +96,7 @@ public class MapTest extends TestCase {
|
||||||
assertEquals(3, target.get("b").intValue());
|
assertEquals(3, target.get("b").intValue());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testObjectMapSerialization() {
|
public void testObjectMapSerialization() {
|
||||||
Map<String, Object> map = new LinkedHashMap<>();
|
Map<String, Object> map = new LinkedHashMap<>();
|
||||||
map.put("a", 1);
|
map.put("a", 1);
|
||||||
|
@ -96,6 +106,7 @@ public class MapTest extends TestCase {
|
||||||
assertTrue(json.contains("\"b\":\"string\""));
|
assertTrue(json.contains("\"b\":\"string\""));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testMapSerializationEmpty() {
|
public void testMapSerializationEmpty() {
|
||||||
Map<String, Integer> map = new LinkedHashMap<>();
|
Map<String, Integer> map = new LinkedHashMap<>();
|
||||||
Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
|
Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
|
||||||
|
@ -103,12 +114,14 @@ public class MapTest extends TestCase {
|
||||||
assertEquals("{}", json);
|
assertEquals("{}", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testMapDeserializationEmpty() {
|
public void testMapDeserializationEmpty() {
|
||||||
Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
|
Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
|
||||||
Map<String, Integer> map = gson.fromJson("{}", typeOfMap);
|
Map<String, Integer> map = gson.fromJson("{}", typeOfMap);
|
||||||
assertTrue(map.isEmpty());
|
assertTrue(map.isEmpty());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testMapSerializationWithNullValue() {
|
public void testMapSerializationWithNullValue() {
|
||||||
Map<String, Integer> map = new LinkedHashMap<>();
|
Map<String, Integer> map = new LinkedHashMap<>();
|
||||||
map.put("abc", null);
|
map.put("abc", null);
|
||||||
|
@ -119,6 +132,7 @@ public class MapTest extends TestCase {
|
||||||
assertEquals("{}", json);
|
assertEquals("{}", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testMapDeserializationWithNullValue() {
|
public void testMapDeserializationWithNullValue() {
|
||||||
Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
|
Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
|
||||||
Map<String, Integer> map = gson.fromJson("{\"abc\":null}", typeOfMap);
|
Map<String, Integer> map = gson.fromJson("{\"abc\":null}", typeOfMap);
|
||||||
|
@ -126,6 +140,7 @@ public class MapTest extends TestCase {
|
||||||
assertNull(map.get("abc"));
|
assertNull(map.get("abc"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testMapSerializationWithNullValueButSerializeNulls() {
|
public void testMapSerializationWithNullValueButSerializeNulls() {
|
||||||
gson = new GsonBuilder().serializeNulls().create();
|
gson = new GsonBuilder().serializeNulls().create();
|
||||||
Map<String, Integer> map = new LinkedHashMap<>();
|
Map<String, Integer> map = new LinkedHashMap<>();
|
||||||
|
@ -136,6 +151,7 @@ public class MapTest extends TestCase {
|
||||||
assertEquals("{\"abc\":null}", json);
|
assertEquals("{\"abc\":null}", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testMapSerializationWithNullKey() {
|
public void testMapSerializationWithNullKey() {
|
||||||
Map<String, Integer> map = new LinkedHashMap<>();
|
Map<String, Integer> map = new LinkedHashMap<>();
|
||||||
map.put(null, 123);
|
map.put(null, 123);
|
||||||
|
@ -145,6 +161,7 @@ public class MapTest extends TestCase {
|
||||||
assertEquals("{\"null\":123}", json);
|
assertEquals("{\"null\":123}", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testMapDeserializationWithNullKey() {
|
public void testMapDeserializationWithNullKey() {
|
||||||
Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
|
Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
|
||||||
Map<String, Integer> map = gson.fromJson("{\"null\":123}", typeOfMap);
|
Map<String, Integer> map = gson.fromJson("{\"null\":123}", typeOfMap);
|
||||||
|
@ -158,6 +175,7 @@ public class MapTest extends TestCase {
|
||||||
assertNull(map.get(null));
|
assertNull(map.get(null));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testMapSerializationWithIntegerKeys() {
|
public void testMapSerializationWithIntegerKeys() {
|
||||||
Map<Integer, String> map = new LinkedHashMap<>();
|
Map<Integer, String> map = new LinkedHashMap<>();
|
||||||
map.put(123, "456");
|
map.put(123, "456");
|
||||||
|
@ -167,6 +185,7 @@ public class MapTest extends TestCase {
|
||||||
assertEquals("{\"123\":\"456\"}", json);
|
assertEquals("{\"123\":\"456\"}", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testMapDeserializationWithIntegerKeys() {
|
public void testMapDeserializationWithIntegerKeys() {
|
||||||
Type typeOfMap = new TypeToken<Map<Integer, String>>() {}.getType();
|
Type typeOfMap = new TypeToken<Map<Integer, String>>() {}.getType();
|
||||||
Map<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap);
|
Map<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap);
|
||||||
|
@ -175,6 +194,7 @@ public class MapTest extends TestCase {
|
||||||
assertEquals("456", map.get(123));
|
assertEquals("456", map.get(123));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testMapDeserializationWithUnquotedIntegerKeys() {
|
public void testMapDeserializationWithUnquotedIntegerKeys() {
|
||||||
Type typeOfMap = new TypeToken<Map<Integer, String>>() {}.getType();
|
Type typeOfMap = new TypeToken<Map<Integer, String>>() {}.getType();
|
||||||
Map<Integer, String> map = gson.fromJson("{123:\"456\"}", typeOfMap);
|
Map<Integer, String> map = gson.fromJson("{123:\"456\"}", typeOfMap);
|
||||||
|
@ -183,6 +203,7 @@ public class MapTest extends TestCase {
|
||||||
assertEquals("456", map.get(123));
|
assertEquals("456", map.get(123));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testMapDeserializationWithLongKeys() {
|
public void testMapDeserializationWithLongKeys() {
|
||||||
long longValue = 9876543210L;
|
long longValue = 9876543210L;
|
||||||
String json = String.format("{\"%d\":\"456\"}", longValue);
|
String json = String.format("{\"%d\":\"456\"}", longValue);
|
||||||
|
@ -193,6 +214,7 @@ public class MapTest extends TestCase {
|
||||||
assertEquals("456", map.get(longValue));
|
assertEquals("456", map.get(longValue));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testMapDeserializationWithUnquotedLongKeys() {
|
public void testMapDeserializationWithUnquotedLongKeys() {
|
||||||
long longKey = 9876543210L;
|
long longKey = 9876543210L;
|
||||||
String json = String.format("{%d:\"456\"}", longKey);
|
String json = String.format("{%d:\"456\"}", longKey);
|
||||||
|
@ -203,6 +225,7 @@ public class MapTest extends TestCase {
|
||||||
assertEquals("456", map.get(longKey));
|
assertEquals("456", map.get(longKey));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testHashMapDeserialization() throws Exception {
|
public void testHashMapDeserialization() throws Exception {
|
||||||
Type typeOfMap = new TypeToken<HashMap<Integer, String>>() {}.getType();
|
Type typeOfMap = new TypeToken<HashMap<Integer, String>>() {}.getType();
|
||||||
HashMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap);
|
HashMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap);
|
||||||
|
@ -211,6 +234,7 @@ public class MapTest extends TestCase {
|
||||||
assertEquals("456", map.get(123));
|
assertEquals("456", map.get(123));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSortedMap() throws Exception {
|
public void testSortedMap() throws Exception {
|
||||||
Type typeOfMap = new TypeToken<SortedMap<Integer, String>>() {}.getType();
|
Type typeOfMap = new TypeToken<SortedMap<Integer, String>>() {}.getType();
|
||||||
SortedMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap);
|
SortedMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap);
|
||||||
|
@ -219,6 +243,7 @@ public class MapTest extends TestCase {
|
||||||
assertEquals("456", map.get(123));
|
assertEquals("456", map.get(123));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testConcurrentMap() throws Exception {
|
public void testConcurrentMap() throws Exception {
|
||||||
Type typeOfMap = new TypeToken<ConcurrentMap<Integer, String>>() {}.getType();
|
Type typeOfMap = new TypeToken<ConcurrentMap<Integer, String>>() {}.getType();
|
||||||
ConcurrentMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap);
|
ConcurrentMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap);
|
||||||
|
@ -229,6 +254,7 @@ public class MapTest extends TestCase {
|
||||||
assertEquals("{\"123\":\"456\"}", json);
|
assertEquals("{\"123\":\"456\"}", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testConcurrentHashMap() throws Exception {
|
public void testConcurrentHashMap() throws Exception {
|
||||||
Type typeOfMap = new TypeToken<ConcurrentHashMap<Integer, String>>() {}.getType();
|
Type typeOfMap = new TypeToken<ConcurrentHashMap<Integer, String>>() {}.getType();
|
||||||
ConcurrentHashMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap);
|
ConcurrentHashMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap);
|
||||||
|
@ -239,6 +265,7 @@ public class MapTest extends TestCase {
|
||||||
assertEquals("{\"123\":\"456\"}", json);
|
assertEquals("{\"123\":\"456\"}", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testConcurrentNavigableMap() throws Exception {
|
public void testConcurrentNavigableMap() throws Exception {
|
||||||
Type typeOfMap = new TypeToken<ConcurrentNavigableMap<Integer, String>>() {}.getType();
|
Type typeOfMap = new TypeToken<ConcurrentNavigableMap<Integer, String>>() {}.getType();
|
||||||
ConcurrentNavigableMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap);
|
ConcurrentNavigableMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap);
|
||||||
|
@ -249,6 +276,7 @@ public class MapTest extends TestCase {
|
||||||
assertEquals("{\"123\":\"456\"}", json);
|
assertEquals("{\"123\":\"456\"}", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testConcurrentSkipListMap() throws Exception {
|
public void testConcurrentSkipListMap() throws Exception {
|
||||||
Type typeOfMap = new TypeToken<ConcurrentSkipListMap<Integer, String>>() {}.getType();
|
Type typeOfMap = new TypeToken<ConcurrentSkipListMap<Integer, String>>() {}.getType();
|
||||||
ConcurrentSkipListMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap);
|
ConcurrentSkipListMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap);
|
||||||
|
@ -259,6 +287,7 @@ public class MapTest extends TestCase {
|
||||||
assertEquals("{\"123\":\"456\"}", json);
|
assertEquals("{\"123\":\"456\"}", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testParameterizedMapSubclassSerialization() {
|
public void testParameterizedMapSubclassSerialization() {
|
||||||
MyParameterizedMap<String, String> map = new MyParameterizedMap<>(10);
|
MyParameterizedMap<String, String> map = new MyParameterizedMap<>(10);
|
||||||
map.put("a", "b");
|
map.put("a", "b");
|
||||||
|
@ -275,6 +304,7 @@ public class MapTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testMapSubclassSerialization() {
|
public void testMapSubclassSerialization() {
|
||||||
MyMap map = new MyMap();
|
MyMap map = new MyMap();
|
||||||
map.put("a", "b");
|
map.put("a", "b");
|
||||||
|
@ -282,6 +312,7 @@ public class MapTest extends TestCase {
|
||||||
assertTrue(json.contains("\"a\":\"b\""));
|
assertTrue(json.contains("\"a\":\"b\""));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testMapStandardSubclassDeserialization() {
|
public void testMapStandardSubclassDeserialization() {
|
||||||
String json = "{a:'1',b:'2'}";
|
String json = "{a:'1',b:'2'}";
|
||||||
Type type = new TypeToken<LinkedHashMap<String, String>>() {}.getType();
|
Type type = new TypeToken<LinkedHashMap<String, String>>() {}.getType();
|
||||||
|
@ -290,6 +321,7 @@ public class MapTest extends TestCase {
|
||||||
assertEquals("2", map.get("b"));
|
assertEquals("2", map.get("b"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testMapSubclassDeserialization() {
|
public void testMapSubclassDeserialization() {
|
||||||
Gson gson = new GsonBuilder().registerTypeAdapter(MyMap.class, new InstanceCreator<MyMap>() {
|
Gson gson = new GsonBuilder().registerTypeAdapter(MyMap.class, new InstanceCreator<MyMap>() {
|
||||||
@Override public MyMap createInstance(Type type) {
|
@Override public MyMap createInstance(Type type) {
|
||||||
|
@ -302,6 +334,7 @@ public class MapTest extends TestCase {
|
||||||
assertEquals("2", map.get("b"));
|
assertEquals("2", map.get("b"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testCustomSerializerForSpecificMapType() {
|
public void testCustomSerializerForSpecificMapType() {
|
||||||
Type type = $Gson$Types.newParameterizedTypeWithOwner(
|
Type type = $Gson$Types.newParameterizedTypeWithOwner(
|
||||||
null, Map.class, String.class, Long.class);
|
null, Map.class, String.class, Long.class);
|
||||||
|
@ -335,6 +368,7 @@ public class MapTest extends TestCase {
|
||||||
/**
|
/**
|
||||||
* Created in response to http://code.google.com/p/google-gson/issues/detail?id=99
|
* Created in response to http://code.google.com/p/google-gson/issues/detail?id=99
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testMapSerializationWithNullValues() {
|
public void testMapSerializationWithNullValues() {
|
||||||
ClassWithAMap target = new ClassWithAMap();
|
ClassWithAMap target = new ClassWithAMap();
|
||||||
target.map.put("name1", null);
|
target.map.put("name1", null);
|
||||||
|
@ -347,6 +381,7 @@ public class MapTest extends TestCase {
|
||||||
/**
|
/**
|
||||||
* Created in response to http://code.google.com/p/google-gson/issues/detail?id=99
|
* Created in response to http://code.google.com/p/google-gson/issues/detail?id=99
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testMapSerializationWithNullValuesSerialized() {
|
public void testMapSerializationWithNullValuesSerialized() {
|
||||||
Gson gson = new GsonBuilder().serializeNulls().create();
|
Gson gson = new GsonBuilder().serializeNulls().create();
|
||||||
ClassWithAMap target = new ClassWithAMap();
|
ClassWithAMap target = new ClassWithAMap();
|
||||||
|
@ -357,6 +392,7 @@ public class MapTest extends TestCase {
|
||||||
assertTrue(json.contains("name2"));
|
assertTrue(json.contains("name2"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testMapSerializationWithWildcardValues() {
|
public void testMapSerializationWithWildcardValues() {
|
||||||
Map<String, ? extends Collection<? extends Integer>> map = new LinkedHashMap<>();
|
Map<String, ? extends Collection<? extends Integer>> map = new LinkedHashMap<>();
|
||||||
map.put("test", null);
|
map.put("test", null);
|
||||||
|
@ -367,6 +403,7 @@ public class MapTest extends TestCase {
|
||||||
assertEquals("{}", json);
|
assertEquals("{}", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testMapDeserializationWithWildcardValues() {
|
public void testMapDeserializationWithWildcardValues() {
|
||||||
Type typeOfMap = new TypeToken<Map<String, ? extends Long>>() {}.getType();
|
Type typeOfMap = new TypeToken<Map<String, ? extends Long>>() {}.getType();
|
||||||
Map<String, ? extends Long> map = gson.fromJson("{\"test\":123}", typeOfMap);
|
Map<String, ? extends Long> map = gson.fromJson("{\"test\":123}", typeOfMap);
|
||||||
|
@ -385,6 +422,7 @@ public class MapTest extends TestCase {
|
||||||
/**
|
/**
|
||||||
* From bug report http://code.google.com/p/google-gson/issues/detail?id=95
|
* From bug report http://code.google.com/p/google-gson/issues/detail?id=95
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testMapOfMapSerialization() {
|
public void testMapOfMapSerialization() {
|
||||||
Map<String, Map<String, String>> map = new HashMap<>();
|
Map<String, Map<String, String>> map = new HashMap<>();
|
||||||
Map<String, String> nestedMap = new HashMap<>();
|
Map<String, String> nestedMap = new HashMap<>();
|
||||||
|
@ -400,6 +438,7 @@ public class MapTest extends TestCase {
|
||||||
/**
|
/**
|
||||||
* From bug report http://code.google.com/p/google-gson/issues/detail?id=95
|
* From bug report http://code.google.com/p/google-gson/issues/detail?id=95
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testMapOfMapDeserialization() {
|
public void testMapOfMapDeserialization() {
|
||||||
String json = "{nestedMap:{'2':'2','1':'1'}}";
|
String json = "{nestedMap:{'2':'2','1':'1'}}";
|
||||||
Type type = new TypeToken<Map<String, Map<String, String>>>(){}.getType();
|
Type type = new TypeToken<Map<String, Map<String, String>>>(){}.getType();
|
||||||
|
@ -412,6 +451,7 @@ public class MapTest extends TestCase {
|
||||||
/**
|
/**
|
||||||
* From bug report http://code.google.com/p/google-gson/issues/detail?id=178
|
* From bug report http://code.google.com/p/google-gson/issues/detail?id=178
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testMapWithQuotes() {
|
public void testMapWithQuotes() {
|
||||||
Map<String, String> map = new HashMap<>();
|
Map<String, String> map = new HashMap<>();
|
||||||
map.put("a\"b", "c\"d");
|
map.put("a\"b", "c\"d");
|
||||||
|
@ -422,6 +462,7 @@ public class MapTest extends TestCase {
|
||||||
/**
|
/**
|
||||||
* From issue 227.
|
* From issue 227.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testWriteMapsWithEmptyStringKey() {
|
public void testWriteMapsWithEmptyStringKey() {
|
||||||
Map<String, Boolean> map = new HashMap<>();
|
Map<String, Boolean> map = new HashMap<>();
|
||||||
map.put("", true);
|
map.put("", true);
|
||||||
|
@ -429,6 +470,7 @@ public class MapTest extends TestCase {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testReadMapsWithEmptyStringKey() {
|
public void testReadMapsWithEmptyStringKey() {
|
||||||
Map<String, Boolean> map = gson.fromJson("{\"\":true}", new TypeToken<Map<String, Boolean>>() {}.getType());
|
Map<String, Boolean> map = gson.fromJson("{\"\":true}", new TypeToken<Map<String, Boolean>>() {}.getType());
|
||||||
assertEquals(Boolean.TRUE, map.get(""));
|
assertEquals(Boolean.TRUE, map.get(""));
|
||||||
|
@ -437,6 +479,7 @@ public class MapTest extends TestCase {
|
||||||
/**
|
/**
|
||||||
* From bug report http://code.google.com/p/google-gson/issues/detail?id=204
|
* From bug report http://code.google.com/p/google-gson/issues/detail?id=204
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testSerializeMaps() {
|
public void testSerializeMaps() {
|
||||||
Map<String, Object> map = new LinkedHashMap<>();
|
Map<String, Object> map = new LinkedHashMap<>();
|
||||||
map.put("a", 12);
|
map.put("a", 12);
|
||||||
|
@ -465,6 +508,7 @@ public class MapTest extends TestCase {
|
||||||
new Gson().toJson(map));
|
new Gson().toJson(map));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public final void testInterfaceTypeMap() {
|
public final void testInterfaceTypeMap() {
|
||||||
MapClass element = new MapClass();
|
MapClass element = new MapClass();
|
||||||
TestTypes.Sub subType = new TestTypes.Sub();
|
TestTypes.Sub subType = new TestTypes.Sub();
|
||||||
|
@ -486,6 +530,7 @@ public class MapTest extends TestCase {
|
||||||
assertEquals(expected, json);
|
assertEquals(expected, json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public final void testInterfaceTypeMapWithSerializer() {
|
public final void testInterfaceTypeMapWithSerializer() {
|
||||||
MapClass element = new MapClass();
|
MapClass element = new MapClass();
|
||||||
TestTypes.Sub subType = new TestTypes.Sub();
|
TestTypes.Sub subType = new TestTypes.Sub();
|
||||||
|
@ -520,6 +565,7 @@ public class MapTest extends TestCase {
|
||||||
assertEquals(expected, json);
|
assertEquals(expected, json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testGeneralMapField() throws Exception {
|
public void testGeneralMapField() throws Exception {
|
||||||
MapWithGeneralMapParameters map = new MapWithGeneralMapParameters();
|
MapWithGeneralMapParameters map = new MapWithGeneralMapParameters();
|
||||||
map.map.put("string", "testString");
|
map.map.put("string", "testString");
|
||||||
|
@ -536,6 +582,7 @@ public class MapTest extends TestCase {
|
||||||
assertEquals(expected, gson.toJson(map));
|
assertEquals(expected, gson.toJson(map));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testComplexKeysSerialization() {
|
public void testComplexKeysSerialization() {
|
||||||
Map<Point, String> map = new LinkedHashMap<>();
|
Map<Point, String> map = new LinkedHashMap<>();
|
||||||
map.put(new Point(2, 3), "a");
|
map.put(new Point(2, 3), "a");
|
||||||
|
@ -545,6 +592,7 @@ public class MapTest extends TestCase {
|
||||||
assertEquals(json, gson.toJson(map, Map.class));
|
assertEquals(json, gson.toJson(map, Map.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testComplexKeysDeserialization() {
|
public void testComplexKeysDeserialization() {
|
||||||
String json = "{'2,3':'a','5,7':'b'}";
|
String json = "{'2,3':'a','5,7':'b'}";
|
||||||
try {
|
try {
|
||||||
|
@ -554,6 +602,7 @@ public class MapTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testStringKeyDeserialization() {
|
public void testStringKeyDeserialization() {
|
||||||
String json = "{'2,3':'a','5,7':'b'}";
|
String json = "{'2,3':'a','5,7':'b'}";
|
||||||
Map<String, String> map = new LinkedHashMap<>();
|
Map<String, String> map = new LinkedHashMap<>();
|
||||||
|
@ -562,6 +611,7 @@ public class MapTest extends TestCase {
|
||||||
assertEquals(map, gson.fromJson(json, new TypeToken<Map<String, String>>() {}.getType()));
|
assertEquals(map, gson.fromJson(json, new TypeToken<Map<String, String>>() {}.getType()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNumberKeyDeserialization() {
|
public void testNumberKeyDeserialization() {
|
||||||
String json = "{'2.3':'a','5.7':'b'}";
|
String json = "{'2.3':'a','5.7':'b'}";
|
||||||
Map<Double, String> map = new LinkedHashMap<>();
|
Map<Double, String> map = new LinkedHashMap<>();
|
||||||
|
@ -570,6 +620,7 @@ public class MapTest extends TestCase {
|
||||||
assertEquals(map, gson.fromJson(json, new TypeToken<Map<Double, String>>() {}.getType()));
|
assertEquals(map, gson.fromJson(json, new TypeToken<Map<Double, String>>() {}.getType()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBooleanKeyDeserialization() {
|
public void testBooleanKeyDeserialization() {
|
||||||
String json = "{'true':'a','false':'b'}";
|
String json = "{'true':'a','false':'b'}";
|
||||||
Map<Boolean, String> map = new LinkedHashMap<>();
|
Map<Boolean, String> map = new LinkedHashMap<>();
|
||||||
|
@ -578,6 +629,7 @@ public class MapTest extends TestCase {
|
||||||
assertEquals(map, gson.fromJson(json, new TypeToken<Map<Boolean, String>>() {}.getType()));
|
assertEquals(map, gson.fromJson(json, new TypeToken<Map<Boolean, String>>() {}.getType()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testMapDeserializationWithDuplicateKeys() {
|
public void testMapDeserializationWithDuplicateKeys() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("{'a':1,'a':2}", new TypeToken<Map<String, Integer>>() {}.getType());
|
gson.fromJson("{'a':1,'a':2}", new TypeToken<Map<String, Integer>>() {}.getType());
|
||||||
|
@ -586,6 +638,7 @@ public class MapTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSerializeMapOfMaps() {
|
public void testSerializeMapOfMaps() {
|
||||||
Type type = new TypeToken<Map<String, Map<String, String>>>() {}.getType();
|
Type type = new TypeToken<Map<String, Map<String, String>>>() {}.getType();
|
||||||
Map<String, Map<String, String>> map = newMap(
|
Map<String, Map<String, String>> map = newMap(
|
||||||
|
@ -595,6 +648,7 @@ public class MapTest extends TestCase {
|
||||||
gson.toJson(map, type).replace('"', '\''));
|
gson.toJson(map, type).replace('"', '\''));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeerializeMapOfMaps() {
|
public void testDeerializeMapOfMaps() {
|
||||||
Type type = new TypeToken<Map<String, Map<String, String>>>() {}.getType();
|
Type type = new TypeToken<Map<String, Map<String, String>>>() {}.getType();
|
||||||
Map<String, Map<String, String>> map = newMap(
|
Map<String, Map<String, String>> map = newMap(
|
||||||
|
@ -611,6 +665,7 @@ public class MapTest extends TestCase {
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testMapNamePromotionWithJsonElementReader() {
|
public void testMapNamePromotionWithJsonElementReader() {
|
||||||
String json = "{'2.3':'a'}";
|
String json = "{'2.3':'a'}";
|
||||||
Map<Double, String> map = new LinkedHashMap<>();
|
Map<Double, String> map = new LinkedHashMap<>();
|
||||||
|
|
|
@ -16,15 +16,19 @@
|
||||||
|
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertNull;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.JsonObject;
|
import com.google.gson.JsonObject;
|
||||||
|
|
||||||
import junit.framework.TestCase;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests for Gson serialization of a sub-class object while encountering a base-class type
|
* Tests for Gson serialization of a sub-class object while encountering a base-class type
|
||||||
|
@ -32,15 +36,15 @@ import java.util.Map;
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("unused")
|
@SuppressWarnings("unused")
|
||||||
public class MoreSpecificTypeSerializationTest extends TestCase {
|
public class MoreSpecificTypeSerializationTest {
|
||||||
private Gson gson;
|
private Gson gson;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
gson = new Gson();
|
gson = new Gson();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSubclassFields() {
|
public void testSubclassFields() {
|
||||||
ClassWithBaseFields target = new ClassWithBaseFields(new Sub(1, 2));
|
ClassWithBaseFields target = new ClassWithBaseFields(new Sub(1, 2));
|
||||||
String json = gson.toJson(target);
|
String json = gson.toJson(target);
|
||||||
|
@ -48,6 +52,7 @@ public class MoreSpecificTypeSerializationTest extends TestCase {
|
||||||
assertTrue(json.contains("\"s\":2"));
|
assertTrue(json.contains("\"s\":2"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testListOfSubclassFields() {
|
public void testListOfSubclassFields() {
|
||||||
Collection<Base> list = new ArrayList<>();
|
Collection<Base> list = new ArrayList<>();
|
||||||
list.add(new Base(1));
|
list.add(new Base(1));
|
||||||
|
@ -58,6 +63,7 @@ public class MoreSpecificTypeSerializationTest extends TestCase {
|
||||||
assertTrue(json, json.contains("{\"s\":3,\"b\":2}"));
|
assertTrue(json, json.contains("{\"s\":3,\"b\":2}"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testMapOfSubclassFields() {
|
public void testMapOfSubclassFields() {
|
||||||
Map<String, Base> map = new HashMap<>();
|
Map<String, Base> map = new HashMap<>();
|
||||||
map.put("base", new Base(1));
|
map.put("base", new Base(1));
|
||||||
|
@ -73,6 +79,7 @@ public class MoreSpecificTypeSerializationTest extends TestCase {
|
||||||
/**
|
/**
|
||||||
* For parameterized type, Gson ignores the more-specific type and sticks to the declared type
|
* For parameterized type, Gson ignores the more-specific type and sticks to the declared type
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testParameterizedSubclassFields() {
|
public void testParameterizedSubclassFields() {
|
||||||
ClassWithParameterizedBaseFields target = new ClassWithParameterizedBaseFields(
|
ClassWithParameterizedBaseFields target = new ClassWithParameterizedBaseFields(
|
||||||
new ParameterizedSub<>("one", "two"));
|
new ParameterizedSub<>("one", "two"));
|
||||||
|
@ -85,6 +92,7 @@ public class MoreSpecificTypeSerializationTest extends TestCase {
|
||||||
* For parameterized type in a List, Gson ignores the more-specific type and sticks to
|
* For parameterized type in a List, Gson ignores the more-specific type and sticks to
|
||||||
* the declared type
|
* the declared type
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testListOfParameterizedSubclassFields() {
|
public void testListOfParameterizedSubclassFields() {
|
||||||
Collection<ParameterizedBase<String>> list = new ArrayList<>();
|
Collection<ParameterizedBase<String>> list = new ArrayList<>();
|
||||||
list.add(new ParameterizedBase<>("one"));
|
list.add(new ParameterizedBase<>("one"));
|
||||||
|
@ -100,6 +108,7 @@ public class MoreSpecificTypeSerializationTest extends TestCase {
|
||||||
* For parameterized type in a map, Gson ignores the more-specific type and sticks to the
|
* For parameterized type in a map, Gson ignores the more-specific type and sticks to the
|
||||||
* declared type
|
* declared type
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testMapOfParameterizedSubclassFields() {
|
public void testMapOfParameterizedSubclassFields() {
|
||||||
Map<String, ParameterizedBase<String>> map = new HashMap<>();
|
Map<String, ParameterizedBase<String>> map = new HashMap<>();
|
||||||
map.put("base", new ParameterizedBase<>("one"));
|
map.put("base", new ParameterizedBase<>("one"));
|
||||||
|
|
|
@ -15,6 +15,9 @@
|
||||||
*/
|
*/
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.fail;
|
||||||
|
|
||||||
import com.google.gson.FieldNamingPolicy;
|
import com.google.gson.FieldNamingPolicy;
|
||||||
import com.google.gson.FieldNamingStrategy;
|
import com.google.gson.FieldNamingStrategy;
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
|
@ -22,10 +25,9 @@ import com.google.gson.GsonBuilder;
|
||||||
import com.google.gson.annotations.SerializedName;
|
import com.google.gson.annotations.SerializedName;
|
||||||
import com.google.gson.common.TestTypes.ClassWithSerializedNameFields;
|
import com.google.gson.common.TestTypes.ClassWithSerializedNameFields;
|
||||||
import com.google.gson.common.TestTypes.StringWrapper;
|
import com.google.gson.common.TestTypes.StringWrapper;
|
||||||
|
|
||||||
import junit.framework.TestCase;
|
|
||||||
|
|
||||||
import java.lang.reflect.Field;
|
import java.lang.reflect.Field;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Functional tests for naming policies.
|
* Functional tests for naming policies.
|
||||||
|
@ -33,15 +35,15 @@ import java.lang.reflect.Field;
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
* @author Joel Leitch
|
* @author Joel Leitch
|
||||||
*/
|
*/
|
||||||
public class NamingPolicyTest extends TestCase {
|
public class NamingPolicyTest {
|
||||||
private GsonBuilder builder;
|
private GsonBuilder builder;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
builder = new GsonBuilder();
|
builder = new GsonBuilder();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testGsonWithNonDefaultFieldNamingPolicySerialization() {
|
public void testGsonWithNonDefaultFieldNamingPolicySerialization() {
|
||||||
Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
|
Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
|
||||||
StringWrapper target = new StringWrapper("blah");
|
StringWrapper target = new StringWrapper("blah");
|
||||||
|
@ -49,6 +51,7 @@ public class NamingPolicyTest extends TestCase {
|
||||||
+ target.someConstantStringInstanceField + "\"}", gson.toJson(target));
|
+ target.someConstantStringInstanceField + "\"}", gson.toJson(target));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testGsonWithNonDefaultFieldNamingPolicyDeserialiation() {
|
public void testGsonWithNonDefaultFieldNamingPolicyDeserialiation() {
|
||||||
Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
|
Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
|
||||||
String target = "{\"SomeConstantStringInstanceField\":\"someValue\"}";
|
String target = "{\"SomeConstantStringInstanceField\":\"someValue\"}";
|
||||||
|
@ -56,6 +59,7 @@ public class NamingPolicyTest extends TestCase {
|
||||||
assertEquals("someValue", deserializedObject.someConstantStringInstanceField);
|
assertEquals("someValue", deserializedObject.someConstantStringInstanceField);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testGsonWithLowerCaseDashPolicySerialization() {
|
public void testGsonWithLowerCaseDashPolicySerialization() {
|
||||||
Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES).create();
|
Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES).create();
|
||||||
StringWrapper target = new StringWrapper("blah");
|
StringWrapper target = new StringWrapper("blah");
|
||||||
|
@ -63,6 +67,7 @@ public class NamingPolicyTest extends TestCase {
|
||||||
+ target.someConstantStringInstanceField + "\"}", gson.toJson(target));
|
+ target.someConstantStringInstanceField + "\"}", gson.toJson(target));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testGsonWithLowerCaseDotPolicySerialization() {
|
public void testGsonWithLowerCaseDotPolicySerialization() {
|
||||||
Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DOTS).create();
|
Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DOTS).create();
|
||||||
StringWrapper target = new StringWrapper("blah");
|
StringWrapper target = new StringWrapper("blah");
|
||||||
|
@ -70,6 +75,7 @@ public class NamingPolicyTest extends TestCase {
|
||||||
+ target.someConstantStringInstanceField + "\"}", gson.toJson(target));
|
+ target.someConstantStringInstanceField + "\"}", gson.toJson(target));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testGsonWithLowerCaseDotPolicyDeserialiation() {
|
public void testGsonWithLowerCaseDotPolicyDeserialiation() {
|
||||||
Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DOTS).create();
|
Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DOTS).create();
|
||||||
String target = "{\"some.constant.string.instance.field\":\"someValue\"}";
|
String target = "{\"some.constant.string.instance.field\":\"someValue\"}";
|
||||||
|
@ -77,6 +83,7 @@ public class NamingPolicyTest extends TestCase {
|
||||||
assertEquals("someValue", deserializedObject.someConstantStringInstanceField);
|
assertEquals("someValue", deserializedObject.someConstantStringInstanceField);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testGsonWithLowerCaseDashPolicyDeserialiation() {
|
public void testGsonWithLowerCaseDashPolicyDeserialiation() {
|
||||||
Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES).create();
|
Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES).create();
|
||||||
String target = "{\"some-constant-string-instance-field\":\"someValue\"}";
|
String target = "{\"some-constant-string-instance-field\":\"someValue\"}";
|
||||||
|
@ -84,6 +91,7 @@ public class NamingPolicyTest extends TestCase {
|
||||||
assertEquals("someValue", deserializedObject.someConstantStringInstanceField);
|
assertEquals("someValue", deserializedObject.someConstantStringInstanceField);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testGsonWithLowerCaseUnderscorePolicySerialization() {
|
public void testGsonWithLowerCaseUnderscorePolicySerialization() {
|
||||||
Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
|
Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
|
||||||
.create();
|
.create();
|
||||||
|
@ -92,6 +100,7 @@ public class NamingPolicyTest extends TestCase {
|
||||||
+ target.someConstantStringInstanceField + "\"}", gson.toJson(target));
|
+ target.someConstantStringInstanceField + "\"}", gson.toJson(target));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testGsonWithLowerCaseUnderscorePolicyDeserialiation() {
|
public void testGsonWithLowerCaseUnderscorePolicyDeserialiation() {
|
||||||
Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
|
Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
|
||||||
.create();
|
.create();
|
||||||
|
@ -100,6 +109,7 @@ public class NamingPolicyTest extends TestCase {
|
||||||
assertEquals("someValue", deserializedObject.someConstantStringInstanceField);
|
assertEquals("someValue", deserializedObject.someConstantStringInstanceField);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testGsonWithSerializedNameFieldNamingPolicySerialization() {
|
public void testGsonWithSerializedNameFieldNamingPolicySerialization() {
|
||||||
Gson gson = builder.create();
|
Gson gson = builder.create();
|
||||||
ClassWithSerializedNameFields expected = new ClassWithSerializedNameFields(5, 6);
|
ClassWithSerializedNameFields expected = new ClassWithSerializedNameFields(5, 6);
|
||||||
|
@ -107,6 +117,7 @@ public class NamingPolicyTest extends TestCase {
|
||||||
assertEquals(expected.getExpectedJson(), actual);
|
assertEquals(expected.getExpectedJson(), actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testGsonWithSerializedNameFieldNamingPolicyDeserialization() {
|
public void testGsonWithSerializedNameFieldNamingPolicyDeserialization() {
|
||||||
Gson gson = builder.create();
|
Gson gson = builder.create();
|
||||||
ClassWithSerializedNameFields expected = new ClassWithSerializedNameFields(5, 7);
|
ClassWithSerializedNameFields expected = new ClassWithSerializedNameFields(5, 7);
|
||||||
|
@ -115,6 +126,7 @@ public class NamingPolicyTest extends TestCase {
|
||||||
assertEquals(expected.f, actual.f);
|
assertEquals(expected.f, actual.f);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testGsonDuplicateNameUsingSerializedNameFieldNamingPolicySerialization() {
|
public void testGsonDuplicateNameUsingSerializedNameFieldNamingPolicySerialization() {
|
||||||
Gson gson = builder.create();
|
Gson gson = builder.create();
|
||||||
try {
|
try {
|
||||||
|
@ -122,9 +134,16 @@ public class NamingPolicyTest extends TestCase {
|
||||||
gson.toJson(target);
|
gson.toJson(target);
|
||||||
fail();
|
fail();
|
||||||
} catch (IllegalArgumentException expected) {
|
} catch (IllegalArgumentException expected) {
|
||||||
|
assertEquals(
|
||||||
|
"Class com.google.gson.functional.NamingPolicyTest$ClassWithDuplicateFields declares multiple JSON fields named 'a';"
|
||||||
|
+ " conflict is caused by fields com.google.gson.functional.NamingPolicyTest$ClassWithDuplicateFields#a and"
|
||||||
|
+ " com.google.gson.functional.NamingPolicyTest$ClassWithDuplicateFields#b",
|
||||||
|
expected.getMessage()
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testGsonWithUpperCamelCaseSpacesPolicySerialiation() {
|
public void testGsonWithUpperCamelCaseSpacesPolicySerialiation() {
|
||||||
Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES)
|
Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES)
|
||||||
.create();
|
.create();
|
||||||
|
@ -133,6 +152,7 @@ public class NamingPolicyTest extends TestCase {
|
||||||
+ target.someConstantStringInstanceField + "\"}", gson.toJson(target));
|
+ target.someConstantStringInstanceField + "\"}", gson.toJson(target));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testGsonWithUpperCamelCaseSpacesPolicyDeserialiation() {
|
public void testGsonWithUpperCamelCaseSpacesPolicyDeserialiation() {
|
||||||
Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES)
|
Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES)
|
||||||
.create();
|
.create();
|
||||||
|
@ -141,6 +161,7 @@ public class NamingPolicyTest extends TestCase {
|
||||||
assertEquals("someValue", deserializedObject.someConstantStringInstanceField);
|
assertEquals("someValue", deserializedObject.someConstantStringInstanceField);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testGsonWithUpperCaseUnderscorePolicySerialization() {
|
public void testGsonWithUpperCaseUnderscorePolicySerialization() {
|
||||||
Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CASE_WITH_UNDERSCORES)
|
Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CASE_WITH_UNDERSCORES)
|
||||||
.create();
|
.create();
|
||||||
|
@ -149,6 +170,7 @@ public class NamingPolicyTest extends TestCase {
|
||||||
+ target.someConstantStringInstanceField + "\"}", gson.toJson(target));
|
+ target.someConstantStringInstanceField + "\"}", gson.toJson(target));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testGsonWithUpperCaseUnderscorePolicyDeserialiation() {
|
public void testGsonWithUpperCaseUnderscorePolicyDeserialiation() {
|
||||||
Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CASE_WITH_UNDERSCORES)
|
Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CASE_WITH_UNDERSCORES)
|
||||||
.create();
|
.create();
|
||||||
|
@ -157,6 +179,7 @@ public class NamingPolicyTest extends TestCase {
|
||||||
assertEquals("someValue", deserializedObject.someConstantStringInstanceField);
|
assertEquals("someValue", deserializedObject.someConstantStringInstanceField);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeprecatedNamingStrategy() throws Exception {
|
public void testDeprecatedNamingStrategy() throws Exception {
|
||||||
Gson gson = builder.setFieldNamingStrategy(new UpperCaseNamingStrategy()).create();
|
Gson gson = builder.setFieldNamingStrategy(new UpperCaseNamingStrategy()).create();
|
||||||
ClassWithDuplicateFields target = new ClassWithDuplicateFields(10);
|
ClassWithDuplicateFields target = new ClassWithDuplicateFields(10);
|
||||||
|
@ -164,6 +187,7 @@ public class NamingPolicyTest extends TestCase {
|
||||||
assertEquals("{\"A\":10}", actual);
|
assertEquals("{\"A\":10}", actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testComplexFieldNameStrategy() throws Exception {
|
public void testComplexFieldNameStrategy() throws Exception {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
String json = gson.toJson(new ClassWithComplexFieldName(10));
|
String json = gson.toJson(new ClassWithComplexFieldName(10));
|
||||||
|
@ -175,6 +199,7 @@ public class NamingPolicyTest extends TestCase {
|
||||||
}
|
}
|
||||||
|
|
||||||
/** http://code.google.com/p/google-gson/issues/detail?id=349 */
|
/** http://code.google.com/p/google-gson/issues/detail?id=349 */
|
||||||
|
@Test
|
||||||
public void testAtSignInSerializedName() {
|
public void testAtSignInSerializedName() {
|
||||||
assertEquals("{\"@foo\":\"bar\"}", new Gson().toJson(new AtName()));
|
assertEquals("{\"@foo\":\"bar\"}", new Gson().toJson(new AtName()));
|
||||||
}
|
}
|
||||||
|
|
|
@ -16,22 +16,26 @@
|
||||||
|
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertNull;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.GsonBuilder;
|
import com.google.gson.GsonBuilder;
|
||||||
|
import com.google.gson.JsonDeserializationContext;
|
||||||
|
import com.google.gson.JsonDeserializer;
|
||||||
import com.google.gson.JsonElement;
|
import com.google.gson.JsonElement;
|
||||||
import com.google.gson.JsonNull;
|
import com.google.gson.JsonNull;
|
||||||
import com.google.gson.JsonObject;
|
import com.google.gson.JsonObject;
|
||||||
import com.google.gson.JsonDeserializationContext;
|
|
||||||
import com.google.gson.JsonDeserializer;
|
|
||||||
import com.google.gson.JsonSerializationContext;
|
import com.google.gson.JsonSerializationContext;
|
||||||
import com.google.gson.JsonSerializer;
|
import com.google.gson.JsonSerializer;
|
||||||
import com.google.gson.common.TestTypes.BagOfPrimitives;
|
import com.google.gson.common.TestTypes.BagOfPrimitives;
|
||||||
import com.google.gson.common.TestTypes.ClassWithObjects;
|
import com.google.gson.common.TestTypes.ClassWithObjects;
|
||||||
|
|
||||||
import junit.framework.TestCase;
|
|
||||||
|
|
||||||
import java.lang.reflect.Type;
|
import java.lang.reflect.Type;
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Functional tests for the different cases for serializing (or ignoring) null fields and object.
|
* Functional tests for the different cases for serializing (or ignoring) null fields and object.
|
||||||
|
@ -39,15 +43,15 @@ import java.util.Collection;
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
* @author Joel Leitch
|
* @author Joel Leitch
|
||||||
*/
|
*/
|
||||||
public class NullObjectAndFieldTest extends TestCase {
|
public class NullObjectAndFieldTest {
|
||||||
private GsonBuilder gsonBuilder;
|
private GsonBuilder gsonBuilder;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
gsonBuilder = new GsonBuilder().serializeNulls();
|
gsonBuilder = new GsonBuilder().serializeNulls();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testTopLevelNullObjectSerialization() {
|
public void testTopLevelNullObjectSerialization() {
|
||||||
Gson gson = gsonBuilder.create();
|
Gson gson = gsonBuilder.create();
|
||||||
String actual = gson.toJson(null);
|
String actual = gson.toJson(null);
|
||||||
|
@ -57,12 +61,14 @@ public class NullObjectAndFieldTest extends TestCase {
|
||||||
assertEquals("null", actual);
|
assertEquals("null", actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testTopLevelNullObjectDeserialization() throws Exception {
|
public void testTopLevelNullObjectDeserialization() throws Exception {
|
||||||
Gson gson = gsonBuilder.create();
|
Gson gson = gsonBuilder.create();
|
||||||
String actual = gson.fromJson("null", String.class);
|
String actual = gson.fromJson("null", String.class);
|
||||||
assertNull(actual);
|
assertNull(actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testExplicitSerializationOfNulls() {
|
public void testExplicitSerializationOfNulls() {
|
||||||
Gson gson = gsonBuilder.create();
|
Gson gson = gsonBuilder.create();
|
||||||
ClassWithObjects target = new ClassWithObjects(null);
|
ClassWithObjects target = new ClassWithObjects(null);
|
||||||
|
@ -71,12 +77,14 @@ public class NullObjectAndFieldTest extends TestCase {
|
||||||
assertEquals(expected, actual);
|
assertEquals(expected, actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testExplicitDeserializationOfNulls() throws Exception {
|
public void testExplicitDeserializationOfNulls() throws Exception {
|
||||||
Gson gson = gsonBuilder.create();
|
Gson gson = gsonBuilder.create();
|
||||||
ClassWithObjects target = gson.fromJson("{\"bag\":null}", ClassWithObjects.class);
|
ClassWithObjects target = gson.fromJson("{\"bag\":null}", ClassWithObjects.class);
|
||||||
assertNull(target.bag);
|
assertNull(target.bag);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testExplicitSerializationOfNullArrayMembers() {
|
public void testExplicitSerializationOfNullArrayMembers() {
|
||||||
Gson gson = gsonBuilder.create();
|
Gson gson = gsonBuilder.create();
|
||||||
ClassWithMembers target = new ClassWithMembers();
|
ClassWithMembers target = new ClassWithMembers();
|
||||||
|
@ -87,6 +95,7 @@ public class NullObjectAndFieldTest extends TestCase {
|
||||||
/**
|
/**
|
||||||
* Added to verify http://code.google.com/p/google-gson/issues/detail?id=68
|
* Added to verify http://code.google.com/p/google-gson/issues/detail?id=68
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testNullWrappedPrimitiveMemberSerialization() {
|
public void testNullWrappedPrimitiveMemberSerialization() {
|
||||||
Gson gson = gsonBuilder.serializeNulls().create();
|
Gson gson = gsonBuilder.serializeNulls().create();
|
||||||
ClassWithNullWrappedPrimitive target = new ClassWithNullWrappedPrimitive();
|
ClassWithNullWrappedPrimitive target = new ClassWithNullWrappedPrimitive();
|
||||||
|
@ -97,6 +106,7 @@ public class NullObjectAndFieldTest extends TestCase {
|
||||||
/**
|
/**
|
||||||
* Added to verify http://code.google.com/p/google-gson/issues/detail?id=68
|
* Added to verify http://code.google.com/p/google-gson/issues/detail?id=68
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testNullWrappedPrimitiveMemberDeserialization() {
|
public void testNullWrappedPrimitiveMemberDeserialization() {
|
||||||
Gson gson = gsonBuilder.create();
|
Gson gson = gsonBuilder.create();
|
||||||
String json = "{\"value\":null}";
|
String json = "{\"value\":null}";
|
||||||
|
@ -104,6 +114,7 @@ public class NullObjectAndFieldTest extends TestCase {
|
||||||
assertNull(target.value);
|
assertNull(target.value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testExplicitSerializationOfNullCollectionMembers() {
|
public void testExplicitSerializationOfNullCollectionMembers() {
|
||||||
Gson gson = gsonBuilder.create();
|
Gson gson = gsonBuilder.create();
|
||||||
ClassWithMembers target = new ClassWithMembers();
|
ClassWithMembers target = new ClassWithMembers();
|
||||||
|
@ -111,6 +122,7 @@ public class NullObjectAndFieldTest extends TestCase {
|
||||||
assertTrue(json.contains("\"col\":null"));
|
assertTrue(json.contains("\"col\":null"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testExplicitSerializationOfNullStringMembers() {
|
public void testExplicitSerializationOfNullStringMembers() {
|
||||||
Gson gson = gsonBuilder.create();
|
Gson gson = gsonBuilder.create();
|
||||||
ClassWithMembers target = new ClassWithMembers();
|
ClassWithMembers target = new ClassWithMembers();
|
||||||
|
@ -118,6 +130,7 @@ public class NullObjectAndFieldTest extends TestCase {
|
||||||
assertTrue(json.contains("\"str\":null"));
|
assertTrue(json.contains("\"str\":null"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testCustomSerializationOfNulls() {
|
public void testCustomSerializationOfNulls() {
|
||||||
gsonBuilder.registerTypeAdapter(ClassWithObjects.class, new ClassWithObjectsSerializer());
|
gsonBuilder.registerTypeAdapter(ClassWithObjects.class, new ClassWithObjectsSerializer());
|
||||||
Gson gson = gsonBuilder.create();
|
Gson gson = gsonBuilder.create();
|
||||||
|
@ -127,6 +140,7 @@ public class NullObjectAndFieldTest extends TestCase {
|
||||||
assertEquals(expected, actual);
|
assertEquals(expected, actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testPrintPrintingObjectWithNulls() throws Exception {
|
public void testPrintPrintingObjectWithNulls() throws Exception {
|
||||||
gsonBuilder = new GsonBuilder();
|
gsonBuilder = new GsonBuilder();
|
||||||
Gson gson = gsonBuilder.create();
|
Gson gson = gsonBuilder.create();
|
||||||
|
@ -138,6 +152,7 @@ public class NullObjectAndFieldTest extends TestCase {
|
||||||
assertTrue(result.contains("\"str\":null"));
|
assertTrue(result.contains("\"str\":null"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testPrintPrintingArraysWithNulls() throws Exception {
|
public void testPrintPrintingArraysWithNulls() throws Exception {
|
||||||
gsonBuilder = new GsonBuilder();
|
gsonBuilder = new GsonBuilder();
|
||||||
Gson gson = gsonBuilder.create();
|
Gson gson = gsonBuilder.create();
|
||||||
|
@ -150,6 +165,7 @@ public class NullObjectAndFieldTest extends TestCase {
|
||||||
}
|
}
|
||||||
|
|
||||||
// test for issue 389
|
// test for issue 389
|
||||||
|
@Test
|
||||||
public void testAbsentJsonElementsAreSetToNull() {
|
public void testAbsentJsonElementsAreSetToNull() {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
ClassWithInitializedMembers target =
|
ClassWithInitializedMembers target =
|
||||||
|
@ -200,6 +216,7 @@ public class NullObjectAndFieldTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testExplicitNullSetsFieldToNullDuringDeserialization() {
|
public void testExplicitNullSetsFieldToNullDuringDeserialization() {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
String json = "{value:null}";
|
String json = "{value:null}";
|
||||||
|
@ -207,6 +224,7 @@ public class NullObjectAndFieldTest extends TestCase {
|
||||||
assertNull(obj.value);
|
assertNull(obj.value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testCustomTypeAdapterPassesNullSerialization() {
|
public void testCustomTypeAdapterPassesNullSerialization() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.registerTypeAdapter(ObjectWithField.class, new JsonSerializer<ObjectWithField>() {
|
.registerTypeAdapter(ObjectWithField.class, new JsonSerializer<ObjectWithField>() {
|
||||||
|
@ -221,6 +239,7 @@ public class NullObjectAndFieldTest extends TestCase {
|
||||||
assertFalse(json.contains("value1"));
|
assertFalse(json.contains("value1"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testCustomTypeAdapterPassesNullDesrialization() {
|
public void testCustomTypeAdapterPassesNullDesrialization() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.setLenient()
|
.setLenient()
|
||||||
|
|
|
@ -16,6 +16,14 @@
|
||||||
|
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertNotNull;
|
||||||
|
import static org.junit.Assert.assertNull;
|
||||||
|
import static org.junit.Assert.assertSame;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
import static org.junit.Assert.fail;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.GsonBuilder;
|
import com.google.gson.GsonBuilder;
|
||||||
import com.google.gson.InstanceCreator;
|
import com.google.gson.InstanceCreator;
|
||||||
|
@ -45,7 +53,9 @@ import java.util.List;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.TimeZone;
|
import java.util.TimeZone;
|
||||||
import junit.framework.TestCase;
|
import org.junit.After;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Functional tests for Json serialization and deserialization of regular classes.
|
* Functional tests for Json serialization and deserialization of regular classes.
|
||||||
|
@ -53,14 +63,13 @@ import junit.framework.TestCase;
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
* @author Joel Leitch
|
* @author Joel Leitch
|
||||||
*/
|
*/
|
||||||
public class ObjectTest extends TestCase {
|
public class ObjectTest {
|
||||||
private Gson gson;
|
private Gson gson;
|
||||||
private TimeZone oldTimeZone;
|
private TimeZone oldTimeZone;
|
||||||
private Locale oldLocale;
|
private Locale oldLocale;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
gson = new Gson();
|
gson = new Gson();
|
||||||
|
|
||||||
oldTimeZone = TimeZone.getDefault();
|
oldTimeZone = TimeZone.getDefault();
|
||||||
|
@ -69,13 +78,13 @@ public class ObjectTest extends TestCase {
|
||||||
Locale.setDefault(Locale.US);
|
Locale.setDefault(Locale.US);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@After
|
||||||
protected void tearDown() throws Exception {
|
public void tearDown() throws Exception {
|
||||||
TimeZone.setDefault(oldTimeZone);
|
TimeZone.setDefault(oldTimeZone);
|
||||||
Locale.setDefault(oldLocale);
|
Locale.setDefault(oldLocale);
|
||||||
super.tearDown();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testJsonInSingleQuotesDeserialization() {
|
public void testJsonInSingleQuotesDeserialization() {
|
||||||
String json = "{'stringValue':'no message','intValue':10,'longValue':20}";
|
String json = "{'stringValue':'no message','intValue':10,'longValue':20}";
|
||||||
BagOfPrimitives target = gson.fromJson(json, BagOfPrimitives.class);
|
BagOfPrimitives target = gson.fromJson(json, BagOfPrimitives.class);
|
||||||
|
@ -84,6 +93,7 @@ public class ObjectTest extends TestCase {
|
||||||
assertEquals(20, target.longValue);
|
assertEquals(20, target.longValue);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testJsonInMixedQuotesDeserialization() {
|
public void testJsonInMixedQuotesDeserialization() {
|
||||||
String json = "{\"stringValue\":'no message','intValue':10,'longValue':20}";
|
String json = "{\"stringValue\":'no message','intValue':10,'longValue':20}";
|
||||||
BagOfPrimitives target = gson.fromJson(json, BagOfPrimitives.class);
|
BagOfPrimitives target = gson.fromJson(json, BagOfPrimitives.class);
|
||||||
|
@ -92,11 +102,13 @@ public class ObjectTest extends TestCase {
|
||||||
assertEquals(20, target.longValue);
|
assertEquals(20, target.longValue);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBagOfPrimitivesSerialization() throws Exception {
|
public void testBagOfPrimitivesSerialization() throws Exception {
|
||||||
BagOfPrimitives target = new BagOfPrimitives(10, 20, false, "stringValue");
|
BagOfPrimitives target = new BagOfPrimitives(10, 20, false, "stringValue");
|
||||||
assertEquals(target.getExpectedJson(), gson.toJson(target));
|
assertEquals(target.getExpectedJson(), gson.toJson(target));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBagOfPrimitivesDeserialization() throws Exception {
|
public void testBagOfPrimitivesDeserialization() throws Exception {
|
||||||
BagOfPrimitives src = new BagOfPrimitives(10, 20, false, "stringValue");
|
BagOfPrimitives src = new BagOfPrimitives(10, 20, false, "stringValue");
|
||||||
String json = src.getExpectedJson();
|
String json = src.getExpectedJson();
|
||||||
|
@ -104,11 +116,13 @@ public class ObjectTest extends TestCase {
|
||||||
assertEquals(json, target.getExpectedJson());
|
assertEquals(json, target.getExpectedJson());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBagOfPrimitiveWrappersSerialization() throws Exception {
|
public void testBagOfPrimitiveWrappersSerialization() throws Exception {
|
||||||
BagOfPrimitiveWrappers target = new BagOfPrimitiveWrappers(10L, 20, false);
|
BagOfPrimitiveWrappers target = new BagOfPrimitiveWrappers(10L, 20, false);
|
||||||
assertEquals(target.getExpectedJson(), gson.toJson(target));
|
assertEquals(target.getExpectedJson(), gson.toJson(target));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBagOfPrimitiveWrappersDeserialization() throws Exception {
|
public void testBagOfPrimitiveWrappersDeserialization() throws Exception {
|
||||||
BagOfPrimitiveWrappers target = new BagOfPrimitiveWrappers(10L, 20, false);
|
BagOfPrimitiveWrappers target = new BagOfPrimitiveWrappers(10L, 20, false);
|
||||||
String jsonString = target.getExpectedJson();
|
String jsonString = target.getExpectedJson();
|
||||||
|
@ -116,17 +130,20 @@ public class ObjectTest extends TestCase {
|
||||||
assertEquals(jsonString, target.getExpectedJson());
|
assertEquals(jsonString, target.getExpectedJson());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testClassWithTransientFieldsSerialization() throws Exception {
|
public void testClassWithTransientFieldsSerialization() throws Exception {
|
||||||
ClassWithTransientFields<Long> target = new ClassWithTransientFields<>(1L);
|
ClassWithTransientFields<Long> target = new ClassWithTransientFields<>(1L);
|
||||||
assertEquals(target.getExpectedJson(), gson.toJson(target));
|
assertEquals(target.getExpectedJson(), gson.toJson(target));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testClassWithTransientFieldsDeserialization() throws Exception {
|
public void testClassWithTransientFieldsDeserialization() throws Exception {
|
||||||
String json = "{\"longValue\":[1]}";
|
String json = "{\"longValue\":[1]}";
|
||||||
ClassWithTransientFields<?> target = gson.fromJson(json, ClassWithTransientFields.class);
|
ClassWithTransientFields<?> target = gson.fromJson(json, ClassWithTransientFields.class);
|
||||||
assertEquals(json, target.getExpectedJson());
|
assertEquals(json, target.getExpectedJson());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testClassWithTransientFieldsDeserializationTransientFieldsPassedInJsonAreIgnored()
|
public void testClassWithTransientFieldsDeserializationTransientFieldsPassedInJsonAreIgnored()
|
||||||
throws Exception {
|
throws Exception {
|
||||||
String json = "{\"transientLongValue\":1,\"longValue\":[1]}";
|
String json = "{\"transientLongValue\":1,\"longValue\":[1]}";
|
||||||
|
@ -134,10 +151,12 @@ public class ObjectTest extends TestCase {
|
||||||
assertFalse(target.transientLongValue != 1);
|
assertFalse(target.transientLongValue != 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testClassWithNoFieldsSerialization() throws Exception {
|
public void testClassWithNoFieldsSerialization() throws Exception {
|
||||||
assertEquals("{}", gson.toJson(new ClassWithNoFields()));
|
assertEquals("{}", gson.toJson(new ClassWithNoFields()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testClassWithNoFieldsDeserialization() throws Exception {
|
public void testClassWithNoFieldsDeserialization() throws Exception {
|
||||||
String json = "{}";
|
String json = "{}";
|
||||||
ClassWithNoFields target = gson.fromJson(json, ClassWithNoFields.class);
|
ClassWithNoFields target = gson.fromJson(json, ClassWithNoFields.class);
|
||||||
|
@ -145,12 +164,40 @@ public class ObjectTest extends TestCase {
|
||||||
assertEquals(expected, target);
|
assertEquals(expected, target);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static class Subclass extends Superclass1 {
|
||||||
|
}
|
||||||
|
private static class Superclass1 extends Superclass2 {
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
String s;
|
||||||
|
}
|
||||||
|
private static class Superclass2 {
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
String s;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testClassWithDuplicateFields() {
|
||||||
|
try {
|
||||||
|
gson.getAdapter(Subclass.class);
|
||||||
|
fail();
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
assertEquals(
|
||||||
|
"Class com.google.gson.functional.ObjectTest$Subclass declares multiple JSON fields named 's';"
|
||||||
|
+ " conflict is caused by fields com.google.gson.functional.ObjectTest$Superclass1#s and"
|
||||||
|
+ " com.google.gson.functional.ObjectTest$Superclass2#s",
|
||||||
|
e.getMessage()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNestedSerialization() throws Exception {
|
public void testNestedSerialization() throws Exception {
|
||||||
Nested target = new Nested(new BagOfPrimitives(10, 20, false, "stringValue"),
|
Nested target = new Nested(new BagOfPrimitives(10, 20, false, "stringValue"),
|
||||||
new BagOfPrimitives(30, 40, true, "stringValue"));
|
new BagOfPrimitives(30, 40, true, "stringValue"));
|
||||||
assertEquals(target.getExpectedJson(), gson.toJson(target));
|
assertEquals(target.getExpectedJson(), gson.toJson(target));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNestedDeserialization() throws Exception {
|
public void testNestedDeserialization() throws Exception {
|
||||||
String json = "{\"primitive1\":{\"longValue\":10,\"intValue\":20,\"booleanValue\":false,"
|
String json = "{\"primitive1\":{\"longValue\":10,\"intValue\":20,\"booleanValue\":false,"
|
||||||
+ "\"stringValue\":\"stringValue\"},\"primitive2\":{\"longValue\":30,\"intValue\":40,"
|
+ "\"stringValue\":\"stringValue\"},\"primitive2\":{\"longValue\":30,\"intValue\":40,"
|
||||||
|
@ -158,15 +205,18 @@ public class ObjectTest extends TestCase {
|
||||||
Nested target = gson.fromJson(json, Nested.class);
|
Nested target = gson.fromJson(json, Nested.class);
|
||||||
assertEquals(json, target.getExpectedJson());
|
assertEquals(json, target.getExpectedJson());
|
||||||
}
|
}
|
||||||
|
@Test
|
||||||
public void testNullSerialization() throws Exception {
|
public void testNullSerialization() throws Exception {
|
||||||
assertEquals("null", gson.toJson(null));
|
assertEquals("null", gson.toJson(null));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testEmptyStringDeserialization() throws Exception {
|
public void testEmptyStringDeserialization() throws Exception {
|
||||||
Object object = gson.fromJson("", Object.class);
|
Object object = gson.fromJson("", Object.class);
|
||||||
assertNull(object);
|
assertNull(object);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testTruncatedDeserialization() {
|
public void testTruncatedDeserialization() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("[\"a\", \"b\",", new TypeToken<List<String>>() {}.getType());
|
gson.fromJson("[\"a\", \"b\",", new TypeToken<List<String>>() {}.getType());
|
||||||
|
@ -175,17 +225,20 @@ public class ObjectTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNullDeserialization() throws Exception {
|
public void testNullDeserialization() throws Exception {
|
||||||
String myNullObject = null;
|
String myNullObject = null;
|
||||||
Object object = gson.fromJson(myNullObject, Object.class);
|
Object object = gson.fromJson(myNullObject, Object.class);
|
||||||
assertNull(object);
|
assertNull(object);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNullFieldsSerialization() throws Exception {
|
public void testNullFieldsSerialization() throws Exception {
|
||||||
Nested target = new Nested(new BagOfPrimitives(10, 20, false, "stringValue"), null);
|
Nested target = new Nested(new BagOfPrimitives(10, 20, false, "stringValue"), null);
|
||||||
assertEquals(target.getExpectedJson(), gson.toJson(target));
|
assertEquals(target.getExpectedJson(), gson.toJson(target));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNullFieldsDeserialization() throws Exception {
|
public void testNullFieldsDeserialization() throws Exception {
|
||||||
String json = "{\"primitive1\":{\"longValue\":10,\"intValue\":20,\"booleanValue\":false"
|
String json = "{\"primitive1\":{\"longValue\":10,\"intValue\":20,\"booleanValue\":false"
|
||||||
+ ",\"stringValue\":\"stringValue\"}}";
|
+ ",\"stringValue\":\"stringValue\"}}";
|
||||||
|
@ -193,28 +246,33 @@ public class ObjectTest extends TestCase {
|
||||||
assertEquals(json, target.getExpectedJson());
|
assertEquals(json, target.getExpectedJson());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testArrayOfObjectsSerialization() throws Exception {
|
public void testArrayOfObjectsSerialization() throws Exception {
|
||||||
ArrayOfObjects target = new ArrayOfObjects();
|
ArrayOfObjects target = new ArrayOfObjects();
|
||||||
assertEquals(target.getExpectedJson(), gson.toJson(target));
|
assertEquals(target.getExpectedJson(), gson.toJson(target));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testArrayOfObjectsDeserialization() throws Exception {
|
public void testArrayOfObjectsDeserialization() throws Exception {
|
||||||
String json = new ArrayOfObjects().getExpectedJson();
|
String json = new ArrayOfObjects().getExpectedJson();
|
||||||
ArrayOfObjects target = gson.fromJson(json, ArrayOfObjects.class);
|
ArrayOfObjects target = gson.fromJson(json, ArrayOfObjects.class);
|
||||||
assertEquals(json, target.getExpectedJson());
|
assertEquals(json, target.getExpectedJson());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testArrayOfArraysSerialization() throws Exception {
|
public void testArrayOfArraysSerialization() throws Exception {
|
||||||
ArrayOfArrays target = new ArrayOfArrays();
|
ArrayOfArrays target = new ArrayOfArrays();
|
||||||
assertEquals(target.getExpectedJson(), gson.toJson(target));
|
assertEquals(target.getExpectedJson(), gson.toJson(target));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testArrayOfArraysDeserialization() throws Exception {
|
public void testArrayOfArraysDeserialization() throws Exception {
|
||||||
String json = new ArrayOfArrays().getExpectedJson();
|
String json = new ArrayOfArrays().getExpectedJson();
|
||||||
ArrayOfArrays target = gson.fromJson(json, ArrayOfArrays.class);
|
ArrayOfArrays target = gson.fromJson(json, ArrayOfArrays.class);
|
||||||
assertEquals(json, target.getExpectedJson());
|
assertEquals(json, target.getExpectedJson());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testArrayOfObjectsAsFields() throws Exception {
|
public void testArrayOfObjectsAsFields() throws Exception {
|
||||||
ClassWithObjects classWithObjects = new ClassWithObjects();
|
ClassWithObjects classWithObjects = new ClassWithObjects();
|
||||||
BagOfPrimitives bagOfPrimitives = new BagOfPrimitives();
|
BagOfPrimitives bagOfPrimitives = new BagOfPrimitives();
|
||||||
|
@ -234,6 +292,7 @@ public class ObjectTest extends TestCase {
|
||||||
/**
|
/**
|
||||||
* Created in response to Issue 14: http://code.google.com/p/google-gson/issues/detail?id=14
|
* Created in response to Issue 14: http://code.google.com/p/google-gson/issues/detail?id=14
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testNullArraysDeserialization() throws Exception {
|
public void testNullArraysDeserialization() throws Exception {
|
||||||
String json = "{\"array\": null}";
|
String json = "{\"array\": null}";
|
||||||
ClassWithArray target = gson.fromJson(json, ClassWithArray.class);
|
ClassWithArray target = gson.fromJson(json, ClassWithArray.class);
|
||||||
|
@ -243,12 +302,14 @@ public class ObjectTest extends TestCase {
|
||||||
/**
|
/**
|
||||||
* Created in response to Issue 14: http://code.google.com/p/google-gson/issues/detail?id=14
|
* Created in response to Issue 14: http://code.google.com/p/google-gson/issues/detail?id=14
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testNullObjectFieldsDeserialization() throws Exception {
|
public void testNullObjectFieldsDeserialization() throws Exception {
|
||||||
String json = "{\"bag\": null}";
|
String json = "{\"bag\": null}";
|
||||||
ClassWithObjects target = gson.fromJson(json, ClassWithObjects.class);
|
ClassWithObjects target = gson.fromJson(json, ClassWithObjects.class);
|
||||||
assertNull(target.bag);
|
assertNull(target.bag);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testEmptyCollectionInAnObjectDeserialization() throws Exception {
|
public void testEmptyCollectionInAnObjectDeserialization() throws Exception {
|
||||||
String json = "{\"children\":[]}";
|
String json = "{\"children\":[]}";
|
||||||
ClassWithCollectionField target = gson.fromJson(json, ClassWithCollectionField.class);
|
ClassWithCollectionField target = gson.fromJson(json, ClassWithCollectionField.class);
|
||||||
|
@ -260,6 +321,7 @@ public class ObjectTest extends TestCase {
|
||||||
Collection<String> children = new ArrayList<>();
|
Collection<String> children = new ArrayList<>();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testPrimitiveArrayInAnObjectDeserialization() throws Exception {
|
public void testPrimitiveArrayInAnObjectDeserialization() throws Exception {
|
||||||
String json = "{\"longArray\":[0,1,2,3,4,5,6,7,8,9]}";
|
String json = "{\"longArray\":[0,1,2,3,4,5,6,7,8,9]}";
|
||||||
PrimitiveArray target = gson.fromJson(json, PrimitiveArray.class);
|
PrimitiveArray target = gson.fromJson(json, PrimitiveArray.class);
|
||||||
|
@ -269,29 +331,34 @@ public class ObjectTest extends TestCase {
|
||||||
/**
|
/**
|
||||||
* Created in response to Issue 14: http://code.google.com/p/google-gson/issues/detail?id=14
|
* Created in response to Issue 14: http://code.google.com/p/google-gson/issues/detail?id=14
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testNullPrimitiveFieldsDeserialization() throws Exception {
|
public void testNullPrimitiveFieldsDeserialization() throws Exception {
|
||||||
String json = "{\"longValue\":null}";
|
String json = "{\"longValue\":null}";
|
||||||
BagOfPrimitives target = gson.fromJson(json, BagOfPrimitives.class);
|
BagOfPrimitives target = gson.fromJson(json, BagOfPrimitives.class);
|
||||||
assertEquals(BagOfPrimitives.DEFAULT_VALUE, target.longValue);
|
assertEquals(BagOfPrimitives.DEFAULT_VALUE, target.longValue);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testEmptyCollectionInAnObjectSerialization() throws Exception {
|
public void testEmptyCollectionInAnObjectSerialization() throws Exception {
|
||||||
ClassWithCollectionField target = new ClassWithCollectionField();
|
ClassWithCollectionField target = new ClassWithCollectionField();
|
||||||
assertEquals("{\"children\":[]}", gson.toJson(target));
|
assertEquals("{\"children\":[]}", gson.toJson(target));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testPrivateNoArgConstructorDeserialization() throws Exception {
|
public void testPrivateNoArgConstructorDeserialization() throws Exception {
|
||||||
ClassWithPrivateNoArgsConstructor target =
|
ClassWithPrivateNoArgsConstructor target =
|
||||||
gson.fromJson("{\"a\":20}", ClassWithPrivateNoArgsConstructor.class);
|
gson.fromJson("{\"a\":20}", ClassWithPrivateNoArgsConstructor.class);
|
||||||
assertEquals(20, target.a);
|
assertEquals(20, target.a);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testAnonymousLocalClassesSerialization() throws Exception {
|
public void testAnonymousLocalClassesSerialization() throws Exception {
|
||||||
assertEquals("null", gson.toJson(new ClassWithNoFields() {
|
assertEquals("null", gson.toJson(new ClassWithNoFields() {
|
||||||
// empty anonymous class
|
// empty anonymous class
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testAnonymousLocalClassesCustomSerialization() throws Exception {
|
public void testAnonymousLocalClassesCustomSerialization() throws Exception {
|
||||||
gson = new GsonBuilder()
|
gson = new GsonBuilder()
|
||||||
.registerTypeHierarchyAdapter(ClassWithNoFields.class,
|
.registerTypeHierarchyAdapter(ClassWithNoFields.class,
|
||||||
|
@ -307,6 +374,7 @@ public class ObjectTest extends TestCase {
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testPrimitiveArrayFieldSerialization() {
|
public void testPrimitiveArrayFieldSerialization() {
|
||||||
PrimitiveArray target = new PrimitiveArray(new long[] { 1L, 2L, 3L });
|
PrimitiveArray target = new PrimitiveArray(new long[] { 1L, 2L, 3L });
|
||||||
assertEquals(target.getExpectedJson(), gson.toJson(target));
|
assertEquals(target.getExpectedJson(), gson.toJson(target));
|
||||||
|
@ -316,6 +384,7 @@ public class ObjectTest extends TestCase {
|
||||||
* Tests that a class field with type Object can be serialized properly.
|
* Tests that a class field with type Object can be serialized properly.
|
||||||
* See issue 54
|
* See issue 54
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testClassWithObjectFieldSerialization() {
|
public void testClassWithObjectFieldSerialization() {
|
||||||
ClassWithObjectField obj = new ClassWithObjectField();
|
ClassWithObjectField obj = new ClassWithObjectField();
|
||||||
obj.member = "abc";
|
obj.member = "abc";
|
||||||
|
@ -328,6 +397,7 @@ public class ObjectTest extends TestCase {
|
||||||
Object member;
|
Object member;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testInnerClassSerialization() {
|
public void testInnerClassSerialization() {
|
||||||
Parent p = new Parent();
|
Parent p = new Parent();
|
||||||
Parent.Child c = p.new Child();
|
Parent.Child c = p.new Child();
|
||||||
|
@ -336,6 +406,7 @@ public class ObjectTest extends TestCase {
|
||||||
assertFalse(json.contains("value1"));
|
assertFalse(json.contains("value1"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testInnerClassDeserialization() {
|
public void testInnerClassDeserialization() {
|
||||||
final Parent p = new Parent();
|
final Parent p = new Parent();
|
||||||
Gson gson = new GsonBuilder().registerTypeAdapter(
|
Gson gson = new GsonBuilder().registerTypeAdapter(
|
||||||
|
@ -404,6 +475,7 @@ public class ObjectTest extends TestCase {
|
||||||
/**
|
/**
|
||||||
* In response to Issue 41 http://code.google.com/p/google-gson/issues/detail?id=41
|
* In response to Issue 41 http://code.google.com/p/google-gson/issues/detail?id=41
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testObjectFieldNamesWithoutQuotesDeserialization() {
|
public void testObjectFieldNamesWithoutQuotesDeserialization() {
|
||||||
String json = "{longValue:1,'booleanValue':true,\"stringValue\":'bar'}";
|
String json = "{longValue:1,'booleanValue':true,\"stringValue\":'bar'}";
|
||||||
BagOfPrimitives bag = gson.fromJson(json, BagOfPrimitives.class);
|
BagOfPrimitives bag = gson.fromJson(json, BagOfPrimitives.class);
|
||||||
|
@ -412,6 +484,7 @@ public class ObjectTest extends TestCase {
|
||||||
assertEquals("bar", bag.stringValue);
|
assertEquals("bar", bag.stringValue);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testStringFieldWithNumberValueDeserialization() {
|
public void testStringFieldWithNumberValueDeserialization() {
|
||||||
String json = "{\"stringValue\":1}";
|
String json = "{\"stringValue\":1}";
|
||||||
BagOfPrimitives bag = gson.fromJson(json, BagOfPrimitives.class);
|
BagOfPrimitives bag = gson.fromJson(json, BagOfPrimitives.class);
|
||||||
|
@ -429,6 +502,7 @@ public class ObjectTest extends TestCase {
|
||||||
/**
|
/**
|
||||||
* Created to reproduce issue 140
|
* Created to reproduce issue 140
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testStringFieldWithEmptyValueSerialization() {
|
public void testStringFieldWithEmptyValueSerialization() {
|
||||||
ClassWithEmptyStringFields target = new ClassWithEmptyStringFields();
|
ClassWithEmptyStringFields target = new ClassWithEmptyStringFields();
|
||||||
target.a = "5794749";
|
target.a = "5794749";
|
||||||
|
@ -441,6 +515,7 @@ public class ObjectTest extends TestCase {
|
||||||
/**
|
/**
|
||||||
* Created to reproduce issue 140
|
* Created to reproduce issue 140
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testStringFieldWithEmptyValueDeserialization() {
|
public void testStringFieldWithEmptyValueDeserialization() {
|
||||||
String json = "{a:\"5794749\",b:\"\",c:\"\"}";
|
String json = "{a:\"5794749\",b:\"\",c:\"\"}";
|
||||||
ClassWithEmptyStringFields target = gson.fromJson(json, ClassWithEmptyStringFields.class);
|
ClassWithEmptyStringFields target = gson.fromJson(json, ClassWithEmptyStringFields.class);
|
||||||
|
@ -455,6 +530,7 @@ public class ObjectTest extends TestCase {
|
||||||
String c = "";
|
String c = "";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testJsonObjectSerialization() {
|
public void testJsonObjectSerialization() {
|
||||||
Gson gson = new GsonBuilder().serializeNulls().create();
|
Gson gson = new GsonBuilder().serializeNulls().create();
|
||||||
JsonObject obj = new JsonObject();
|
JsonObject obj = new JsonObject();
|
||||||
|
@ -465,6 +541,7 @@ public class ObjectTest extends TestCase {
|
||||||
/**
|
/**
|
||||||
* Test for issue 215.
|
* Test for issue 215.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testSingletonLists() {
|
public void testSingletonLists() {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
Product product = new Product();
|
Product product = new Product();
|
||||||
|
@ -494,6 +571,7 @@ public class ObjectTest extends TestCase {
|
||||||
}
|
}
|
||||||
|
|
||||||
// http://code.google.com/p/google-gson/issues/detail?id=270
|
// http://code.google.com/p/google-gson/issues/detail?id=270
|
||||||
|
@Test
|
||||||
public void testDateAsMapObjectField() {
|
public void testDateAsMapObjectField() {
|
||||||
HasObjectMap a = new HasObjectMap();
|
HasObjectMap a = new HasObjectMap();
|
||||||
a.map.put("date", new Date(0));
|
a.map.put("date", new Date(0));
|
||||||
|
@ -514,6 +592,7 @@ public class ObjectTest extends TestCase {
|
||||||
* <p>Important: It is not documented that this is officially supported; this
|
* <p>Important: It is not documented that this is officially supported; this
|
||||||
* test just checks the current behavior.
|
* test just checks the current behavior.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testStaticFieldSerialization() {
|
public void testStaticFieldSerialization() {
|
||||||
// By default Gson should ignore static fields
|
// By default Gson should ignore static fields
|
||||||
assertEquals("{}", gson.toJson(new ClassWithStaticField()));
|
assertEquals("{}", gson.toJson(new ClassWithStaticField()));
|
||||||
|
@ -536,6 +615,7 @@ public class ObjectTest extends TestCase {
|
||||||
* <p>Important: It is not documented that this is officially supported; this
|
* <p>Important: It is not documented that this is officially supported; this
|
||||||
* test just checks the current behavior.
|
* test just checks the current behavior.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testStaticFieldDeserialization() {
|
public void testStaticFieldDeserialization() {
|
||||||
// By default Gson should ignore static fields
|
// By default Gson should ignore static fields
|
||||||
gson.fromJson("{\"s\":\"custom\"}", ClassWithStaticField.class);
|
gson.fromJson("{\"s\":\"custom\"}", ClassWithStaticField.class);
|
||||||
|
@ -572,6 +652,7 @@ public class ObjectTest extends TestCase {
|
||||||
static final String s = "initial";
|
static final String s = "initial";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testThrowingDefaultConstructor() {
|
public void testThrowingDefaultConstructor() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("{}", ClassWithThrowingConstructor.class);
|
gson.fromJson("{}", ClassWithThrowingConstructor.class);
|
||||||
|
|
|
@ -15,20 +15,22 @@
|
||||||
*/
|
*/
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
import java.lang.reflect.Type;
|
import static org.junit.Assert.assertEquals;
|
||||||
import java.util.Arrays;
|
import static org.junit.Assert.assertTrue;
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.LinkedList;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import junit.framework.TestCase;
|
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.GsonBuilder;
|
import com.google.gson.GsonBuilder;
|
||||||
import com.google.gson.common.TestTypes.ArrayOfObjects;
|
import com.google.gson.common.TestTypes.ArrayOfObjects;
|
||||||
import com.google.gson.common.TestTypes.BagOfPrimitives;
|
import com.google.gson.common.TestTypes.BagOfPrimitives;
|
||||||
import com.google.gson.reflect.TypeToken;
|
import com.google.gson.reflect.TypeToken;
|
||||||
|
import java.lang.reflect.Type;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.LinkedList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Functional tests for pretty printing option.
|
* Functional tests for pretty printing option.
|
||||||
|
@ -36,18 +38,18 @@ import com.google.gson.reflect.TypeToken;
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
* @author Joel Leitch
|
* @author Joel Leitch
|
||||||
*/
|
*/
|
||||||
public class PrettyPrintingTest extends TestCase {
|
public class PrettyPrintingTest {
|
||||||
|
|
||||||
private static final boolean DEBUG = false;
|
private static final boolean DEBUG = false;
|
||||||
|
|
||||||
private Gson gson;
|
private Gson gson;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
gson = new GsonBuilder().setPrettyPrinting().create();
|
gson = new GsonBuilder().setPrettyPrinting().create();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testPrettyPrintList() {
|
public void testPrettyPrintList() {
|
||||||
BagOfPrimitives b = new BagOfPrimitives();
|
BagOfPrimitives b = new BagOfPrimitives();
|
||||||
List<BagOfPrimitives> listOfB = new LinkedList<>();
|
List<BagOfPrimitives> listOfB = new LinkedList<>();
|
||||||
|
@ -59,18 +61,21 @@ public class PrettyPrintingTest extends TestCase {
|
||||||
print(json);
|
print(json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testPrettyPrintArrayOfObjects() {
|
public void testPrettyPrintArrayOfObjects() {
|
||||||
ArrayOfObjects target = new ArrayOfObjects();
|
ArrayOfObjects target = new ArrayOfObjects();
|
||||||
String json = gson.toJson(target);
|
String json = gson.toJson(target);
|
||||||
print(json);
|
print(json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testPrettyPrintArrayOfPrimitives() {
|
public void testPrettyPrintArrayOfPrimitives() {
|
||||||
int[] ints = new int[] { 1, 2, 3, 4, 5 };
|
int[] ints = new int[] { 1, 2, 3, 4, 5 };
|
||||||
String json = gson.toJson(ints);
|
String json = gson.toJson(ints);
|
||||||
assertEquals("[\n 1,\n 2,\n 3,\n 4,\n 5\n]", json);
|
assertEquals("[\n 1,\n 2,\n 3,\n 4,\n 5\n]", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testPrettyPrintArrayOfPrimitiveArrays() {
|
public void testPrettyPrintArrayOfPrimitiveArrays() {
|
||||||
int[][] ints = new int[][] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 },
|
int[][] ints = new int[][] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 },
|
||||||
{ 9, 0 }, { 10 } };
|
{ 9, 0 }, { 10 } };
|
||||||
|
@ -79,6 +84,7 @@ public class PrettyPrintingTest extends TestCase {
|
||||||
+ "\n [\n 7,\n 8\n ],\n [\n 9,\n 0\n ],\n [\n 10\n ]\n]", json);
|
+ "\n [\n 7,\n 8\n ],\n [\n 9,\n 0\n ],\n [\n 10\n ]\n]", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testPrettyPrintListOfPrimitiveArrays() {
|
public void testPrettyPrintListOfPrimitiveArrays() {
|
||||||
List<Integer[]> list = Arrays.asList(new Integer[][] { { 1, 2 }, { 3, 4 },
|
List<Integer[]> list = Arrays.asList(new Integer[][] { { 1, 2 }, { 3, 4 },
|
||||||
{ 5, 6 }, { 7, 8 }, { 9, 0 }, { 10 } });
|
{ 5, 6 }, { 7, 8 }, { 9, 0 }, { 10 } });
|
||||||
|
@ -87,6 +93,7 @@ public class PrettyPrintingTest extends TestCase {
|
||||||
+ "\n [\n 7,\n 8\n ],\n [\n 9,\n 0\n ],\n [\n 10\n ]\n]", json);
|
+ "\n [\n 7,\n 8\n ],\n [\n 9,\n 0\n ],\n [\n 10\n ]\n]", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testMap() {
|
public void testMap() {
|
||||||
Map<String, Integer> map = new LinkedHashMap<>();
|
Map<String, Integer> map = new LinkedHashMap<>();
|
||||||
map.put("abc", 1);
|
map.put("abc", 1);
|
||||||
|
@ -96,6 +103,7 @@ public class PrettyPrintingTest extends TestCase {
|
||||||
}
|
}
|
||||||
|
|
||||||
// In response to bug 153
|
// In response to bug 153
|
||||||
|
@Test
|
||||||
public void testEmptyMapField() {
|
public void testEmptyMapField() {
|
||||||
ClassWithMap obj = new ClassWithMap();
|
ClassWithMap obj = new ClassWithMap();
|
||||||
obj.map = new LinkedHashMap<>();
|
obj.map = new LinkedHashMap<>();
|
||||||
|
@ -109,6 +117,7 @@ public class PrettyPrintingTest extends TestCase {
|
||||||
int value = 2;
|
int value = 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testMultipleArrays() {
|
public void testMultipleArrays() {
|
||||||
int[][][] ints = new int[][][] { { { 1 }, { 2 } } };
|
int[][][] ints = new int[][][] { { { 1 }, { 2 } } };
|
||||||
String json = gson.toJson(ints);
|
String json = gson.toJson(ints);
|
||||||
|
|
|
@ -16,8 +16,11 @@
|
||||||
|
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
import com.google.gson.*;
|
import static org.junit.Assert.assertEquals;
|
||||||
import junit.framework.TestCase;
|
|
||||||
|
import com.google.gson.Gson;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Functional tests for Java Character values.
|
* Functional tests for Java Character values.
|
||||||
|
@ -25,21 +28,22 @@ import junit.framework.TestCase;
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
* @author Joel Leitch
|
* @author Joel Leitch
|
||||||
*/
|
*/
|
||||||
public class PrimitiveCharacterTest extends TestCase {
|
public class PrimitiveCharacterTest {
|
||||||
private Gson gson;
|
private Gson gson;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
gson = new Gson();
|
gson = new Gson();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testPrimitiveCharacterAutoboxedSerialization() {
|
public void testPrimitiveCharacterAutoboxedSerialization() {
|
||||||
assertEquals("\"A\"", gson.toJson('A'));
|
assertEquals("\"A\"", gson.toJson('A'));
|
||||||
assertEquals("\"A\"", gson.toJson('A', char.class));
|
assertEquals("\"A\"", gson.toJson('A', char.class));
|
||||||
assertEquals("\"A\"", gson.toJson('A', Character.class));
|
assertEquals("\"A\"", gson.toJson('A', Character.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testPrimitiveCharacterAutoboxedDeserialization() {
|
public void testPrimitiveCharacterAutoboxedDeserialization() {
|
||||||
char expected = 'a';
|
char expected = 'a';
|
||||||
char actual = gson.fromJson("a", char.class);
|
char actual = gson.fromJson("a", char.class);
|
||||||
|
|
|
@ -17,6 +17,10 @@
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
import static org.junit.Assert.assertArrayEquals;
|
import static org.junit.Assert.assertArrayEquals;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
import static org.junit.Assert.fail;
|
||||||
|
|
||||||
import com.google.gson.*;
|
import com.google.gson.*;
|
||||||
import com.google.gson.internal.LazilyParsedNumber;
|
import com.google.gson.internal.LazilyParsedNumber;
|
||||||
|
@ -27,7 +31,8 @@ import java.math.BigDecimal;
|
||||||
import java.math.BigInteger;
|
import java.math.BigInteger;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import junit.framework.TestCase;
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Functional tests for Json primitive values: integers, and floating point numbers.
|
* Functional tests for Json primitive values: integers, and floating point numbers.
|
||||||
|
@ -35,19 +40,20 @@ import junit.framework.TestCase;
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
* @author Joel Leitch
|
* @author Joel Leitch
|
||||||
*/
|
*/
|
||||||
public class PrimitiveTest extends TestCase {
|
public class PrimitiveTest {
|
||||||
private Gson gson;
|
private Gson gson;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
gson = new Gson();
|
gson = new Gson();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testPrimitiveIntegerAutoboxedSerialization() {
|
public void testPrimitiveIntegerAutoboxedSerialization() {
|
||||||
assertEquals("1", gson.toJson(1));
|
assertEquals("1", gson.toJson(1));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testPrimitiveIntegerAutoboxedDeserialization() {
|
public void testPrimitiveIntegerAutoboxedDeserialization() {
|
||||||
int expected = 1;
|
int expected = 1;
|
||||||
int actual = gson.fromJson("1", int.class);
|
int actual = gson.fromJson("1", int.class);
|
||||||
|
@ -57,6 +63,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
assertEquals(expected, actual);
|
assertEquals(expected, actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testByteSerialization() {
|
public void testByteSerialization() {
|
||||||
assertEquals("1", gson.toJson(1, byte.class));
|
assertEquals("1", gson.toJson(1, byte.class));
|
||||||
assertEquals("1", gson.toJson(1, Byte.class));
|
assertEquals("1", gson.toJson(1, Byte.class));
|
||||||
|
@ -67,6 +74,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
assertEquals("1", gson.toJson(1.5, Byte.class));
|
assertEquals("1", gson.toJson(1.5, Byte.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testByteDeserialization() {
|
public void testByteDeserialization() {
|
||||||
Byte boxed = gson.fromJson("1", Byte.class);
|
Byte boxed = gson.fromJson("1", Byte.class);
|
||||||
assertEquals(1, (byte)boxed);
|
assertEquals(1, (byte)boxed);
|
||||||
|
@ -77,6 +85,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
assertArrayEquals(new byte[] {-128, 0, 127, -1}, bytes);
|
assertArrayEquals(new byte[] {-128, 0, 127, -1}, bytes);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testByteDeserializationLossy() {
|
public void testByteDeserializationLossy() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("-129", byte.class);
|
gson.fromJson("-129", byte.class);
|
||||||
|
@ -100,6 +109,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testShortSerialization() {
|
public void testShortSerialization() {
|
||||||
assertEquals("1", gson.toJson(1, short.class));
|
assertEquals("1", gson.toJson(1, short.class));
|
||||||
assertEquals("1", gson.toJson(1, Short.class));
|
assertEquals("1", gson.toJson(1, Short.class));
|
||||||
|
@ -112,6 +122,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
assertEquals("1", gson.toJson(1.5, Short.class));
|
assertEquals("1", gson.toJson(1.5, Short.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testShortDeserialization() {
|
public void testShortDeserialization() {
|
||||||
Short boxed = gson.fromJson("1", Short.class);
|
Short boxed = gson.fromJson("1", Short.class);
|
||||||
assertEquals(1, (short)boxed);
|
assertEquals(1, (short)boxed);
|
||||||
|
@ -122,6 +133,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
assertArrayEquals(new short[] {-32768, 0, 32767, -1}, shorts);
|
assertArrayEquals(new short[] {-32768, 0, 32767, -1}, shorts);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testShortDeserializationLossy() {
|
public void testShortDeserializationLossy() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("-32769", short.class);
|
gson.fromJson("-32769", short.class);
|
||||||
|
@ -145,6 +157,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testIntSerialization() {
|
public void testIntSerialization() {
|
||||||
assertEquals("1", gson.toJson(1, int.class));
|
assertEquals("1", gson.toJson(1, int.class));
|
||||||
assertEquals("1", gson.toJson(1, Integer.class));
|
assertEquals("1", gson.toJson(1, Integer.class));
|
||||||
|
@ -157,6 +170,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
assertEquals("1", gson.toJson(1.5, Integer.class));
|
assertEquals("1", gson.toJson(1.5, Integer.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testLongSerialization() {
|
public void testLongSerialization() {
|
||||||
assertEquals("1", gson.toJson(1L, long.class));
|
assertEquals("1", gson.toJson(1L, long.class));
|
||||||
assertEquals("1", gson.toJson(1L, Long.class));
|
assertEquals("1", gson.toJson(1L, Long.class));
|
||||||
|
@ -168,6 +182,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
assertEquals("1", gson.toJson(1.5, Long.class));
|
assertEquals("1", gson.toJson(1.5, Long.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testFloatSerialization() {
|
public void testFloatSerialization() {
|
||||||
assertEquals("1.5", gson.toJson(1.5f, float.class));
|
assertEquals("1.5", gson.toJson(1.5f, float.class));
|
||||||
assertEquals("1.5", gson.toJson(1.5f, Float.class));
|
assertEquals("1.5", gson.toJson(1.5f, Float.class));
|
||||||
|
@ -182,6 +197,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
assertEquals("Infinity", gson.toJson(Double.MAX_VALUE, Float.class));
|
assertEquals("Infinity", gson.toJson(Double.MAX_VALUE, Float.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDoubleSerialization() {
|
public void testDoubleSerialization() {
|
||||||
assertEquals("1.5", gson.toJson(1.5, double.class));
|
assertEquals("1.5", gson.toJson(1.5, double.class));
|
||||||
assertEquals("1.5", gson.toJson(1.5, Double.class));
|
assertEquals("1.5", gson.toJson(1.5, Double.class));
|
||||||
|
@ -193,6 +209,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
assertEquals(Double.toString(Long.MAX_VALUE - 10L), gson.toJson(Long.MAX_VALUE - 10L, Double.class));
|
assertEquals(Double.toString(Long.MAX_VALUE - 10L), gson.toJson(Long.MAX_VALUE - 10L, Double.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testPrimitiveIntegerAutoboxedInASingleElementArraySerialization() {
|
public void testPrimitiveIntegerAutoboxedInASingleElementArraySerialization() {
|
||||||
int target[] = {-9332};
|
int target[] = {-9332};
|
||||||
assertEquals("[-9332]", gson.toJson(target));
|
assertEquals("[-9332]", gson.toJson(target));
|
||||||
|
@ -200,22 +217,26 @@ public class PrimitiveTest extends TestCase {
|
||||||
assertEquals("[-9332]", gson.toJson(target, Integer[].class));
|
assertEquals("[-9332]", gson.toJson(target, Integer[].class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testReallyLongValuesSerialization() {
|
public void testReallyLongValuesSerialization() {
|
||||||
long value = 333961828784581L;
|
long value = 333961828784581L;
|
||||||
assertEquals("333961828784581", gson.toJson(value));
|
assertEquals("333961828784581", gson.toJson(value));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testReallyLongValuesDeserialization() {
|
public void testReallyLongValuesDeserialization() {
|
||||||
String json = "333961828784581";
|
String json = "333961828784581";
|
||||||
long value = gson.fromJson(json, Long.class);
|
long value = gson.fromJson(json, Long.class);
|
||||||
assertEquals(333961828784581L, value);
|
assertEquals(333961828784581L, value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testPrimitiveLongAutoboxedSerialization() {
|
public void testPrimitiveLongAutoboxedSerialization() {
|
||||||
assertEquals("1", gson.toJson(1L, long.class));
|
assertEquals("1", gson.toJson(1L, long.class));
|
||||||
assertEquals("1", gson.toJson(1L, Long.class));
|
assertEquals("1", gson.toJson(1L, Long.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testPrimitiveLongAutoboxedDeserialization() {
|
public void testPrimitiveLongAutoboxedDeserialization() {
|
||||||
long expected = 1L;
|
long expected = 1L;
|
||||||
long actual = gson.fromJson("1", long.class);
|
long actual = gson.fromJson("1", long.class);
|
||||||
|
@ -225,6 +246,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
assertEquals(expected, actual);
|
assertEquals(expected, actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testPrimitiveLongAutoboxedInASingleElementArraySerialization() {
|
public void testPrimitiveLongAutoboxedInASingleElementArraySerialization() {
|
||||||
long[] target = {-23L};
|
long[] target = {-23L};
|
||||||
assertEquals("[-23]", gson.toJson(target));
|
assertEquals("[-23]", gson.toJson(target));
|
||||||
|
@ -232,11 +254,13 @@ public class PrimitiveTest extends TestCase {
|
||||||
assertEquals("[-23]", gson.toJson(target, Long[].class));
|
assertEquals("[-23]", gson.toJson(target, Long[].class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testPrimitiveBooleanAutoboxedSerialization() {
|
public void testPrimitiveBooleanAutoboxedSerialization() {
|
||||||
assertEquals("true", gson.toJson(true));
|
assertEquals("true", gson.toJson(true));
|
||||||
assertEquals("false", gson.toJson(false));
|
assertEquals("false", gson.toJson(false));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBooleanDeserialization() {
|
public void testBooleanDeserialization() {
|
||||||
boolean value = gson.fromJson("false", boolean.class);
|
boolean value = gson.fromJson("false", boolean.class);
|
||||||
assertEquals(false, value);
|
assertEquals(false, value);
|
||||||
|
@ -244,6 +268,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
assertEquals(true, value);
|
assertEquals(true, value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testPrimitiveBooleanAutoboxedInASingleElementArraySerialization() {
|
public void testPrimitiveBooleanAutoboxedInASingleElementArraySerialization() {
|
||||||
boolean target[] = {false};
|
boolean target[] = {false};
|
||||||
assertEquals("[false]", gson.toJson(target));
|
assertEquals("[false]", gson.toJson(target));
|
||||||
|
@ -251,6 +276,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
assertEquals("[false]", gson.toJson(target, Boolean[].class));
|
assertEquals("[false]", gson.toJson(target, Boolean[].class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNumberSerialization() {
|
public void testNumberSerialization() {
|
||||||
Number expected = 1L;
|
Number expected = 1L;
|
||||||
String json = gson.toJson(expected);
|
String json = gson.toJson(expected);
|
||||||
|
@ -260,6 +286,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
assertEquals(expected.toString(), json);
|
assertEquals(expected.toString(), json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNumberDeserialization() {
|
public void testNumberDeserialization() {
|
||||||
String json = "1";
|
String json = "1";
|
||||||
Number expected = Integer.valueOf(json);
|
Number expected = Integer.valueOf(json);
|
||||||
|
@ -276,24 +303,28 @@ public class PrimitiveTest extends TestCase {
|
||||||
assertEquals(1L, actual.longValue());
|
assertEquals(1L, actual.longValue());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNumberAsStringDeserialization() {
|
public void testNumberAsStringDeserialization() {
|
||||||
Number value = gson.fromJson("\"18\"", Number.class);
|
Number value = gson.fromJson("\"18\"", Number.class);
|
||||||
assertEquals(18, value.intValue());
|
assertEquals(18, value.intValue());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testPrimitiveDoubleAutoboxedSerialization() {
|
public void testPrimitiveDoubleAutoboxedSerialization() {
|
||||||
assertEquals("-122.08234335", gson.toJson(-122.08234335D));
|
assertEquals("-122.08234335", gson.toJson(-122.08234335D));
|
||||||
assertEquals("122.08112002", gson.toJson(122.08112002D));
|
assertEquals("122.08112002", gson.toJson(122.08112002D));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testPrimitiveDoubleAutoboxedDeserialization() {
|
public void testPrimitiveDoubleAutoboxedDeserialization() {
|
||||||
double actual = gson.fromJson("-122.08858585", double.class);
|
double actual = gson.fromJson("-122.08858585", double.class);
|
||||||
assertEquals(-122.08858585D, actual);
|
assertEquals(-122.08858585D, actual, 0);
|
||||||
|
|
||||||
actual = gson.fromJson("122.023900008000", Double.class);
|
actual = gson.fromJson("122.023900008000", Double.class);
|
||||||
assertEquals(122.023900008D, actual);
|
assertEquals(122.023900008D, actual, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testPrimitiveDoubleAutoboxedInASingleElementArraySerialization() {
|
public void testPrimitiveDoubleAutoboxedInASingleElementArraySerialization() {
|
||||||
double[] target = {-122.08D};
|
double[] target = {-122.08D};
|
||||||
assertEquals("[-122.08]", gson.toJson(target));
|
assertEquals("[-122.08]", gson.toJson(target));
|
||||||
|
@ -301,6 +332,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
assertEquals("[-122.08]", gson.toJson(target, Double[].class));
|
assertEquals("[-122.08]", gson.toJson(target, Double[].class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDoubleAsStringRepresentationDeserialization() {
|
public void testDoubleAsStringRepresentationDeserialization() {
|
||||||
String doubleValue = "1.0043E+5";
|
String doubleValue = "1.0043E+5";
|
||||||
Double expected = Double.valueOf(doubleValue);
|
Double expected = Double.valueOf(doubleValue);
|
||||||
|
@ -308,9 +340,10 @@ public class PrimitiveTest extends TestCase {
|
||||||
assertEquals(expected, actual);
|
assertEquals(expected, actual);
|
||||||
|
|
||||||
double actual1 = gson.fromJson(doubleValue, double.class);
|
double actual1 = gson.fromJson(doubleValue, double.class);
|
||||||
assertEquals(expected.doubleValue(), actual1);
|
assertEquals(expected, actual1, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDoubleNoFractAsStringRepresentationDeserialization() {
|
public void testDoubleNoFractAsStringRepresentationDeserialization() {
|
||||||
String doubleValue = "1E+5";
|
String doubleValue = "1E+5";
|
||||||
Double expected = Double.valueOf(doubleValue);
|
Double expected = Double.valueOf(doubleValue);
|
||||||
|
@ -318,22 +351,24 @@ public class PrimitiveTest extends TestCase {
|
||||||
assertEquals(expected, actual);
|
assertEquals(expected, actual);
|
||||||
|
|
||||||
double actual1 = gson.fromJson(doubleValue, double.class);
|
double actual1 = gson.fromJson(doubleValue, double.class);
|
||||||
assertEquals(expected.doubleValue(), actual1);
|
assertEquals(expected, actual1, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDoubleArrayDeserialization() {
|
public void testDoubleArrayDeserialization() {
|
||||||
String json = "[0.0, 0.004761904761904762, 3.4013606962703525E-4, 7.936508173034305E-4,"
|
String json = "[0.0, 0.004761904761904762, 3.4013606962703525E-4, 7.936508173034305E-4,"
|
||||||
+ "0.0011904761904761906, 0.0]";
|
+ "0.0011904761904761906, 0.0]";
|
||||||
double[] values = gson.fromJson(json, double[].class);
|
double[] values = gson.fromJson(json, double[].class);
|
||||||
assertEquals(6, values.length);
|
assertEquals(6, values.length, 0);
|
||||||
assertEquals(0.0, values[0]);
|
assertEquals(0.0, values[0], 0);
|
||||||
assertEquals(0.004761904761904762, values[1]);
|
assertEquals(0.004761904761904762, values[1], 0);
|
||||||
assertEquals(3.4013606962703525E-4, values[2]);
|
assertEquals(3.4013606962703525E-4, values[2], 0);
|
||||||
assertEquals(7.936508173034305E-4, values[3]);
|
assertEquals(7.936508173034305E-4, values[3], 0);
|
||||||
assertEquals(0.0011904761904761906, values[4]);
|
assertEquals(0.0011904761904761906, values[4], 0);
|
||||||
assertEquals(0.0, values[5]);
|
assertEquals(0.0, values[5], 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testLargeDoubleDeserialization() {
|
public void testLargeDoubleDeserialization() {
|
||||||
String doubleValue = "1.234567899E8";
|
String doubleValue = "1.234567899E8";
|
||||||
Double expected = Double.valueOf(doubleValue);
|
Double expected = Double.valueOf(doubleValue);
|
||||||
|
@ -341,21 +376,24 @@ public class PrimitiveTest extends TestCase {
|
||||||
assertEquals(expected, actual);
|
assertEquals(expected, actual);
|
||||||
|
|
||||||
double actual1 = gson.fromJson(doubleValue, double.class);
|
double actual1 = gson.fromJson(doubleValue, double.class);
|
||||||
assertEquals(expected.doubleValue(), actual1);
|
assertEquals(expected, actual1, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBigDecimalSerialization() {
|
public void testBigDecimalSerialization() {
|
||||||
BigDecimal target = new BigDecimal("-122.0e-21");
|
BigDecimal target = new BigDecimal("-122.0e-21");
|
||||||
String json = gson.toJson(target);
|
String json = gson.toJson(target);
|
||||||
assertEquals(target, new BigDecimal(json));
|
assertEquals(target, new BigDecimal(json));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBigDecimalDeserialization() {
|
public void testBigDecimalDeserialization() {
|
||||||
BigDecimal target = new BigDecimal("-122.0e-21");
|
BigDecimal target = new BigDecimal("-122.0e-21");
|
||||||
String json = "-122.0e-21";
|
String json = "-122.0e-21";
|
||||||
assertEquals(target, gson.fromJson(json, BigDecimal.class));
|
assertEquals(target, gson.fromJson(json, BigDecimal.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBigDecimalInASingleElementArraySerialization() {
|
public void testBigDecimalInASingleElementArraySerialization() {
|
||||||
BigDecimal[] target = {new BigDecimal("-122.08e-21")};
|
BigDecimal[] target = {new BigDecimal("-122.08e-21")};
|
||||||
String json = gson.toJson(target);
|
String json = gson.toJson(target);
|
||||||
|
@ -367,18 +405,21 @@ public class PrimitiveTest extends TestCase {
|
||||||
assertEquals(target[0], new BigDecimal(actual));
|
assertEquals(target[0], new BigDecimal(actual));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSmallValueForBigDecimalSerialization() {
|
public void testSmallValueForBigDecimalSerialization() {
|
||||||
BigDecimal target = new BigDecimal("1.55");
|
BigDecimal target = new BigDecimal("1.55");
|
||||||
String actual = gson.toJson(target);
|
String actual = gson.toJson(target);
|
||||||
assertEquals(target.toString(), actual);
|
assertEquals(target.toString(), actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSmallValueForBigDecimalDeserialization() {
|
public void testSmallValueForBigDecimalDeserialization() {
|
||||||
BigDecimal expected = new BigDecimal("1.55");
|
BigDecimal expected = new BigDecimal("1.55");
|
||||||
BigDecimal actual = gson.fromJson("1.55", BigDecimal.class);
|
BigDecimal actual = gson.fromJson("1.55", BigDecimal.class);
|
||||||
assertEquals(expected, actual);
|
assertEquals(expected, actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBigDecimalPreservePrecisionSerialization() {
|
public void testBigDecimalPreservePrecisionSerialization() {
|
||||||
String expectedValue = "1.000";
|
String expectedValue = "1.000";
|
||||||
BigDecimal obj = new BigDecimal(expectedValue);
|
BigDecimal obj = new BigDecimal(expectedValue);
|
||||||
|
@ -387,6 +428,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
assertEquals(expectedValue, actualValue);
|
assertEquals(expectedValue, actualValue);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBigDecimalPreservePrecisionDeserialization() {
|
public void testBigDecimalPreservePrecisionDeserialization() {
|
||||||
String json = "1.000";
|
String json = "1.000";
|
||||||
BigDecimal expected = new BigDecimal(json);
|
BigDecimal expected = new BigDecimal(json);
|
||||||
|
@ -395,6 +437,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
assertEquals(expected, actual);
|
assertEquals(expected, actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBigDecimalAsStringRepresentationDeserialization() {
|
public void testBigDecimalAsStringRepresentationDeserialization() {
|
||||||
String doubleValue = "0.05E+5";
|
String doubleValue = "0.05E+5";
|
||||||
BigDecimal expected = new BigDecimal(doubleValue);
|
BigDecimal expected = new BigDecimal(doubleValue);
|
||||||
|
@ -402,6 +445,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
assertEquals(expected, actual);
|
assertEquals(expected, actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBigDecimalNoFractAsStringRepresentationDeserialization() {
|
public void testBigDecimalNoFractAsStringRepresentationDeserialization() {
|
||||||
String doubleValue = "5E+5";
|
String doubleValue = "5E+5";
|
||||||
BigDecimal expected = new BigDecimal(doubleValue);
|
BigDecimal expected = new BigDecimal(doubleValue);
|
||||||
|
@ -409,17 +453,20 @@ public class PrimitiveTest extends TestCase {
|
||||||
assertEquals(expected, actual);
|
assertEquals(expected, actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBigIntegerSerialization() {
|
public void testBigIntegerSerialization() {
|
||||||
BigInteger target = new BigInteger("12121211243123245845384534687435634558945453489543985435");
|
BigInteger target = new BigInteger("12121211243123245845384534687435634558945453489543985435");
|
||||||
assertEquals(target.toString(), gson.toJson(target));
|
assertEquals(target.toString(), gson.toJson(target));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBigIntegerDeserialization() {
|
public void testBigIntegerDeserialization() {
|
||||||
String json = "12121211243123245845384534687435634558945453489543985435";
|
String json = "12121211243123245845384534687435634558945453489543985435";
|
||||||
BigInteger target = new BigInteger(json);
|
BigInteger target = new BigInteger(json);
|
||||||
assertEquals(target, gson.fromJson(json, BigInteger.class));
|
assertEquals(target, gson.fromJson(json, BigInteger.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBigIntegerInASingleElementArraySerialization() {
|
public void testBigIntegerInASingleElementArraySerialization() {
|
||||||
BigInteger[] target = {new BigInteger("1212121243434324323254365345367456456456465464564564")};
|
BigInteger[] target = {new BigInteger("1212121243434324323254365345367456456456465464564564")};
|
||||||
String json = gson.toJson(target);
|
String json = gson.toJson(target);
|
||||||
|
@ -431,18 +478,21 @@ public class PrimitiveTest extends TestCase {
|
||||||
assertEquals(target[0], new BigInteger(actual));
|
assertEquals(target[0], new BigInteger(actual));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSmallValueForBigIntegerSerialization() {
|
public void testSmallValueForBigIntegerSerialization() {
|
||||||
BigInteger target = new BigInteger("15");
|
BigInteger target = new BigInteger("15");
|
||||||
String actual = gson.toJson(target);
|
String actual = gson.toJson(target);
|
||||||
assertEquals(target.toString(), actual);
|
assertEquals(target.toString(), actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSmallValueForBigIntegerDeserialization() {
|
public void testSmallValueForBigIntegerDeserialization() {
|
||||||
BigInteger expected = new BigInteger("15");
|
BigInteger expected = new BigInteger("15");
|
||||||
BigInteger actual = gson.fromJson("15", BigInteger.class);
|
BigInteger actual = gson.fromJson("15", BigInteger.class);
|
||||||
assertEquals(expected, actual);
|
assertEquals(expected, actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBadValueForBigIntegerDeserialization() {
|
public void testBadValueForBigIntegerDeserialization() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("15.099", BigInteger.class);
|
gson.fromJson("15.099", BigInteger.class);
|
||||||
|
@ -450,18 +500,21 @@ public class PrimitiveTest extends TestCase {
|
||||||
} catch (JsonSyntaxException expected) { }
|
} catch (JsonSyntaxException expected) { }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testLazilyParsedNumberSerialization() {
|
public void testLazilyParsedNumberSerialization() {
|
||||||
LazilyParsedNumber target = new LazilyParsedNumber("1.5");
|
LazilyParsedNumber target = new LazilyParsedNumber("1.5");
|
||||||
String actual = gson.toJson(target);
|
String actual = gson.toJson(target);
|
||||||
assertEquals("1.5", actual);
|
assertEquals("1.5", actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testLazilyParsedNumberDeserialization() {
|
public void testLazilyParsedNumberDeserialization() {
|
||||||
LazilyParsedNumber expected = new LazilyParsedNumber("1.5");
|
LazilyParsedNumber expected = new LazilyParsedNumber("1.5");
|
||||||
LazilyParsedNumber actual = gson.fromJson("1.5", LazilyParsedNumber.class);
|
LazilyParsedNumber actual = gson.fromJson("1.5", LazilyParsedNumber.class);
|
||||||
assertEquals(expected, actual);
|
assertEquals(expected, actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testMoreSpecificSerialization() {
|
public void testMoreSpecificSerialization() {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
String expected = "This is a string";
|
String expected = "This is a string";
|
||||||
|
@ -476,6 +529,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
return json.substring(json.indexOf('[') + 1, json.indexOf(']'));
|
return json.substring(json.indexOf('[') + 1, json.indexOf(']'));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDoubleNaNSerializationNotSupportedByDefault() {
|
public void testDoubleNaNSerializationNotSupportedByDefault() {
|
||||||
try {
|
try {
|
||||||
double nan = Double.NaN;
|
double nan = Double.NaN;
|
||||||
|
@ -490,6 +544,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDoubleNaNSerialization() {
|
public void testDoubleNaNSerialization() {
|
||||||
Gson gson = new GsonBuilder().setLenient().serializeSpecialFloatingPointValues().create();
|
Gson gson = new GsonBuilder().setLenient().serializeSpecialFloatingPointValues().create();
|
||||||
double nan = Double.NaN;
|
double nan = Double.NaN;
|
||||||
|
@ -497,11 +552,13 @@ public class PrimitiveTest extends TestCase {
|
||||||
assertEquals("NaN", gson.toJson(Double.NaN));
|
assertEquals("NaN", gson.toJson(Double.NaN));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDoubleNaNDeserialization() {
|
public void testDoubleNaNDeserialization() {
|
||||||
assertTrue(Double.isNaN(gson.fromJson("NaN", Double.class)));
|
assertTrue(Double.isNaN(gson.fromJson("NaN", Double.class)));
|
||||||
assertTrue(Double.isNaN(gson.fromJson("NaN", double.class)));
|
assertTrue(Double.isNaN(gson.fromJson("NaN", double.class)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testFloatNaNSerializationNotSupportedByDefault() {
|
public void testFloatNaNSerializationNotSupportedByDefault() {
|
||||||
try {
|
try {
|
||||||
float nan = Float.NaN;
|
float nan = Float.NaN;
|
||||||
|
@ -516,6 +573,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testFloatNaNSerialization() {
|
public void testFloatNaNSerialization() {
|
||||||
Gson gson = new GsonBuilder().setLenient().serializeSpecialFloatingPointValues().create();
|
Gson gson = new GsonBuilder().setLenient().serializeSpecialFloatingPointValues().create();
|
||||||
float nan = Float.NaN;
|
float nan = Float.NaN;
|
||||||
|
@ -523,11 +581,13 @@ public class PrimitiveTest extends TestCase {
|
||||||
assertEquals("NaN", gson.toJson(Float.NaN));
|
assertEquals("NaN", gson.toJson(Float.NaN));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testFloatNaNDeserialization() {
|
public void testFloatNaNDeserialization() {
|
||||||
assertTrue(Float.isNaN(gson.fromJson("NaN", Float.class)));
|
assertTrue(Float.isNaN(gson.fromJson("NaN", Float.class)));
|
||||||
assertTrue(Float.isNaN(gson.fromJson("NaN", float.class)));
|
assertTrue(Float.isNaN(gson.fromJson("NaN", float.class)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBigDecimalNaNDeserializationNotSupported() {
|
public void testBigDecimalNaNDeserializationNotSupported() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("NaN", BigDecimal.class);
|
gson.fromJson("NaN", BigDecimal.class);
|
||||||
|
@ -536,6 +596,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDoubleInfinitySerializationNotSupportedByDefault() {
|
public void testDoubleInfinitySerializationNotSupportedByDefault() {
|
||||||
try {
|
try {
|
||||||
double infinity = Double.POSITIVE_INFINITY;
|
double infinity = Double.POSITIVE_INFINITY;
|
||||||
|
@ -550,6 +611,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDoubleInfinitySerialization() {
|
public void testDoubleInfinitySerialization() {
|
||||||
Gson gson = new GsonBuilder().setLenient().serializeSpecialFloatingPointValues().create();
|
Gson gson = new GsonBuilder().setLenient().serializeSpecialFloatingPointValues().create();
|
||||||
double infinity = Double.POSITIVE_INFINITY;
|
double infinity = Double.POSITIVE_INFINITY;
|
||||||
|
@ -557,11 +619,13 @@ public class PrimitiveTest extends TestCase {
|
||||||
assertEquals("Infinity", gson.toJson(Double.POSITIVE_INFINITY));
|
assertEquals("Infinity", gson.toJson(Double.POSITIVE_INFINITY));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDoubleInfinityDeserialization() {
|
public void testDoubleInfinityDeserialization() {
|
||||||
assertTrue(Double.isInfinite(gson.fromJson("Infinity", Double.class)));
|
assertTrue(Double.isInfinite(gson.fromJson("Infinity", Double.class)));
|
||||||
assertTrue(Double.isInfinite(gson.fromJson("Infinity", double.class)));
|
assertTrue(Double.isInfinite(gson.fromJson("Infinity", double.class)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testFloatInfinitySerializationNotSupportedByDefault() {
|
public void testFloatInfinitySerializationNotSupportedByDefault() {
|
||||||
try {
|
try {
|
||||||
float infinity = Float.POSITIVE_INFINITY;
|
float infinity = Float.POSITIVE_INFINITY;
|
||||||
|
@ -576,6 +640,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testFloatInfinitySerialization() {
|
public void testFloatInfinitySerialization() {
|
||||||
Gson gson = new GsonBuilder().setLenient().serializeSpecialFloatingPointValues().create();
|
Gson gson = new GsonBuilder().setLenient().serializeSpecialFloatingPointValues().create();
|
||||||
float infinity = Float.POSITIVE_INFINITY;
|
float infinity = Float.POSITIVE_INFINITY;
|
||||||
|
@ -583,11 +648,13 @@ public class PrimitiveTest extends TestCase {
|
||||||
assertEquals("Infinity", gson.toJson(Float.POSITIVE_INFINITY));
|
assertEquals("Infinity", gson.toJson(Float.POSITIVE_INFINITY));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testFloatInfinityDeserialization() {
|
public void testFloatInfinityDeserialization() {
|
||||||
assertTrue(Float.isInfinite(gson.fromJson("Infinity", Float.class)));
|
assertTrue(Float.isInfinite(gson.fromJson("Infinity", Float.class)));
|
||||||
assertTrue(Float.isInfinite(gson.fromJson("Infinity", float.class)));
|
assertTrue(Float.isInfinite(gson.fromJson("Infinity", float.class)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBigDecimalInfinityDeserializationNotSupported() {
|
public void testBigDecimalInfinityDeserializationNotSupported() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("Infinity", BigDecimal.class);
|
gson.fromJson("Infinity", BigDecimal.class);
|
||||||
|
@ -596,6 +663,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNegativeInfinitySerializationNotSupportedByDefault() {
|
public void testNegativeInfinitySerializationNotSupportedByDefault() {
|
||||||
try {
|
try {
|
||||||
double negativeInfinity = Double.NEGATIVE_INFINITY;
|
double negativeInfinity = Double.NEGATIVE_INFINITY;
|
||||||
|
@ -610,6 +678,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNegativeInfinitySerialization() {
|
public void testNegativeInfinitySerialization() {
|
||||||
Gson gson = new GsonBuilder().setLenient().serializeSpecialFloatingPointValues().create();
|
Gson gson = new GsonBuilder().setLenient().serializeSpecialFloatingPointValues().create();
|
||||||
double negativeInfinity = Double.NEGATIVE_INFINITY;
|
double negativeInfinity = Double.NEGATIVE_INFINITY;
|
||||||
|
@ -617,11 +686,13 @@ public class PrimitiveTest extends TestCase {
|
||||||
assertEquals("-Infinity", gson.toJson(Double.NEGATIVE_INFINITY));
|
assertEquals("-Infinity", gson.toJson(Double.NEGATIVE_INFINITY));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNegativeInfinityDeserialization() {
|
public void testNegativeInfinityDeserialization() {
|
||||||
assertTrue(Double.isInfinite(gson.fromJson("-Infinity", double.class)));
|
assertTrue(Double.isInfinite(gson.fromJson("-Infinity", double.class)));
|
||||||
assertTrue(Double.isInfinite(gson.fromJson("-Infinity", Double.class)));
|
assertTrue(Double.isInfinite(gson.fromJson("-Infinity", Double.class)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNegativeInfinityFloatSerializationNotSupportedByDefault() {
|
public void testNegativeInfinityFloatSerializationNotSupportedByDefault() {
|
||||||
try {
|
try {
|
||||||
float negativeInfinity = Float.NEGATIVE_INFINITY;
|
float negativeInfinity = Float.NEGATIVE_INFINITY;
|
||||||
|
@ -636,6 +707,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNegativeInfinityFloatSerialization() {
|
public void testNegativeInfinityFloatSerialization() {
|
||||||
Gson gson = new GsonBuilder().setLenient().serializeSpecialFloatingPointValues().create();
|
Gson gson = new GsonBuilder().setLenient().serializeSpecialFloatingPointValues().create();
|
||||||
float negativeInfinity = Float.NEGATIVE_INFINITY;
|
float negativeInfinity = Float.NEGATIVE_INFINITY;
|
||||||
|
@ -643,11 +715,13 @@ public class PrimitiveTest extends TestCase {
|
||||||
assertEquals("-Infinity", gson.toJson(Float.NEGATIVE_INFINITY));
|
assertEquals("-Infinity", gson.toJson(Float.NEGATIVE_INFINITY));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNegativeInfinityFloatDeserialization() {
|
public void testNegativeInfinityFloatDeserialization() {
|
||||||
assertTrue(Float.isInfinite(gson.fromJson("-Infinity", float.class)));
|
assertTrue(Float.isInfinite(gson.fromJson("-Infinity", float.class)));
|
||||||
assertTrue(Float.isInfinite(gson.fromJson("-Infinity", Float.class)));
|
assertTrue(Float.isInfinite(gson.fromJson("-Infinity", Float.class)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testBigDecimalNegativeInfinityDeserializationNotSupported() {
|
public void testBigDecimalNegativeInfinityDeserializationNotSupported() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("-Infinity", BigDecimal.class);
|
gson.fromJson("-Infinity", BigDecimal.class);
|
||||||
|
@ -656,6 +730,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testLongAsStringSerialization() throws Exception {
|
public void testLongAsStringSerialization() throws Exception {
|
||||||
gson = new GsonBuilder().setLongSerializationPolicy(LongSerializationPolicy.STRING).create();
|
gson = new GsonBuilder().setLongSerializationPolicy(LongSerializationPolicy.STRING).create();
|
||||||
String result = gson.toJson(15L);
|
String result = gson.toJson(15L);
|
||||||
|
@ -666,6 +741,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
assertEquals("2", result);
|
assertEquals("2", result);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testLongAsStringDeserialization() throws Exception {
|
public void testLongAsStringDeserialization() throws Exception {
|
||||||
long value = gson.fromJson("\"15\"", long.class);
|
long value = gson.fromJson("\"15\"", long.class);
|
||||||
assertEquals(15, value);
|
assertEquals(15, value);
|
||||||
|
@ -675,6 +751,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
assertEquals(25, value);
|
assertEquals(25, value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testQuotedStringSerializationAndDeserialization() throws Exception {
|
public void testQuotedStringSerializationAndDeserialization() throws Exception {
|
||||||
String value = "String Blah Blah Blah...1, 2, 3";
|
String value = "String Blah Blah Blah...1, 2, 3";
|
||||||
String serializedForm = gson.toJson(value);
|
String serializedForm = gson.toJson(value);
|
||||||
|
@ -684,6 +761,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
assertEquals(value, actual);
|
assertEquals(value, actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testUnquotedStringDeserializationFails() throws Exception {
|
public void testUnquotedStringDeserializationFails() throws Exception {
|
||||||
assertEquals("UnquotedSingleWord", gson.fromJson("UnquotedSingleWord", String.class));
|
assertEquals("UnquotedSingleWord", gson.fromJson("UnquotedSingleWord", String.class));
|
||||||
|
|
||||||
|
@ -694,6 +772,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
} catch (JsonSyntaxException expected) { }
|
} catch (JsonSyntaxException expected) { }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testHtmlCharacterSerialization() throws Exception {
|
public void testHtmlCharacterSerialization() throws Exception {
|
||||||
String target = "<script>var a = 12;</script>";
|
String target = "<script>var a = 12;</script>";
|
||||||
String result = gson.toJson(target);
|
String result = gson.toJson(target);
|
||||||
|
@ -704,6 +783,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
assertTrue(result.equals('"' + target + '"'));
|
assertTrue(result.equals('"' + target + '"'));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserializePrimitiveWrapperAsObjectField() {
|
public void testDeserializePrimitiveWrapperAsObjectField() {
|
||||||
String json = "{i:10}";
|
String json = "{i:10}";
|
||||||
ClassWithIntegerField target = gson.fromJson(json, ClassWithIntegerField.class);
|
ClassWithIntegerField target = gson.fromJson(json, ClassWithIntegerField.class);
|
||||||
|
@ -714,12 +794,14 @@ public class PrimitiveTest extends TestCase {
|
||||||
Integer i;
|
Integer i;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testPrimitiveClassLiteral() {
|
public void testPrimitiveClassLiteral() {
|
||||||
assertEquals(1, gson.fromJson("1", int.class).intValue());
|
assertEquals(1, gson.fromJson("1", int.class).intValue());
|
||||||
assertEquals(1, gson.fromJson(new StringReader("1"), int.class).intValue());
|
assertEquals(1, gson.fromJson(new StringReader("1"), int.class).intValue());
|
||||||
assertEquals(1, gson.fromJson(new JsonPrimitive(1), int.class).intValue());
|
assertEquals(1, gson.fromJson(new JsonPrimitive(1), int.class).intValue());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserializeJsonObjectAsLongPrimitive() {
|
public void testDeserializeJsonObjectAsLongPrimitive() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("{'abc':1}", long.class);
|
gson.fromJson("{'abc':1}", long.class);
|
||||||
|
@ -727,6 +809,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
} catch (JsonSyntaxException expected) {}
|
} catch (JsonSyntaxException expected) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserializeJsonArrayAsLongWrapper() {
|
public void testDeserializeJsonArrayAsLongWrapper() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("[1,2,3]", Long.class);
|
gson.fromJson("[1,2,3]", Long.class);
|
||||||
|
@ -734,6 +817,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
} catch (JsonSyntaxException expected) {}
|
} catch (JsonSyntaxException expected) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserializeJsonArrayAsInt() {
|
public void testDeserializeJsonArrayAsInt() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("[1, 2, 3, 4]", int.class);
|
gson.fromJson("[1, 2, 3, 4]", int.class);
|
||||||
|
@ -741,6 +825,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
} catch (JsonSyntaxException expected) {}
|
} catch (JsonSyntaxException expected) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserializeJsonObjectAsInteger() {
|
public void testDeserializeJsonObjectAsInteger() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("{}", Integer.class);
|
gson.fromJson("{}", Integer.class);
|
||||||
|
@ -748,6 +833,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
} catch (JsonSyntaxException expected) {}
|
} catch (JsonSyntaxException expected) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserializeJsonObjectAsShortPrimitive() {
|
public void testDeserializeJsonObjectAsShortPrimitive() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("{'abc':1}", short.class);
|
gson.fromJson("{'abc':1}", short.class);
|
||||||
|
@ -755,6 +841,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
} catch (JsonSyntaxException expected) {}
|
} catch (JsonSyntaxException expected) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserializeJsonArrayAsShortWrapper() {
|
public void testDeserializeJsonArrayAsShortWrapper() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("['a','b']", Short.class);
|
gson.fromJson("['a','b']", Short.class);
|
||||||
|
@ -762,6 +849,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
} catch (JsonSyntaxException expected) {}
|
} catch (JsonSyntaxException expected) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserializeJsonArrayAsDoublePrimitive() {
|
public void testDeserializeJsonArrayAsDoublePrimitive() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("[1,2]", double.class);
|
gson.fromJson("[1,2]", double.class);
|
||||||
|
@ -769,6 +857,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
} catch (JsonSyntaxException expected) {}
|
} catch (JsonSyntaxException expected) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserializeJsonObjectAsDoubleWrapper() {
|
public void testDeserializeJsonObjectAsDoubleWrapper() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("{'abc':1}", Double.class);
|
gson.fromJson("{'abc':1}", Double.class);
|
||||||
|
@ -776,6 +865,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
} catch (JsonSyntaxException expected) {}
|
} catch (JsonSyntaxException expected) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserializeJsonObjectAsFloatPrimitive() {
|
public void testDeserializeJsonObjectAsFloatPrimitive() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("{'abc':1}", float.class);
|
gson.fromJson("{'abc':1}", float.class);
|
||||||
|
@ -783,6 +873,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
} catch (JsonSyntaxException expected) {}
|
} catch (JsonSyntaxException expected) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserializeJsonArrayAsFloatWrapper() {
|
public void testDeserializeJsonArrayAsFloatWrapper() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("[1,2,3]", Float.class);
|
gson.fromJson("[1,2,3]", Float.class);
|
||||||
|
@ -790,6 +881,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
} catch (JsonSyntaxException expected) {}
|
} catch (JsonSyntaxException expected) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserializeJsonObjectAsBytePrimitive() {
|
public void testDeserializeJsonObjectAsBytePrimitive() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("{'abc':1}", byte.class);
|
gson.fromJson("{'abc':1}", byte.class);
|
||||||
|
@ -797,6 +889,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
} catch (JsonSyntaxException expected) {}
|
} catch (JsonSyntaxException expected) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserializeJsonArrayAsByteWrapper() {
|
public void testDeserializeJsonArrayAsByteWrapper() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("[1,2,3,4]", Byte.class);
|
gson.fromJson("[1,2,3,4]", Byte.class);
|
||||||
|
@ -804,6 +897,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
} catch (JsonSyntaxException expected) {}
|
} catch (JsonSyntaxException expected) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserializeJsonObjectAsBooleanPrimitive() {
|
public void testDeserializeJsonObjectAsBooleanPrimitive() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("{'abc':1}", boolean.class);
|
gson.fromJson("{'abc':1}", boolean.class);
|
||||||
|
@ -811,6 +905,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
} catch (JsonSyntaxException expected) {}
|
} catch (JsonSyntaxException expected) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserializeJsonArrayAsBooleanWrapper() {
|
public void testDeserializeJsonArrayAsBooleanWrapper() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("[1,2,3,4]", Boolean.class);
|
gson.fromJson("[1,2,3,4]", Boolean.class);
|
||||||
|
@ -818,6 +913,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
} catch (JsonSyntaxException expected) {}
|
} catch (JsonSyntaxException expected) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserializeJsonArrayAsBigDecimal() {
|
public void testDeserializeJsonArrayAsBigDecimal() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("[1,2,3,4]", BigDecimal.class);
|
gson.fromJson("[1,2,3,4]", BigDecimal.class);
|
||||||
|
@ -825,6 +921,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
} catch (JsonSyntaxException expected) {}
|
} catch (JsonSyntaxException expected) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserializeJsonObjectAsBigDecimal() {
|
public void testDeserializeJsonObjectAsBigDecimal() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("{'a':1}", BigDecimal.class);
|
gson.fromJson("{'a':1}", BigDecimal.class);
|
||||||
|
@ -832,6 +929,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
} catch (JsonSyntaxException expected) {}
|
} catch (JsonSyntaxException expected) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserializeJsonArrayAsBigInteger() {
|
public void testDeserializeJsonArrayAsBigInteger() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("[1,2,3,4]", BigInteger.class);
|
gson.fromJson("[1,2,3,4]", BigInteger.class);
|
||||||
|
@ -839,6 +937,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
} catch (JsonSyntaxException expected) {}
|
} catch (JsonSyntaxException expected) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserializeJsonObjectAsBigInteger() {
|
public void testDeserializeJsonObjectAsBigInteger() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("{'c':2}", BigInteger.class);
|
gson.fromJson("{'c':2}", BigInteger.class);
|
||||||
|
@ -846,6 +945,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
} catch (JsonSyntaxException expected) {}
|
} catch (JsonSyntaxException expected) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserializeJsonArrayAsNumber() {
|
public void testDeserializeJsonArrayAsNumber() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("[1,2,3,4]", Number.class);
|
gson.fromJson("[1,2,3,4]", Number.class);
|
||||||
|
@ -853,6 +953,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
} catch (JsonSyntaxException expected) {}
|
} catch (JsonSyntaxException expected) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserializeJsonObjectAsNumber() {
|
public void testDeserializeJsonObjectAsNumber() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("{'c':2}", Number.class);
|
gson.fromJson("{'c':2}", Number.class);
|
||||||
|
@ -860,10 +961,12 @@ public class PrimitiveTest extends TestCase {
|
||||||
} catch (JsonSyntaxException expected) {}
|
} catch (JsonSyntaxException expected) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserializingDecimalPointValueZeroSucceeds() {
|
public void testDeserializingDecimalPointValueZeroSucceeds() {
|
||||||
assertEquals(1, (int) gson.fromJson("1.0", Integer.class));
|
assertEquals(1, (int) gson.fromJson("1.0", Integer.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserializingNonZeroDecimalPointValuesAsIntegerFails() {
|
public void testDeserializingNonZeroDecimalPointValuesAsIntegerFails() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("1.02", Byte.class);
|
gson.fromJson("1.02", Byte.class);
|
||||||
|
@ -887,6 +990,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserializingBigDecimalAsIntegerFails() {
|
public void testDeserializingBigDecimalAsIntegerFails() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("-122.08e-213", Integer.class);
|
gson.fromJson("-122.08e-213", Integer.class);
|
||||||
|
@ -895,6 +999,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserializingBigIntegerAsInteger() {
|
public void testDeserializingBigIntegerAsInteger() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("12121211243123245845384534687435634558945453489543985435", Integer.class);
|
gson.fromJson("12121211243123245845384534687435634558945453489543985435", Integer.class);
|
||||||
|
@ -903,6 +1008,7 @@ public class PrimitiveTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserializingBigIntegerAsLong() {
|
public void testDeserializingBigIntegerAsLong() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("12121211243123245845384534687435634558945453489543985435", Long.class);
|
gson.fromJson("12121211243123245845384534687435634558945453489543985435", Long.class);
|
||||||
|
@ -911,29 +1017,33 @@ public class PrimitiveTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testValueVeryCloseToZeroIsZero() {
|
public void testValueVeryCloseToZeroIsZero() {
|
||||||
assertEquals(0, (byte) gson.fromJson("-122.08e-2132", byte.class));
|
assertEquals(0, (byte) gson.fromJson("-122.08e-2132", byte.class));
|
||||||
assertEquals(0, (short) gson.fromJson("-122.08e-2132", short.class));
|
assertEquals(0, (short) gson.fromJson("-122.08e-2132", short.class));
|
||||||
assertEquals(0, (int) gson.fromJson("-122.08e-2132", int.class));
|
assertEquals(0, (int) gson.fromJson("-122.08e-2132", int.class));
|
||||||
assertEquals(0, (long) gson.fromJson("-122.08e-2132", long.class));
|
assertEquals(0, (long) gson.fromJson("-122.08e-2132", long.class));
|
||||||
assertEquals(-0.0f, gson.fromJson("-122.08e-2132", float.class));
|
assertEquals(-0.0f, gson.fromJson("-122.08e-2132", float.class), 0);
|
||||||
assertEquals(-0.0, gson.fromJson("-122.08e-2132", double.class));
|
assertEquals(-0.0, gson.fromJson("-122.08e-2132", double.class), 0);
|
||||||
assertEquals(0.0f, gson.fromJson("122.08e-2132", float.class));
|
assertEquals(0.0f, gson.fromJson("122.08e-2132", float.class), 0);
|
||||||
assertEquals(0.0, gson.fromJson("122.08e-2132", double.class));
|
assertEquals(0.0, gson.fromJson("122.08e-2132", double.class), 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserializingBigDecimalAsFloat() {
|
public void testDeserializingBigDecimalAsFloat() {
|
||||||
String json = "-122.08e-2132332";
|
String json = "-122.08e-2132332";
|
||||||
float actual = gson.fromJson(json, float.class);
|
float actual = gson.fromJson(json, float.class);
|
||||||
assertEquals(-0.0f, actual);
|
assertEquals(-0.0f, actual, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserializingBigDecimalAsDouble() {
|
public void testDeserializingBigDecimalAsDouble() {
|
||||||
String json = "-122.08e-2132332";
|
String json = "-122.08e-2132332";
|
||||||
double actual = gson.fromJson(json, double.class);
|
double actual = gson.fromJson(json, double.class);
|
||||||
assertEquals(-0.0d, actual);
|
assertEquals(-0.0d, actual, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserializingBigDecimalAsBigIntegerFails() {
|
public void testDeserializingBigDecimalAsBigIntegerFails() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("-122.08e-213", BigInteger.class);
|
gson.fromJson("-122.08e-213", BigInteger.class);
|
||||||
|
@ -942,12 +1052,14 @@ public class PrimitiveTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserializingBigIntegerAsBigDecimal() {
|
public void testDeserializingBigIntegerAsBigDecimal() {
|
||||||
BigDecimal actual =
|
BigDecimal actual =
|
||||||
gson.fromJson("12121211243123245845384534687435634558945453489543985435", BigDecimal.class);
|
gson.fromJson("12121211243123245845384534687435634558945453489543985435", BigDecimal.class);
|
||||||
assertEquals("12121211243123245845384534687435634558945453489543985435", actual.toPlainString());
|
assertEquals("12121211243123245845384534687435634558945453489543985435", actual.toPlainString());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testStringsAsBooleans() {
|
public void testStringsAsBooleans() {
|
||||||
String json = "['true', 'false', 'TRUE', 'yes', '1']";
|
String json = "['true', 'false', 'TRUE', 'yes', '1']";
|
||||||
assertEquals(Arrays.asList(true, false, true, false, false),
|
assertEquals(Arrays.asList(true, false, true, false, false),
|
||||||
|
|
|
@ -16,6 +16,9 @@
|
||||||
|
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.GsonBuilder;
|
import com.google.gson.GsonBuilder;
|
||||||
import com.google.gson.JsonObject;
|
import com.google.gson.JsonObject;
|
||||||
|
@ -25,7 +28,8 @@ import com.google.gson.common.TestTypes.Nested;
|
||||||
import com.google.gson.common.TestTypes.PrimitiveArray;
|
import com.google.gson.common.TestTypes.PrimitiveArray;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import junit.framework.TestCase;
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Functional tests for print formatting.
|
* Functional tests for print formatting.
|
||||||
|
@ -33,16 +37,16 @@ import junit.framework.TestCase;
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
* @author Joel Leitch
|
* @author Joel Leitch
|
||||||
*/
|
*/
|
||||||
public class PrintFormattingTest extends TestCase {
|
public class PrintFormattingTest {
|
||||||
|
|
||||||
private Gson gson;
|
private Gson gson;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
gson = new Gson();
|
gson = new Gson();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testCompactFormattingLeavesNoWhiteSpace() {
|
public void testCompactFormattingLeavesNoWhiteSpace() {
|
||||||
List<Object> list = new ArrayList<>();
|
List<Object> list = new ArrayList<>();
|
||||||
list.add(new BagOfPrimitives());
|
list.add(new BagOfPrimitives());
|
||||||
|
@ -54,6 +58,7 @@ public class PrintFormattingTest extends TestCase {
|
||||||
assertContainsNoWhiteSpace(json);
|
assertContainsNoWhiteSpace(json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testJsonObjectWithNullValues() {
|
public void testJsonObjectWithNullValues() {
|
||||||
JsonObject obj = new JsonObject();
|
JsonObject obj = new JsonObject();
|
||||||
obj.addProperty("field1", "value1");
|
obj.addProperty("field1", "value1");
|
||||||
|
@ -63,6 +68,7 @@ public class PrintFormattingTest extends TestCase {
|
||||||
assertFalse(json.contains("field2"));
|
assertFalse(json.contains("field2"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testJsonObjectWithNullValuesSerialized() {
|
public void testJsonObjectWithNullValuesSerialized() {
|
||||||
gson = new GsonBuilder().serializeNulls().create();
|
gson = new GsonBuilder().serializeNulls().create();
|
||||||
JsonObject obj = new JsonObject();
|
JsonObject obj = new JsonObject();
|
||||||
|
|
|
@ -15,41 +15,44 @@
|
||||||
*/
|
*/
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
import java.util.Arrays;
|
import static org.junit.Assert.assertEquals;
|
||||||
import java.util.Collection;
|
|
||||||
|
|
||||||
import junit.framework.TestCase;
|
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.reflect.TypeToken;
|
import com.google.gson.reflect.TypeToken;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Collection;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Unit tests to validate serialization of parameterized types without explicit types
|
* Unit tests to validate serialization of parameterized types without explicit types
|
||||||
*
|
*
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
*/
|
*/
|
||||||
public class RawSerializationTest extends TestCase {
|
public class RawSerializationTest {
|
||||||
|
|
||||||
private Gson gson;
|
private Gson gson;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
gson = new Gson();
|
gson = new Gson();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testCollectionOfPrimitives() {
|
public void testCollectionOfPrimitives() {
|
||||||
Collection<Integer> ints = Arrays.asList(1, 2, 3, 4, 5);
|
Collection<Integer> ints = Arrays.asList(1, 2, 3, 4, 5);
|
||||||
String json = gson.toJson(ints);
|
String json = gson.toJson(ints);
|
||||||
assertEquals("[1,2,3,4,5]", json);
|
assertEquals("[1,2,3,4,5]", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testCollectionOfObjects() {
|
public void testCollectionOfObjects() {
|
||||||
Collection<Foo> foos = Arrays.asList(new Foo(1), new Foo(2));
|
Collection<Foo> foos = Arrays.asList(new Foo(1), new Foo(2));
|
||||||
String json = gson.toJson(foos);
|
String json = gson.toJson(foos);
|
||||||
assertEquals("[{\"b\":1},{\"b\":2}]", json);
|
assertEquals("[{\"b\":1},{\"b\":2}]", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testParameterizedObject() {
|
public void testParameterizedObject() {
|
||||||
Bar<Foo> bar = new Bar<>(new Foo(1));
|
Bar<Foo> bar = new Bar<>(new Foo(1));
|
||||||
String expectedJson = "{\"t\":{\"b\":1}}";
|
String expectedJson = "{\"t\":{\"b\":1}}";
|
||||||
|
@ -61,6 +64,7 @@ public class RawSerializationTest extends TestCase {
|
||||||
assertEquals(expectedJson, json);
|
assertEquals(expectedJson, json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testTwoLevelParameterizedObject() {
|
public void testTwoLevelParameterizedObject() {
|
||||||
Bar<Bar<Foo>> bar = new Bar<>(new Bar<>(new Foo(1)));
|
Bar<Bar<Foo>> bar = new Bar<>(new Bar<>(new Foo(1)));
|
||||||
String expectedJson = "{\"t\":{\"t\":{\"b\":1}}}";
|
String expectedJson = "{\"t\":{\"t\":{\"b\":1}}}";
|
||||||
|
@ -72,6 +76,7 @@ public class RawSerializationTest extends TestCase {
|
||||||
assertEquals(expectedJson, json);
|
assertEquals(expectedJson, json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testThreeLevelParameterizedObject() {
|
public void testThreeLevelParameterizedObject() {
|
||||||
Bar<Bar<Bar<Foo>>> bar = new Bar<>(new Bar<>(new Bar<>(new Foo(1))));
|
Bar<Bar<Bar<Foo>>> bar = new Bar<>(new Bar<>(new Bar<>(new Foo(1))));
|
||||||
String expectedJson = "{\"t\":{\"t\":{\"t\":{\"b\":1}}}}";
|
String expectedJson = "{\"t\":{\"t\":{\"t\":{\"b\":1}}}}";
|
||||||
|
|
|
@ -15,6 +15,12 @@
|
||||||
*/
|
*/
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertNull;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
import static org.junit.Assert.fail;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.GsonBuilder;
|
import com.google.gson.GsonBuilder;
|
||||||
import com.google.gson.JsonStreamParser;
|
import com.google.gson.JsonStreamParser;
|
||||||
|
@ -30,7 +36,8 @@ import java.io.StringWriter;
|
||||||
import java.io.Writer;
|
import java.io.Writer;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import junit.framework.TestCase;
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Functional tests for the support of {@link Reader}s and {@link Writer}s.
|
* Functional tests for the support of {@link Reader}s and {@link Writer}s.
|
||||||
|
@ -38,15 +45,15 @@ import junit.framework.TestCase;
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
* @author Joel Leitch
|
* @author Joel Leitch
|
||||||
*/
|
*/
|
||||||
public class ReadersWritersTest extends TestCase {
|
public class ReadersWritersTest {
|
||||||
private Gson gson;
|
private Gson gson;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
gson = new Gson();
|
gson = new Gson();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testWriterForSerialization() throws Exception {
|
public void testWriterForSerialization() throws Exception {
|
||||||
Writer writer = new StringWriter();
|
Writer writer = new StringWriter();
|
||||||
BagOfPrimitives src = new BagOfPrimitives();
|
BagOfPrimitives src = new BagOfPrimitives();
|
||||||
|
@ -54,6 +61,7 @@ public class ReadersWritersTest extends TestCase {
|
||||||
assertEquals(src.getExpectedJson(), writer.toString());
|
assertEquals(src.getExpectedJson(), writer.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testReaderForDeserialization() throws Exception {
|
public void testReaderForDeserialization() throws Exception {
|
||||||
BagOfPrimitives expected = new BagOfPrimitives();
|
BagOfPrimitives expected = new BagOfPrimitives();
|
||||||
Reader json = new StringReader(expected.getExpectedJson());
|
Reader json = new StringReader(expected.getExpectedJson());
|
||||||
|
@ -61,18 +69,21 @@ public class ReadersWritersTest extends TestCase {
|
||||||
assertEquals(expected, actual);
|
assertEquals(expected, actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testTopLevelNullObjectSerializationWithWriter() {
|
public void testTopLevelNullObjectSerializationWithWriter() {
|
||||||
StringWriter writer = new StringWriter();
|
StringWriter writer = new StringWriter();
|
||||||
gson.toJson(null, writer);
|
gson.toJson(null, writer);
|
||||||
assertEquals("null", writer.toString());
|
assertEquals("null", writer.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testTopLevelNullObjectDeserializationWithReader() {
|
public void testTopLevelNullObjectDeserializationWithReader() {
|
||||||
StringReader reader = new StringReader("null");
|
StringReader reader = new StringReader("null");
|
||||||
Integer nullIntObject = gson.fromJson(reader, Integer.class);
|
Integer nullIntObject = gson.fromJson(reader, Integer.class);
|
||||||
assertNull(nullIntObject);
|
assertNull(nullIntObject);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testTopLevelNullObjectSerializationWithWriterAndSerializeNulls() {
|
public void testTopLevelNullObjectSerializationWithWriterAndSerializeNulls() {
|
||||||
Gson gson = new GsonBuilder().serializeNulls().create();
|
Gson gson = new GsonBuilder().serializeNulls().create();
|
||||||
StringWriter writer = new StringWriter();
|
StringWriter writer = new StringWriter();
|
||||||
|
@ -80,6 +91,7 @@ public class ReadersWritersTest extends TestCase {
|
||||||
assertEquals("null", writer.toString());
|
assertEquals("null", writer.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testTopLevelNullObjectDeserializationWithReaderAndSerializeNulls() {
|
public void testTopLevelNullObjectDeserializationWithReaderAndSerializeNulls() {
|
||||||
Gson gson = new GsonBuilder().serializeNulls().create();
|
Gson gson = new GsonBuilder().serializeNulls().create();
|
||||||
StringReader reader = new StringReader("null");
|
StringReader reader = new StringReader("null");
|
||||||
|
@ -87,6 +99,7 @@ public class ReadersWritersTest extends TestCase {
|
||||||
assertNull(nullIntObject);
|
assertNull(nullIntObject);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testReadWriteTwoStrings() throws IOException {
|
public void testReadWriteTwoStrings() throws IOException {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
CharArrayWriter writer = new CharArrayWriter();
|
CharArrayWriter writer = new CharArrayWriter();
|
||||||
|
@ -100,6 +113,7 @@ public class ReadersWritersTest extends TestCase {
|
||||||
assertEquals("two", actualTwo);
|
assertEquals("two", actualTwo);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testReadWriteTwoObjects() throws IOException {
|
public void testReadWriteTwoObjects() throws IOException {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
CharArrayWriter writer = new CharArrayWriter();
|
CharArrayWriter writer = new CharArrayWriter();
|
||||||
|
@ -116,6 +130,7 @@ public class ReadersWritersTest extends TestCase {
|
||||||
assertFalse(parser.hasNext());
|
assertFalse(parser.hasNext());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testTypeMismatchThrowsJsonSyntaxExceptionForStrings() {
|
public void testTypeMismatchThrowsJsonSyntaxExceptionForStrings() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson("true", new TypeToken<Map<String, String>>() {}.getType());
|
gson.fromJson("true", new TypeToken<Map<String, String>>() {}.getType());
|
||||||
|
@ -124,6 +139,7 @@ public class ReadersWritersTest extends TestCase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testTypeMismatchThrowsJsonSyntaxExceptionForReaders() {
|
public void testTypeMismatchThrowsJsonSyntaxExceptionForReaders() {
|
||||||
try {
|
try {
|
||||||
gson.fromJson(new StringReader("true"), new TypeToken<Map<String, String>>() {}.getType());
|
gson.fromJson(new StringReader("true"), new TypeToken<Map<String, String>>() {}.getType());
|
||||||
|
@ -136,6 +152,7 @@ public class ReadersWritersTest extends TestCase {
|
||||||
* Verifies that passing an {@link Appendable} which is not an instance of {@link Writer}
|
* Verifies that passing an {@link Appendable} which is not an instance of {@link Writer}
|
||||||
* to {@code Gson.toJson} works correctly.
|
* to {@code Gson.toJson} works correctly.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testToJsonAppendable() {
|
public void testToJsonAppendable() {
|
||||||
class CustomAppendable implements Appendable {
|
class CustomAppendable implements Appendable {
|
||||||
final StringBuilder stringBuilder = new StringBuilder();
|
final StringBuilder stringBuilder = new StringBuilder();
|
||||||
|
|
|
@ -15,11 +15,7 @@
|
||||||
*/
|
*/
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
import java.io.IOException;
|
import static org.junit.Assert.assertEquals;
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import junit.framework.TestCase;
|
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.JsonElement;
|
import com.google.gson.JsonElement;
|
||||||
|
@ -33,11 +29,15 @@ import com.google.gson.internal.Streams;
|
||||||
import com.google.gson.reflect.TypeToken;
|
import com.google.gson.reflect.TypeToken;
|
||||||
import com.google.gson.stream.JsonReader;
|
import com.google.gson.stream.JsonReader;
|
||||||
import com.google.gson.stream.JsonWriter;
|
import com.google.gson.stream.JsonWriter;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Functional tests for the RuntimeTypeAdapterFactory feature in extras.
|
* Functional tests for the RuntimeTypeAdapterFactory feature in extras.
|
||||||
*/
|
*/
|
||||||
public final class RuntimeTypeAdapterFactoryFunctionalTest extends TestCase {
|
public final class RuntimeTypeAdapterFactoryFunctionalTest {
|
||||||
|
|
||||||
private final Gson gson = new Gson();
|
private final Gson gson = new Gson();
|
||||||
|
|
||||||
|
@ -45,6 +45,7 @@ public final class RuntimeTypeAdapterFactoryFunctionalTest extends TestCase {
|
||||||
* This test also ensures that {@link TypeAdapterFactory} registered through {@link JsonAdapter}
|
* This test also ensures that {@link TypeAdapterFactory} registered through {@link JsonAdapter}
|
||||||
* work correctly for {@link Gson#getDelegateAdapter(TypeAdapterFactory, TypeToken)}.
|
* work correctly for {@link Gson#getDelegateAdapter(TypeAdapterFactory, TypeToken)}.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testSubclassesAutomaticallySerialized() throws Exception {
|
public void testSubclassesAutomaticallySerialized() throws Exception {
|
||||||
Shape shape = new Circle(25);
|
Shape shape = new Circle(25);
|
||||||
String json = gson.toJson(shape);
|
String json = gson.toJson(shape);
|
||||||
|
|
|
@ -16,18 +16,21 @@
|
||||||
|
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.GsonBuilder;
|
import com.google.gson.GsonBuilder;
|
||||||
import com.google.gson.common.TestTypes.BagOfPrimitives;
|
import com.google.gson.common.TestTypes.BagOfPrimitives;
|
||||||
|
import org.junit.Before;
|
||||||
import junit.framework.TestCase;
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests for security-related aspects of Gson
|
* Tests for security-related aspects of Gson
|
||||||
*
|
*
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
*/
|
*/
|
||||||
public class SecurityTest extends TestCase {
|
public class SecurityTest {
|
||||||
/**
|
/**
|
||||||
* Keep this in sync with Gson.JSON_NON_EXECUTABLE_PREFIX
|
* Keep this in sync with Gson.JSON_NON_EXECUTABLE_PREFIX
|
||||||
*/
|
*/
|
||||||
|
@ -35,18 +38,19 @@ public class SecurityTest extends TestCase {
|
||||||
|
|
||||||
private GsonBuilder gsonBuilder;
|
private GsonBuilder gsonBuilder;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
gsonBuilder = new GsonBuilder().setLenient();
|
gsonBuilder = new GsonBuilder().setLenient();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNonExecutableJsonSerialization() {
|
public void testNonExecutableJsonSerialization() {
|
||||||
Gson gson = gsonBuilder.generateNonExecutableJson().create();
|
Gson gson = gsonBuilder.generateNonExecutableJson().create();
|
||||||
String json = gson.toJson(new BagOfPrimitives());
|
String json = gson.toJson(new BagOfPrimitives());
|
||||||
assertTrue(json.startsWith(JSON_NON_EXECUTABLE_PREFIX));
|
assertTrue(json.startsWith(JSON_NON_EXECUTABLE_PREFIX));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNonExecutableJsonDeserialization() {
|
public void testNonExecutableJsonDeserialization() {
|
||||||
String json = JSON_NON_EXECUTABLE_PREFIX + "{longValue:1}";
|
String json = JSON_NON_EXECUTABLE_PREFIX + "{longValue:1}";
|
||||||
Gson gson = gsonBuilder.create();
|
Gson gson = gsonBuilder.create();
|
||||||
|
@ -54,6 +58,7 @@ public class SecurityTest extends TestCase {
|
||||||
assertEquals(1, target.longValue);
|
assertEquals(1, target.longValue);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testJsonWithNonExectuableTokenSerialization() {
|
public void testJsonWithNonExectuableTokenSerialization() {
|
||||||
Gson gson = gsonBuilder.generateNonExecutableJson().create();
|
Gson gson = gsonBuilder.generateNonExecutableJson().create();
|
||||||
String json = gson.toJson(JSON_NON_EXECUTABLE_PREFIX);
|
String json = gson.toJson(JSON_NON_EXECUTABLE_PREFIX);
|
||||||
|
@ -64,6 +69,7 @@ public class SecurityTest extends TestCase {
|
||||||
* Gson should be able to deserialize a stream with non-exectuable token even if it is created
|
* Gson should be able to deserialize a stream with non-exectuable token even if it is created
|
||||||
* without {@link GsonBuilder#generateNonExecutableJson()}.
|
* without {@link GsonBuilder#generateNonExecutableJson()}.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testJsonWithNonExectuableTokenWithRegularGsonDeserialization() {
|
public void testJsonWithNonExectuableTokenWithRegularGsonDeserialization() {
|
||||||
Gson gson = gsonBuilder.create();
|
Gson gson = gsonBuilder.create();
|
||||||
String json = JSON_NON_EXECUTABLE_PREFIX + "{stringValue:')]}\\u0027\\n'}";
|
String json = JSON_NON_EXECUTABLE_PREFIX + "{stringValue:')]}\\u0027\\n'}";
|
||||||
|
@ -75,6 +81,7 @@ public class SecurityTest extends TestCase {
|
||||||
* Gson should be able to deserialize a stream with non-exectuable token if it is created
|
* Gson should be able to deserialize a stream with non-exectuable token if it is created
|
||||||
* with {@link GsonBuilder#generateNonExecutableJson()}.
|
* with {@link GsonBuilder#generateNonExecutableJson()}.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testJsonWithNonExectuableTokenWithConfiguredGsonDeserialization() {
|
public void testJsonWithNonExectuableTokenWithConfiguredGsonDeserialization() {
|
||||||
// Gson should be able to deserialize a stream with non-exectuable token even if it is created
|
// Gson should be able to deserialize a stream with non-exectuable token even if it is created
|
||||||
Gson gson = gsonBuilder.generateNonExecutableJson().create();
|
Gson gson = gsonBuilder.generateNonExecutableJson().create();
|
||||||
|
|
|
@ -15,20 +15,23 @@
|
||||||
*/
|
*/
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.annotations.SerializedName;
|
import com.google.gson.annotations.SerializedName;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
import junit.framework.TestCase;
|
public final class SerializedNameTest {
|
||||||
|
|
||||||
public final class SerializedNameTest extends TestCase {
|
|
||||||
private final Gson gson = new Gson();
|
private final Gson gson = new Gson();
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testFirstNameIsChosenForSerialization() {
|
public void testFirstNameIsChosenForSerialization() {
|
||||||
MyClass target = new MyClass("v1", "v2");
|
MyClass target = new MyClass("v1", "v2");
|
||||||
// Ensure name1 occurs exactly once, and name2 and name3 don't appear
|
// Ensure name1 occurs exactly once, and name2 and name3 don't appear
|
||||||
assertEquals("{\"name\":\"v1\",\"name1\":\"v2\"}", gson.toJson(target));
|
assertEquals("{\"name\":\"v1\",\"name1\":\"v2\"}", gson.toJson(target));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testMultipleNamesDeserializedCorrectly() {
|
public void testMultipleNamesDeserializedCorrectly() {
|
||||||
assertEquals("v1", gson.fromJson("{'name':'v1'}", MyClass.class).a);
|
assertEquals("v1", gson.fromJson("{'name':'v1'}", MyClass.class).a);
|
||||||
|
|
||||||
|
@ -38,6 +41,7 @@ public final class SerializedNameTest extends TestCase {
|
||||||
assertEquals("v3", gson.fromJson("{'name3':'v3'}", MyClass.class).b);
|
assertEquals("v3", gson.fromJson("{'name3':'v3'}", MyClass.class).b);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testMultipleNamesInTheSameString() {
|
public void testMultipleNamesInTheSameString() {
|
||||||
// The last value takes precedence
|
// The last value takes precedence
|
||||||
assertEquals("v3", gson.fromJson("{'name1':'v1','name2':'v2','name3':'v3'}", MyClass.class).b);
|
assertEquals("v3", gson.fromJson("{'name1':'v1','name2':'v2','name3':'v3'}", MyClass.class).b);
|
||||||
|
|
|
@ -16,6 +16,11 @@
|
||||||
|
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertNull;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
import static org.junit.Assert.fail;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.GsonBuilder;
|
import com.google.gson.GsonBuilder;
|
||||||
import com.google.gson.JsonArray;
|
import com.google.gson.JsonArray;
|
||||||
|
@ -33,14 +38,15 @@ import java.util.Collections;
|
||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import junit.framework.TestCase;
|
import org.junit.Test;
|
||||||
|
|
||||||
public final class StreamingTypeAdaptersTest extends TestCase {
|
public final class StreamingTypeAdaptersTest {
|
||||||
private Gson miniGson = new GsonBuilder().create();
|
private Gson miniGson = new GsonBuilder().create();
|
||||||
private TypeAdapter<Truck> truckAdapter = miniGson.getAdapter(Truck.class);
|
private TypeAdapter<Truck> truckAdapter = miniGson.getAdapter(Truck.class);
|
||||||
private TypeAdapter<Map<String, Double>> mapAdapter
|
private TypeAdapter<Map<String, Double>> mapAdapter
|
||||||
= miniGson.getAdapter(new TypeToken<Map<String, Double>>() {});
|
= miniGson.getAdapter(new TypeToken<Map<String, Double>>() {});
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSerialize() {
|
public void testSerialize() {
|
||||||
Truck truck = new Truck();
|
Truck truck = new Truck();
|
||||||
truck.passengers = Arrays.asList(new Person("Jesse", 29), new Person("Jodie", 29));
|
truck.passengers = Arrays.asList(new Person("Jesse", 29), new Person("Jodie", 29));
|
||||||
|
@ -51,14 +57,16 @@ public final class StreamingTypeAdaptersTest extends TestCase {
|
||||||
truckAdapter.toJson(truck).replace('\"', '\''));
|
truckAdapter.toJson(truck).replace('\"', '\''));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserialize() throws IOException {
|
public void testDeserialize() throws IOException {
|
||||||
String json = "{'horsePower':300.0,"
|
String json = "{'horsePower':300.0,"
|
||||||
+ "'passengers':[{'age':29,'name':'Jesse'},{'age':29,'name':'Jodie'}]}";
|
+ "'passengers':[{'age':29,'name':'Jesse'},{'age':29,'name':'Jodie'}]}";
|
||||||
Truck truck = truckAdapter.fromJson(json.replace('\'', '\"'));
|
Truck truck = truckAdapter.fromJson(json.replace('\'', '\"'));
|
||||||
assertEquals(300.0, truck.horsePower);
|
assertEquals(300.0, truck.horsePower, 0);
|
||||||
assertEquals(Arrays.asList(new Person("Jesse", 29), new Person("Jodie", 29)), truck.passengers);
|
assertEquals(Arrays.asList(new Person("Jesse", 29), new Person("Jodie", 29)), truck.passengers);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSerializeNullField() {
|
public void testSerializeNullField() {
|
||||||
Truck truck = new Truck();
|
Truck truck = new Truck();
|
||||||
truck.passengers = null;
|
truck.passengers = null;
|
||||||
|
@ -66,11 +74,13 @@ public final class StreamingTypeAdaptersTest extends TestCase {
|
||||||
truckAdapter.toJson(truck).replace('\"', '\''));
|
truckAdapter.toJson(truck).replace('\"', '\''));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserializeNullField() throws IOException {
|
public void testDeserializeNullField() throws IOException {
|
||||||
Truck truck = truckAdapter.fromJson("{'horsePower':0.0,'passengers':null}".replace('\'', '\"'));
|
Truck truck = truckAdapter.fromJson("{'horsePower':0.0,'passengers':null}".replace('\'', '\"'));
|
||||||
assertNull(truck.passengers);
|
assertNull(truck.passengers);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSerializeNullObject() {
|
public void testSerializeNullObject() {
|
||||||
Truck truck = new Truck();
|
Truck truck = new Truck();
|
||||||
truck.passengers = Arrays.asList((Person) null);
|
truck.passengers = Arrays.asList((Person) null);
|
||||||
|
@ -78,11 +88,13 @@ public final class StreamingTypeAdaptersTest extends TestCase {
|
||||||
truckAdapter.toJson(truck).replace('\"', '\''));
|
truckAdapter.toJson(truck).replace('\"', '\''));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserializeNullObject() throws IOException {
|
public void testDeserializeNullObject() throws IOException {
|
||||||
Truck truck = truckAdapter.fromJson("{'horsePower':0.0,'passengers':[null]}".replace('\'', '\"'));
|
Truck truck = truckAdapter.fromJson("{'horsePower':0.0,'passengers':[null]}".replace('\'', '\"'));
|
||||||
assertEquals(Arrays.asList((Person) null), truck.passengers);
|
assertEquals(Arrays.asList((Person) null), truck.passengers);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSerializeWithCustomTypeAdapter() {
|
public void testSerializeWithCustomTypeAdapter() {
|
||||||
usePersonNameAdapter();
|
usePersonNameAdapter();
|
||||||
Truck truck = new Truck();
|
Truck truck = new Truck();
|
||||||
|
@ -91,6 +103,7 @@ public final class StreamingTypeAdaptersTest extends TestCase {
|
||||||
truckAdapter.toJson(truck).replace('\"', '\''));
|
truckAdapter.toJson(truck).replace('\"', '\''));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserializeWithCustomTypeAdapter() throws IOException {
|
public void testDeserializeWithCustomTypeAdapter() throws IOException {
|
||||||
usePersonNameAdapter();
|
usePersonNameAdapter();
|
||||||
Truck truck = truckAdapter.fromJson("{'horsePower':0.0,'passengers':['Jesse','Jodie']}".replace('\'', '\"'));
|
Truck truck = truckAdapter.fromJson("{'horsePower':0.0,'passengers':['Jesse','Jodie']}".replace('\'', '\"'));
|
||||||
|
@ -111,6 +124,7 @@ public final class StreamingTypeAdaptersTest extends TestCase {
|
||||||
truckAdapter = miniGson.getAdapter(Truck.class);
|
truckAdapter = miniGson.getAdapter(Truck.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSerializeMap() {
|
public void testSerializeMap() {
|
||||||
Map<String, Double> map = new LinkedHashMap<>();
|
Map<String, Double> map = new LinkedHashMap<>();
|
||||||
map.put("a", 5.0);
|
map.put("a", 5.0);
|
||||||
|
@ -118,6 +132,7 @@ public final class StreamingTypeAdaptersTest extends TestCase {
|
||||||
assertEquals("{'a':5.0,'b':10.0}", mapAdapter.toJson(map).replace('"', '\''));
|
assertEquals("{'a':5.0,'b':10.0}", mapAdapter.toJson(map).replace('"', '\''));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserializeMap() throws IOException {
|
public void testDeserializeMap() throws IOException {
|
||||||
Map<String, Double> map = new LinkedHashMap<>();
|
Map<String, Double> map = new LinkedHashMap<>();
|
||||||
map.put("a", 5.0);
|
map.put("a", 5.0);
|
||||||
|
@ -125,23 +140,27 @@ public final class StreamingTypeAdaptersTest extends TestCase {
|
||||||
assertEquals(map, mapAdapter.fromJson("{'a':5.0,'b':10.0}".replace('\'', '\"')));
|
assertEquals(map, mapAdapter.fromJson("{'a':5.0,'b':10.0}".replace('\'', '\"')));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSerialize1dArray() {
|
public void testSerialize1dArray() {
|
||||||
TypeAdapter<double[]> arrayAdapter = miniGson.getAdapter(new TypeToken<double[]>() {});
|
TypeAdapter<double[]> arrayAdapter = miniGson.getAdapter(new TypeToken<double[]>() {});
|
||||||
assertEquals("[1.0,2.0,3.0]", arrayAdapter.toJson(new double[]{ 1.0, 2.0, 3.0 }));
|
assertEquals("[1.0,2.0,3.0]", arrayAdapter.toJson(new double[]{ 1.0, 2.0, 3.0 }));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserialize1dArray() throws IOException {
|
public void testDeserialize1dArray() throws IOException {
|
||||||
TypeAdapter<double[]> arrayAdapter = miniGson.getAdapter(new TypeToken<double[]>() {});
|
TypeAdapter<double[]> arrayAdapter = miniGson.getAdapter(new TypeToken<double[]>() {});
|
||||||
double[] array = arrayAdapter.fromJson("[1.0,2.0,3.0]");
|
double[] array = arrayAdapter.fromJson("[1.0,2.0,3.0]");
|
||||||
assertTrue(Arrays.toString(array), Arrays.equals(new double[]{1.0, 2.0, 3.0}, array));
|
assertTrue(Arrays.toString(array), Arrays.equals(new double[]{1.0, 2.0, 3.0}, array));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSerialize2dArray() {
|
public void testSerialize2dArray() {
|
||||||
TypeAdapter<double[][]> arrayAdapter = miniGson.getAdapter(new TypeToken<double[][]>() {});
|
TypeAdapter<double[][]> arrayAdapter = miniGson.getAdapter(new TypeToken<double[][]>() {});
|
||||||
double[][] array = { {1.0, 2.0 }, { 3.0 } };
|
double[][] array = { {1.0, 2.0 }, { 3.0 } };
|
||||||
assertEquals("[[1.0,2.0],[3.0]]", arrayAdapter.toJson(array));
|
assertEquals("[[1.0,2.0],[3.0]]", arrayAdapter.toJson(array));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserialize2dArray() throws IOException {
|
public void testDeserialize2dArray() throws IOException {
|
||||||
TypeAdapter<double[][]> arrayAdapter = miniGson.getAdapter(new TypeToken<double[][]>() {});
|
TypeAdapter<double[][]> arrayAdapter = miniGson.getAdapter(new TypeToken<double[][]>() {});
|
||||||
double[][] array = arrayAdapter.fromJson("[[1.0,2.0],[3.0]]");
|
double[][] array = arrayAdapter.fromJson("[[1.0,2.0],[3.0]]");
|
||||||
|
@ -149,6 +168,7 @@ public final class StreamingTypeAdaptersTest extends TestCase {
|
||||||
assertTrue(Arrays.toString(array), Arrays.deepEquals(expected, array));
|
assertTrue(Arrays.toString(array), Arrays.deepEquals(expected, array));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNullSafe() {
|
public void testNullSafe() {
|
||||||
TypeAdapter<Person> typeAdapter = new TypeAdapter<Person>() {
|
TypeAdapter<Person> typeAdapter = new TypeAdapter<Person>() {
|
||||||
@Override public Person read(JsonReader in) throws IOException {
|
@Override public Person read(JsonReader in) throws IOException {
|
||||||
|
@ -179,11 +199,12 @@ public final class StreamingTypeAdaptersTest extends TestCase {
|
||||||
assertEquals("{\"horsePower\":1.0,\"passengers\":[null,\"jesse,30\"]}",
|
assertEquals("{\"horsePower\":1.0,\"passengers\":[null,\"jesse,30\"]}",
|
||||||
gson.toJson(truck, Truck.class));
|
gson.toJson(truck, Truck.class));
|
||||||
truck = gson.fromJson(json, Truck.class);
|
truck = gson.fromJson(json, Truck.class);
|
||||||
assertEquals(1.0D, truck.horsePower);
|
assertEquals(1.0D, truck.horsePower, 0);
|
||||||
assertNull(truck.passengers.get(0));
|
assertNull(truck.passengers.get(0));
|
||||||
assertEquals("jesse", truck.passengers.get(1).name);
|
assertEquals("jesse", truck.passengers.get(1).name);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSerializeRecursive() {
|
public void testSerializeRecursive() {
|
||||||
TypeAdapter<Node> nodeAdapter = miniGson.getAdapter(Node.class);
|
TypeAdapter<Node> nodeAdapter = miniGson.getAdapter(Node.class);
|
||||||
Node root = new Node("root");
|
Node root = new Node("root");
|
||||||
|
@ -195,6 +216,7 @@ public final class StreamingTypeAdaptersTest extends TestCase {
|
||||||
nodeAdapter.toJson(root).replace('"', '\''));
|
nodeAdapter.toJson(root).replace('"', '\''));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testFromJsonTree() {
|
public void testFromJsonTree() {
|
||||||
JsonObject truckObject = new JsonObject();
|
JsonObject truckObject = new JsonObject();
|
||||||
truckObject.add("horsePower", new JsonPrimitive(300));
|
truckObject.add("horsePower", new JsonPrimitive(300));
|
||||||
|
@ -206,7 +228,7 @@ public final class StreamingTypeAdaptersTest extends TestCase {
|
||||||
truckObject.add("passengers", passengersArray);
|
truckObject.add("passengers", passengersArray);
|
||||||
|
|
||||||
Truck truck = truckAdapter.fromJsonTree(truckObject);
|
Truck truck = truckAdapter.fromJsonTree(truckObject);
|
||||||
assertEquals(300.0, truck.horsePower);
|
assertEquals(300.0, truck.horsePower, 0);
|
||||||
assertEquals(Arrays.asList(new Person("Jesse", 30)), truck.passengers);
|
assertEquals(Arrays.asList(new Person("Jesse", 30)), truck.passengers);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -1,8 +1,10 @@
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
import junit.framework.TestCase;
|
import com.google.gson.Gson;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Functional tests for Json serialization and deserialization of strings.
|
* Functional tests for Json serialization and deserialization of strings.
|
||||||
|
@ -10,73 +12,83 @@ import junit.framework.TestCase;
|
||||||
* @author Inderjeet Singh
|
* @author Inderjeet Singh
|
||||||
* @author Joel Leitch
|
* @author Joel Leitch
|
||||||
*/
|
*/
|
||||||
public class StringTest extends TestCase {
|
public class StringTest {
|
||||||
private Gson gson;
|
private Gson gson;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
super.setUp();
|
|
||||||
gson = new Gson();
|
gson = new Gson();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testStringValueSerialization() throws Exception {
|
public void testStringValueSerialization() throws Exception {
|
||||||
String value = "someRandomStringValue";
|
String value = "someRandomStringValue";
|
||||||
assertEquals('"' + value + '"', gson.toJson(value));
|
assertEquals('"' + value + '"', gson.toJson(value));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testStringValueDeserialization() throws Exception {
|
public void testStringValueDeserialization() throws Exception {
|
||||||
String value = "someRandomStringValue";
|
String value = "someRandomStringValue";
|
||||||
String actual = gson.fromJson("\"" + value + "\"", String.class);
|
String actual = gson.fromJson("\"" + value + "\"", String.class);
|
||||||
assertEquals(value, actual);
|
assertEquals(value, actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSingleQuoteInStringSerialization() throws Exception {
|
public void testSingleQuoteInStringSerialization() throws Exception {
|
||||||
String valueWithQuotes = "beforeQuote'afterQuote";
|
String valueWithQuotes = "beforeQuote'afterQuote";
|
||||||
String jsonRepresentation = gson.toJson(valueWithQuotes);
|
String jsonRepresentation = gson.toJson(valueWithQuotes);
|
||||||
assertEquals(valueWithQuotes, gson.fromJson(jsonRepresentation, String.class));
|
assertEquals(valueWithQuotes, gson.fromJson(jsonRepresentation, String.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testEscapedCtrlNInStringSerialization() throws Exception {
|
public void testEscapedCtrlNInStringSerialization() throws Exception {
|
||||||
String value = "a\nb";
|
String value = "a\nb";
|
||||||
String json = gson.toJson(value);
|
String json = gson.toJson(value);
|
||||||
assertEquals("\"a\\nb\"", json);
|
assertEquals("\"a\\nb\"", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testEscapedCtrlNInStringDeserialization() throws Exception {
|
public void testEscapedCtrlNInStringDeserialization() throws Exception {
|
||||||
String json = "'a\\nb'";
|
String json = "'a\\nb'";
|
||||||
String actual = gson.fromJson(json, String.class);
|
String actual = gson.fromJson(json, String.class);
|
||||||
assertEquals("a\nb", actual);
|
assertEquals("a\nb", actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testEscapedCtrlRInStringSerialization() throws Exception {
|
public void testEscapedCtrlRInStringSerialization() throws Exception {
|
||||||
String value = "a\rb";
|
String value = "a\rb";
|
||||||
String json = gson.toJson(value);
|
String json = gson.toJson(value);
|
||||||
assertEquals("\"a\\rb\"", json);
|
assertEquals("\"a\\rb\"", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testEscapedCtrlRInStringDeserialization() throws Exception {
|
public void testEscapedCtrlRInStringDeserialization() throws Exception {
|
||||||
String json = "'a\\rb'";
|
String json = "'a\\rb'";
|
||||||
String actual = gson.fromJson(json, String.class);
|
String actual = gson.fromJson(json, String.class);
|
||||||
assertEquals("a\rb", actual);
|
assertEquals("a\rb", actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testEscapedBackslashInStringSerialization() throws Exception {
|
public void testEscapedBackslashInStringSerialization() throws Exception {
|
||||||
String value = "a\\b";
|
String value = "a\\b";
|
||||||
String json = gson.toJson(value);
|
String json = gson.toJson(value);
|
||||||
assertEquals("\"a\\\\b\"", json);
|
assertEquals("\"a\\\\b\"", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testEscapedBackslashInStringDeserialization() throws Exception {
|
public void testEscapedBackslashInStringDeserialization() throws Exception {
|
||||||
String actual = gson.fromJson("'a\\\\b'", String.class);
|
String actual = gson.fromJson("'a\\\\b'", String.class);
|
||||||
assertEquals("a\\b", actual);
|
assertEquals("a\\b", actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSingleQuoteInStringDeserialization() throws Exception {
|
public void testSingleQuoteInStringDeserialization() throws Exception {
|
||||||
String value = "beforeQuote'afterQuote";
|
String value = "beforeQuote'afterQuote";
|
||||||
String actual = gson.fromJson("\"" + value + "\"", String.class);
|
String actual = gson.fromJson("\"" + value + "\"", String.class);
|
||||||
assertEquals(value, actual);
|
assertEquals(value, actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testEscapingQuotesInStringSerialization() throws Exception {
|
public void testEscapingQuotesInStringSerialization() throws Exception {
|
||||||
String valueWithQuotes = "beforeQuote\"afterQuote";
|
String valueWithQuotes = "beforeQuote\"afterQuote";
|
||||||
String jsonRepresentation = gson.toJson(valueWithQuotes);
|
String jsonRepresentation = gson.toJson(valueWithQuotes);
|
||||||
|
@ -84,6 +96,7 @@ public class StringTest extends TestCase {
|
||||||
assertEquals(valueWithQuotes, target);
|
assertEquals(valueWithQuotes, target);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testEscapingQuotesInStringDeserialization() throws Exception {
|
public void testEscapingQuotesInStringDeserialization() throws Exception {
|
||||||
String value = "beforeQuote\\\"afterQuote";
|
String value = "beforeQuote\\\"afterQuote";
|
||||||
String actual = gson.fromJson("\"" + value + "\"", String.class);
|
String actual = gson.fromJson("\"" + value + "\"", String.class);
|
||||||
|
@ -91,12 +104,14 @@ public class StringTest extends TestCase {
|
||||||
assertEquals(expected, actual);
|
assertEquals(expected, actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testStringValueAsSingleElementArraySerialization() throws Exception {
|
public void testStringValueAsSingleElementArraySerialization() throws Exception {
|
||||||
String[] target = {"abc"};
|
String[] target = {"abc"};
|
||||||
assertEquals("[\"abc\"]", gson.toJson(target));
|
assertEquals("[\"abc\"]", gson.toJson(target));
|
||||||
assertEquals("[\"abc\"]", gson.toJson(target, String[].class));
|
assertEquals("[\"abc\"]", gson.toJson(target, String[].class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testStringWithEscapedSlashDeserialization() {
|
public void testStringWithEscapedSlashDeserialization() {
|
||||||
String value = "/";
|
String value = "/";
|
||||||
String json = "'\\/'";
|
String json = "'\\/'";
|
||||||
|
@ -107,6 +122,7 @@ public class StringTest extends TestCase {
|
||||||
/**
|
/**
|
||||||
* Created in response to http://groups.google.com/group/google-gson/browse_thread/thread/2431d4a3d0d6cb23
|
* Created in response to http://groups.google.com/group/google-gson/browse_thread/thread/2431d4a3d0d6cb23
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testAssignmentCharSerialization() {
|
public void testAssignmentCharSerialization() {
|
||||||
String value = "abc=";
|
String value = "abc=";
|
||||||
String json = gson.toJson(value);
|
String json = gson.toJson(value);
|
||||||
|
@ -116,6 +132,7 @@ public class StringTest extends TestCase {
|
||||||
/**
|
/**
|
||||||
* Created in response to http://groups.google.com/group/google-gson/browse_thread/thread/2431d4a3d0d6cb23
|
* Created in response to http://groups.google.com/group/google-gson/browse_thread/thread/2431d4a3d0d6cb23
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testAssignmentCharDeserialization() {
|
public void testAssignmentCharDeserialization() {
|
||||||
String json = "\"abc=\"";
|
String json = "\"abc=\"";
|
||||||
String value = gson.fromJson(json, String.class);
|
String value = gson.fromJson(json, String.class);
|
||||||
|
@ -126,12 +143,14 @@ public class StringTest extends TestCase {
|
||||||
assertEquals("abc=", value);
|
assertEquals("abc=", value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testJavascriptKeywordsInStringSerialization() {
|
public void testJavascriptKeywordsInStringSerialization() {
|
||||||
String value = "null true false function";
|
String value = "null true false function";
|
||||||
String json = gson.toJson(value);
|
String json = gson.toJson(value);
|
||||||
assertEquals("\"" + value + "\"", json);
|
assertEquals("\"" + value + "\"", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testJavascriptKeywordsInStringDeserialization() {
|
public void testJavascriptKeywordsInStringDeserialization() {
|
||||||
String json = "'null true false function'";
|
String json = "'null true false function'";
|
||||||
String value = gson.fromJson(json, String.class);
|
String value = gson.fromJson(json, String.class);
|
||||||
|
|
|
@ -16,12 +16,9 @@
|
||||||
|
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
import java.lang.reflect.Type;
|
import static org.junit.Assert.assertEquals;
|
||||||
import java.math.BigDecimal;
|
import static org.junit.Assert.fail;
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.Collection;
|
|
||||||
import java.util.LinkedList;
|
|
||||||
import java.util.List;
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.GsonBuilder;
|
import com.google.gson.GsonBuilder;
|
||||||
import com.google.gson.ToNumberPolicy;
|
import com.google.gson.ToNumberPolicy;
|
||||||
|
@ -29,9 +26,16 @@ import com.google.gson.ToNumberStrategy;
|
||||||
import com.google.gson.internal.LazilyParsedNumber;
|
import com.google.gson.internal.LazilyParsedNumber;
|
||||||
import com.google.gson.reflect.TypeToken;
|
import com.google.gson.reflect.TypeToken;
|
||||||
import com.google.gson.stream.JsonReader;
|
import com.google.gson.stream.JsonReader;
|
||||||
import junit.framework.TestCase;
|
import java.lang.reflect.Type;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.LinkedList;
|
||||||
|
import java.util.List;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
public class ToNumberPolicyFunctionalTest extends TestCase {
|
public class ToNumberPolicyFunctionalTest {
|
||||||
|
@Test
|
||||||
public void testDefault() {
|
public void testDefault() {
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
assertEquals(null, gson.fromJson("null", Object.class));
|
assertEquals(null, gson.fromJson("null", Object.class));
|
||||||
|
@ -40,6 +44,7 @@ public class ToNumberPolicyFunctionalTest extends TestCase {
|
||||||
assertEquals(new LazilyParsedNumber("10"), gson.fromJson("10", Number.class));
|
assertEquals(new LazilyParsedNumber("10"), gson.fromJson("10", Number.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testAsDoubles() {
|
public void testAsDoubles() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.setObjectToNumberStrategy(ToNumberPolicy.DOUBLE)
|
.setObjectToNumberStrategy(ToNumberPolicy.DOUBLE)
|
||||||
|
@ -51,6 +56,7 @@ public class ToNumberPolicyFunctionalTest extends TestCase {
|
||||||
assertEquals(10.0, gson.fromJson("10", Number.class));
|
assertEquals(10.0, gson.fromJson("10", Number.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testAsLazilyParsedNumbers() {
|
public void testAsLazilyParsedNumbers() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.setObjectToNumberStrategy(ToNumberPolicy.LAZILY_PARSED_NUMBER)
|
.setObjectToNumberStrategy(ToNumberPolicy.LAZILY_PARSED_NUMBER)
|
||||||
|
@ -62,6 +68,7 @@ public class ToNumberPolicyFunctionalTest extends TestCase {
|
||||||
assertEquals(new LazilyParsedNumber("10"), gson.fromJson("10", Number.class));
|
assertEquals(new LazilyParsedNumber("10"), gson.fromJson("10", Number.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testAsLongsOrDoubles() {
|
public void testAsLongsOrDoubles() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
|
.setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
|
||||||
|
@ -75,6 +82,7 @@ public class ToNumberPolicyFunctionalTest extends TestCase {
|
||||||
assertEquals(10.0, gson.fromJson("10.0", Number.class));
|
assertEquals(10.0, gson.fromJson("10.0", Number.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testAsBigDecimals() {
|
public void testAsBigDecimals() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.setObjectToNumberStrategy(ToNumberPolicy.BIG_DECIMAL)
|
.setObjectToNumberStrategy(ToNumberPolicy.BIG_DECIMAL)
|
||||||
|
@ -90,6 +98,7 @@ public class ToNumberPolicyFunctionalTest extends TestCase {
|
||||||
assertEquals(new BigDecimal("1e400"), gson.fromJson("1e400", BigDecimal.class));
|
assertEquals(new BigDecimal("1e400"), gson.fromJson("1e400", BigDecimal.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testAsListOfLongsOrDoubles() {
|
public void testAsListOfLongsOrDoubles() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
|
.setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
|
||||||
|
@ -107,6 +116,7 @@ public class ToNumberPolicyFunctionalTest extends TestCase {
|
||||||
assertEquals(expected, numbers);
|
assertEquals(expected, numbers);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testCustomStrategiesCannotAffectConcreteDeclaredNumbers() {
|
public void testCustomStrategiesCannotAffectConcreteDeclaredNumbers() {
|
||||||
ToNumberStrategy fail = new ToNumberStrategy() {
|
ToNumberStrategy fail = new ToNumberStrategy() {
|
||||||
@Override
|
@Override
|
||||||
|
|
|
@ -16,6 +16,9 @@
|
||||||
|
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.GsonBuilder;
|
import com.google.gson.GsonBuilder;
|
||||||
import com.google.gson.JsonDeserializationContext;
|
import com.google.gson.JsonDeserializationContext;
|
||||||
|
@ -31,12 +34,13 @@ import java.lang.reflect.Type;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import junit.framework.TestCase;
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Collection of functional tests for DOM tree based type adapters.
|
* Collection of functional tests for DOM tree based type adapters.
|
||||||
*/
|
*/
|
||||||
public class TreeTypeAdaptersTest extends TestCase {
|
public class TreeTypeAdaptersTest {
|
||||||
private static final Id<Student> STUDENT1_ID = new Id<>("5", Student.class);
|
private static final Id<Student> STUDENT1_ID = new Id<>("5", Student.class);
|
||||||
private static final Id<Student> STUDENT2_ID = new Id<>("6", Student.class);
|
private static final Id<Student> STUDENT2_ID = new Id<>("6", Student.class);
|
||||||
private static final Student STUDENT1 = new Student(STUDENT1_ID, "first");
|
private static final Student STUDENT1 = new Student(STUDENT1_ID, "first");
|
||||||
|
@ -49,8 +53,8 @@ public class TreeTypeAdaptersTest extends TestCase {
|
||||||
private Gson gson;
|
private Gson gson;
|
||||||
private Course<HistoryCourse> course;
|
private Course<HistoryCourse> course;
|
||||||
|
|
||||||
@Override
|
@Before
|
||||||
protected void setUp() {
|
public void setUp() {
|
||||||
gson = new GsonBuilder()
|
gson = new GsonBuilder()
|
||||||
.setLenient()
|
.setLenient()
|
||||||
.registerTypeAdapter(Id.class, new IdTreeTypeAdapter())
|
.registerTypeAdapter(Id.class, new IdTreeTypeAdapter())
|
||||||
|
@ -59,6 +63,7 @@ public class TreeTypeAdaptersTest extends TestCase {
|
||||||
new Assignment<HistoryCourse>(null, null), Arrays.asList(STUDENT1, STUDENT2));
|
new Assignment<HistoryCourse>(null, null), Arrays.asList(STUDENT1, STUDENT2));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSerializeId() {
|
public void testSerializeId() {
|
||||||
String json = gson.toJson(course, TYPE_COURSE_HISTORY);
|
String json = gson.toJson(course, TYPE_COURSE_HISTORY);
|
||||||
assertTrue(json.contains(String.valueOf(COURSE_ID.getValue())));
|
assertTrue(json.contains(String.valueOf(COURSE_ID.getValue())));
|
||||||
|
@ -66,6 +71,7 @@ public class TreeTypeAdaptersTest extends TestCase {
|
||||||
assertTrue(json.contains(String.valueOf(STUDENT2_ID.getValue())));
|
assertTrue(json.contains(String.valueOf(STUDENT2_ID.getValue())));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDeserializeId() {
|
public void testDeserializeId() {
|
||||||
String json = "{courseId:1,students:[{id:1,name:'first'},{id:6,name:'second'}],"
|
String json = "{courseId:1,students:[{id:1,name:'first'},{id:6,name:'second'}],"
|
||||||
+ "numAssignments:4,assignment:{}}";
|
+ "numAssignments:4,assignment:{}}";
|
||||||
|
|
|
@ -16,6 +16,8 @@
|
||||||
|
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.GsonBuilder;
|
import com.google.gson.GsonBuilder;
|
||||||
import com.google.gson.JsonDeserializationContext;
|
import com.google.gson.JsonDeserializationContext;
|
||||||
|
@ -29,9 +31,10 @@ import com.google.gson.stream.JsonReader;
|
||||||
import com.google.gson.stream.JsonWriter;
|
import com.google.gson.stream.JsonWriter;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.lang.reflect.Type;
|
import java.lang.reflect.Type;
|
||||||
import junit.framework.TestCase;
|
import org.junit.Test;
|
||||||
|
|
||||||
public final class TypeAdapterPrecedenceTest extends TestCase {
|
public final class TypeAdapterPrecedenceTest {
|
||||||
|
@Test
|
||||||
public void testNonstreamingFollowedByNonstreaming() {
|
public void testNonstreamingFollowedByNonstreaming() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.setLenient()
|
.setLenient()
|
||||||
|
@ -44,6 +47,7 @@ public final class TypeAdapterPrecedenceTest extends TestCase {
|
||||||
assertEquals("foo via deserializer 2", gson.fromJson("foo", Foo.class).name);
|
assertEquals("foo via deserializer 2", gson.fromJson("foo", Foo.class).name);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testStreamingFollowedByStreaming() {
|
public void testStreamingFollowedByStreaming() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.setLenient()
|
.setLenient()
|
||||||
|
@ -54,6 +58,7 @@ public final class TypeAdapterPrecedenceTest extends TestCase {
|
||||||
assertEquals("foo via type adapter 2", gson.fromJson("foo", Foo.class).name);
|
assertEquals("foo via type adapter 2", gson.fromJson("foo", Foo.class).name);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSerializeNonstreamingTypeAdapterFollowedByStreamingTypeAdapter() {
|
public void testSerializeNonstreamingTypeAdapterFollowedByStreamingTypeAdapter() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.setLenient()
|
.setLenient()
|
||||||
|
@ -65,6 +70,7 @@ public final class TypeAdapterPrecedenceTest extends TestCase {
|
||||||
assertEquals("foo via type adapter", gson.fromJson("foo", Foo.class).name);
|
assertEquals("foo via type adapter", gson.fromJson("foo", Foo.class).name);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testStreamingFollowedByNonstreaming() {
|
public void testStreamingFollowedByNonstreaming() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.setLenient()
|
.setLenient()
|
||||||
|
@ -76,6 +82,7 @@ public final class TypeAdapterPrecedenceTest extends TestCase {
|
||||||
assertEquals("foo via deserializer", gson.fromJson("foo", Foo.class).name);
|
assertEquals("foo via deserializer", gson.fromJson("foo", Foo.class).name);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testStreamingHierarchicalFollowedByNonstreaming() {
|
public void testStreamingHierarchicalFollowedByNonstreaming() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.setLenient()
|
.setLenient()
|
||||||
|
@ -87,6 +94,7 @@ public final class TypeAdapterPrecedenceTest extends TestCase {
|
||||||
assertEquals("foo via deserializer", gson.fromJson("foo", Foo.class).name);
|
assertEquals("foo via deserializer", gson.fromJson("foo", Foo.class).name);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testStreamingFollowedByNonstreamingHierarchical() {
|
public void testStreamingFollowedByNonstreamingHierarchical() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.registerTypeAdapter(Foo.class, newTypeAdapter("type adapter"))
|
.registerTypeAdapter(Foo.class, newTypeAdapter("type adapter"))
|
||||||
|
@ -97,6 +105,7 @@ public final class TypeAdapterPrecedenceTest extends TestCase {
|
||||||
assertEquals("foo via type adapter", gson.fromJson("\"foo\"", Foo.class).name);
|
assertEquals("foo via type adapter", gson.fromJson("\"foo\"", Foo.class).name);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testStreamingHierarchicalFollowedByNonstreamingHierarchical() {
|
public void testStreamingHierarchicalFollowedByNonstreamingHierarchical() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.setLenient()
|
.setLenient()
|
||||||
|
@ -108,6 +117,7 @@ public final class TypeAdapterPrecedenceTest extends TestCase {
|
||||||
assertEquals("foo via type adapter", gson.fromJson("foo", Foo.class).name);
|
assertEquals("foo via type adapter", gson.fromJson("foo", Foo.class).name);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testNonstreamingHierarchicalFollowedByNonstreaming() {
|
public void testNonstreamingHierarchicalFollowedByNonstreaming() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.setLenient()
|
.setLenient()
|
||||||
|
|
|
@ -16,6 +16,8 @@
|
||||||
|
|
||||||
package com.google.gson.functional;
|
package com.google.gson.functional;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.GsonBuilder;
|
import com.google.gson.GsonBuilder;
|
||||||
import com.google.gson.JsonDeserializationContext;
|
import com.google.gson.JsonDeserializationContext;
|
||||||
|
@ -27,13 +29,14 @@ import com.google.gson.JsonPrimitive;
|
||||||
import com.google.gson.JsonSerializationContext;
|
import com.google.gson.JsonSerializationContext;
|
||||||
import com.google.gson.JsonSerializer;
|
import com.google.gson.JsonSerializer;
|
||||||
import java.lang.reflect.Type;
|
import java.lang.reflect.Type;
|
||||||
import junit.framework.TestCase;
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Test that the hierarchy adapter works when subtypes are used.
|
* Test that the hierarchy adapter works when subtypes are used.
|
||||||
*/
|
*/
|
||||||
public final class TypeHierarchyAdapterTest extends TestCase {
|
public final class TypeHierarchyAdapterTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testTypeHierarchy() {
|
public void testTypeHierarchy() {
|
||||||
Manager andy = new Manager();
|
Manager andy = new Manager();
|
||||||
andy.userid = "andy";
|
andy.userid = "andy";
|
||||||
|
@ -116,6 +119,7 @@ public final class TypeHierarchyAdapterTest extends TestCase {
|
||||||
((Manager) company.ceo.minions[2]).minions[1].userid);
|
((Manager) company.ceo.minions[2]).minions[1].userid);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testRegisterSuperTypeFirst() {
|
public void testRegisterSuperTypeFirst() {
|
||||||
Gson gson = new GsonBuilder()
|
Gson gson = new GsonBuilder()
|
||||||
.registerTypeHierarchyAdapter(Employee.class, new EmployeeAdapter())
|
.registerTypeHierarchyAdapter(Employee.class, new EmployeeAdapter())
|
||||||
|
@ -132,6 +136,7 @@ public final class TypeHierarchyAdapterTest extends TestCase {
|
||||||
}
|
}
|
||||||
|
|
||||||
/** This behaviour changed in Gson 2.1; it used to throw. */
|
/** This behaviour changed in Gson 2.1; it used to throw. */
|
||||||
|
@Test
|
||||||
public void testRegisterSubTypeFirstAllowed() {
|
public void testRegisterSubTypeFirstAllowed() {
|
||||||
new GsonBuilder()
|
new GsonBuilder()
|
||||||
.registerTypeHierarchyAdapter(Manager.class, new ManagerAdapter())
|
.registerTypeHierarchyAdapter(Manager.class, new ManagerAdapter())
|
||||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue