Merge gson 2.9.1 from master.

This cherrypick is needed because some, but not all projects
in tm-mainline-prod are downstream from AOSP master.

Original change: https://android-review.googlesource.com/c/platform/external/gson/+/2181028

Bug: 243950468
Test: mm, presubmit
Change-Id: I159511b2ae6e37c26dece3a402d55c1dcdd264b7
Merged-In: Iaf4b7ab38cbb6da756e1a534c42de49a90ba682d
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..b8a47ca
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1 @@
+gson/docs/javadocs/* linguist-documentation
diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md
new file mode 100644
index 0000000..483fd2e
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/bug_report.md
@@ -0,0 +1,49 @@
+---
+name: Bug report
+about: Report a Gson bug.
+title: ''
+labels: bug
+assignees: ''
+
+---
+
+# Gson version
+<!-- Gson version you are using, for example '2.8.8' -->
+
+
+# Java / Android version
+<!-- Version of the Java or Android platform on which the bug occurred -->
+
+
+# Used tools
+<!-- List relevant build tools and plugins with version number here which might affect Gson -->
+- [ ] Maven; version: 
+- [ ] Gradle; version: 
+- [ ] ProGuard (attach the configuration file please); version: 
+- [ ] ...
+
+# Description
+<!-- Describe the bug you experienced -->
+
+
+## Expected behavior
+<!-- What behavior did you expect? -->
+
+
+## Actual behavior
+<!-- What happened instead? -->
+
+
+# Reproduction steps
+<!-- Provide exact reproduction steps for reproducing the bug -->
+<!-- Provide a short code snippet or link to a demo project -->
+
+1. ...
+2. ...
+
+# Exception stack trace
+<!-- In case an exception occurred, paste the COMPLETE exception stack trace in the code block below or attach it as file -->
+
+```
+
+```
diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml
new file mode 100644
index 0000000..b798788
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/config.yml
@@ -0,0 +1,4 @@
+contact_links:
+  - name: Usage question
+    url: https://stackoverflow.com/questions/tagged/gson
+    about: Ask usage questions on StackOverflow.
diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md
new file mode 100644
index 0000000..176fa7a
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/feature_request.md
@@ -0,0 +1,20 @@
+---
+name: Feature request
+about: Request a feature. ⚠️ Gson is in maintenance mode; large feature requests might be rejected.
+title: ''
+labels: enhancement
+assignees: ''
+
+---
+
+# Problem solved by the feature
+<!-- Describe which problem the requested feature solves -->
+
+
+# Feature description
+<!-- Describe the feature -->
+
+
+# Alternatives / workarounds
+<!-- Describe alternatives or workarounds in case you are aware of any -->
+
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
new file mode 100644
index 0000000..daec318
--- /dev/null
+++ b/.github/dependabot.yml
@@ -0,0 +1,6 @@
+version: 2
+updates:
+  - package-ecosystem: "maven"
+    directory: "/"
+    schedule:
+      interval: "daily"
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
new file mode 100644
index 0000000..0008892
--- /dev/null
+++ b/.github/workflows/build.yml
@@ -0,0 +1,19 @@
+name: Build
+
+on: [push, pull_request]
+
+jobs:
+  build:
+    runs-on: ubuntu-latest
+
+    steps:
+      - uses: actions/checkout@v2
+      - name: Set up JDK 11
+        uses: actions/setup-java@v2
+        with:
+          distribution: 'temurin'
+          java-version: '11'
+          cache: 'maven'
+      - name: Build with Maven
+        # This also runs javadoc:javadoc to detect any issues with the Javadoc
+        run: mvn --batch-mode --update-snapshots verify javadoc:javadoc
diff --git a/.github/workflows/cifuzz.yml b/.github/workflows/cifuzz.yml
new file mode 100644
index 0000000..29b86b3
--- /dev/null
+++ b/.github/workflows/cifuzz.yml
@@ -0,0 +1,25 @@
+name: CIFuzz
+on: [pull_request]
+jobs:
+  Fuzzing:
+    runs-on: ubuntu-latest
+    steps:
+    - name: Build Fuzzers
+      id: build
+      uses: google/oss-fuzz/infra/cifuzz/actions/build_fuzzers@master
+      with:
+        oss-fuzz-project-name: 'gson'
+        dry-run: false
+        language: jvm
+    - name: Run Fuzzers
+      uses: google/oss-fuzz/infra/cifuzz/actions/run_fuzzers@master
+      with:
+        oss-fuzz-project-name: 'gson'
+        fuzz-seconds: 600
+        dry-run: false
+    - name: Upload Crash
+      uses: actions/upload-artifact@v1
+      if: failure() && steps.build.outcome == 'success'
+      with:
+        name: artifacts
+        path: ./out/artifacts
diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml
new file mode 100644
index 0000000..17ed734
--- /dev/null
+++ b/.github/workflows/codeql-analysis.yml
@@ -0,0 +1,54 @@
+# Based on default config generated by GitHub, see also https://github.com/github/codeql-action
+
+name: "CodeQL"
+
+on:
+  push:
+    branches: [ master ]
+  pull_request:
+    branches: [ master ]
+  schedule:
+    # Run every Monday at 16:10
+    - cron: '10 16 * * 1'
+
+jobs:
+  analyze:
+    name: Analyze
+    runs-on: ubuntu-latest
+    permissions:
+      security-events: write
+
+    strategy:
+      fail-fast: false
+      matrix:
+        language: [ 'java' ]
+
+    steps:
+    - name: Checkout repository
+      uses: actions/checkout@v2
+
+    # Initializes the CodeQL tools for scanning
+    - name: Initialize CodeQL
+      uses: github/codeql-action/init@v2
+      with:
+        languages: ${{ matrix.language }}
+        # Run all security queries and maintainability and reliability queries
+        queries: +security-and-quality
+
+    - name: Cache local Maven repository
+      uses: actions/cache@v3
+      with:
+        path: ~/.m2/repository
+        key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
+        restore-keys: |
+          ${{ runner.os }}-maven-
+
+    # Only compile main sources, but ignore test sources because findings for them might not
+    # be that relevant (though GitHub security view also allows filtering by source type)
+    # Can replace this with github/codeql-action/autobuild action to run complete build
+    - name: Compile sources
+      run: |
+        mvn compile --batch-mode
+
+    - name: Perform CodeQL Analysis
+      uses: github/codeql-action/analyze@v2
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..2fc591b
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,22 @@
+.classpath
+.project
+.settings
+eclipsebin
+target
+*/target
+pom.xml.*
+release.properties
+
+.idea
+*.iml
+*.ipr
+*.iws
+classes
+
+.gradle
+local.properties
+build
+
+.DS_Store
+
+examples/android-proguard-example/gen
diff --git a/Android.bp b/Android.bp
new file mode 100644
index 0000000..6e9b498
--- /dev/null
+++ b/Android.bp
@@ -0,0 +1,55 @@
+// Copyright (C) 2022 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package {
+    default_applicable_licenses: ["external_gson_license"],
+}
+
+license {
+    name: "external_gson_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "LICENSE",
+    ],
+}
+
+java_library {
+    name: "gson",
+    host_supported: true,
+    srcs: [
+        "gson/src/main/java/com/google/gson/**/*.java",
+        ":GsonBuildConfig.java",
+    ],
+    sdk_version: "current",
+}
+
+python_binary_host {
+    name: "gson_version_generator",
+    main: "version_generator.py",
+    srcs: ["version_generator.py"],
+}
+
+genrule {
+    name: "GsonBuildConfig.java",
+    srcs: [
+        "gson/src/main/java-templates/com/google/gson/internal/GsonBuildConfig.java",
+        "pom.xml",
+    ],
+    out: ["com/google/gson/internal/GsonBuildConfig.java"],
+    cmd: "$(location gson_version_generator) $(in) > $(out)",
+    tools: ["gson_version_generator"],
+}
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..374faf3
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,451 @@
+Change Log
+==========
+
+## Version 2.9.0
+
+**The minimum supported Java version changes from 6 to 7.**
+
+* Change target Java version to 7 (#2043)
+* Put `module-info.class` into Multi-Release JAR folder (#2013)
+* Improve error message when abstract class cannot be constructed (#1814)
+* Support EnumMap deserialization (#2071)
+* Add LazilyParsedNumber default adapter (#2060)
+* Fix JsonReader.hasNext() returning true at end of document (#2061)
+* Remove Gradle build support. Build script was outdated and not actively
+  maintained anymore (#2063)
+* Add `GsonBuilder.disableJdkUnsafe()` (#1904)
+* Add `UPPER_CASE_WITH_UNDERSCORES` in FieldNamingPolicy (#2024)
+* Fix failing to serialize Collection or Map with inaccessible constructor (#1902)
+* Improve TreeTypeAdapter thread-safety (#1976)
+* Fix `Gson.newJsonWriter` ignoring lenient and HTML-safe setting (#1989)
+* Delete unused LinkedHashTreeMap (#1992)
+* Make default adapters stricter; improve exception messages (#2000)
+* Fix `FieldNamingPolicy.upperCaseFirstLetter` uppercasing non-letter (#2004)
+
+## Version 2.8.9
+
+* Make OSGi bundle's dependency on `sun.misc` optional (#1993).
+* Deprecate `Gson.excluder()` exposing internal `Excluder` class (#1986).
+* Prevent Java deserialization of internal classes (#1991).
+* Improve number strategy implementation (#1987).
+* Fix LongSerializationPolicy null handling being inconsistent with Gson (#1990).
+* Support arbitrary Number implementation for Object and Number deserialization (#1290).
+* Bump proguard-maven-plugin from 2.4.0 to 2.5.1 (#1980).
+* Don't exclude static local classes (#1969).
+* Fix `RuntimeTypeAdapterFactory` depending on internal `Streams` class (#1959).
+* Improve Maven build (#1964).
+* Make dependency on `java.sql` optional (#1707).
+
+## Version 2.8.8
+
+* Fixed issue with recursive types (#1390).
+* Better behaviour with Java 9+ and `Unsafe` if there is a security manager (#1712).
+* `EnumTypeAdapter` now works better when ProGuard has obfuscated enum fields (#1495).
+
+## Version 2.8.7
+
+* Fixed `ISO8601UtilsTest` failing on systems with UTC+X.
+* Improved javadoc for `JsonStreamParser`.
+* Updated proguard.cfg (#1693).
+* Fixed `IllegalStateException` in `JsonTreeWriter` (#1592).
+* Added `JsonArray.isEmpty()` (#1640).
+* Added new test cases (#1638).
+* Fixed OSGi metadata generation to work on JavaSE < 9 (#1603).
+
+## Version 2.8.6
+_2019-10-04_  [GitHub Diff](https://github.com/google/gson/compare/gson-parent-2.8.5...gson-parent-2.8.6)
+ * Added static methods `JsonParser.parseString` and `JsonParser.parseReader` and deprecated instance method `JsonParser.parse`
+ * Java 9 module-info support
+
+## Version 2.8.5
+_2018-05-21_  [GitHub Diff](https://github.com/google/gson/compare/gson-parent-2.8.4...gson-parent-2.8.5)
+ * Print Gson version while throwing AssertionError and IllegalArgumentException
+ * Moved `utils.VersionUtils` class to `internal.JavaVersion`. This is a potential backward incompatible change from 2.8.4
+ * Fixed issue https://github.com/google/gson/issues/1310 by supporting Debian Java 9
+
+## Version 2.8.4
+_2018-05-01_  [GitHub Diff](https://github.com/google/gson/compare/gson-parent-2.8.3...gson-parent-2.8.4)
+ * Added a new FieldNamingPolicy, `LOWER_CASE_WITH_DOTS` that mapps JSON name `someFieldName` to `some.field.name`
+ * Fixed issue https://github.com/google/gson/issues/1305 by removing compile/runtime dependency on `sun.misc.Unsafe`
+
+## Version 2.8.3
+_2018-04-27_  [GitHub Diff](https://github.com/google/gson/compare/gson-parent-2.8.2...gson-parent-2.8.3)
+ * Added a new API, `GsonBuilder.newBuilder()` that clones the current builder
+ * Preserving DateFormatter behavior on JDK 9
+ * Numerous other bugfixes
+
+## Version 2.8.2
+_2017-09-19_  [GitHub Diff](https://github.com/google/gson/compare/gson-parent-2.8.1...gson-parent-2.8.2)
+ * Introduced a new API, `JsonElement.deepCopy()`
+ * Numerous other bugfixes
+
+## Version 2.8.1
+_2017-05-30_  [GitHub Diff](https://github.com/google/gson/compare/gson-parent-2.8.0...gson-parent-2.8.1)
+ * New: `JsonObject.keySet()`
+ * `@JsonAdapter` annotation can now use `JsonSerializer` and `JsonDeserializer` as well.
+
+## Version 2.8
+_2016-10-26_  [GitHub Diff](https://github.com/google/gson/compare/gson-parent-2.7...gson-parent-2.8.0)
+ * New: `TypeToken.getParameterized()` and `TypeToken.getArray()` make it easier to
+   register or look up a `TypeAdapter`.
+ * New: `@JsonAdapter(nullSafe=true)` to specify that a custom type adapter handles null.
+
+## Version 2.7
+_2016-06-14_  [GitHub Diff](https://github.com/google/gson/compare/gson-parent-2.6.2...gson-parent-2.7)
+ * Added support for JsonSerializer/JsonDeserializer in @JsonAdapter annotation
+ * Exposing Gson properties excluder(), fieldNamingStrategy(), serializeNulls(), htmlSafe()
+ * Added JsonObject.size() method
+ * Added JsonWriter.value(Boolean value) method
+ * Using ArrayDeque, ConcurrentHashMap, and other JDK 1.6 features
+ * Better error reporting
+ * Plenty of other bug fixes
+
+## Version 2.6.2
+_2016-02-26_  [GitHub Diff](https://github.com/google/gson/compare/gson-parent-2.6.1...gson-parent-2.6.2)
+ * Fixed an NPE bug with @JsonAdapter annotation
+ * Added back OSGI manifest
+ * Some documentation typo fixes
+
+## Version 2.6.1
+
+_2016-02-11_ [GitHub Diff](https://github.com/google/gson/compare/gson-parent-2.6...gson-parent-2.6.1)
+
+ * Fix: The 2.6 release targeted Java 1.7, but we intend to target Java 1.6. The
+   2.6.1 release is identical to 2.6, but it targets Java 1.6.
+
+
+## Version 2.6
+
+_2016-02-11_ [GitHub Diff](https://github.com/google/gson/compare/gson-parent-2.5...gson-parent-2.6)
+
+ * Permit timezones without minutes in the default date adapter.
+ * Update reader and writer for RFC 7159. This means that strings, numbers,
+   booleans and null may be top-level values in JSON documents, even if the
+   reader is strict.
+ * New `setLenient()` method on `GsonBuilder`. This setting impacts the new
+   factory method `Gson.newJsonReader()`.
+ * Adapters discovered with `@JsonAdapter` are now null safe by default.
+
+
+## Version 2.5
+
+_2015-11-24_ [GitHub Diff](https://github.com/google/gson/compare/gson-parent-2.4...gson-parent-2.5)
+
+ * Updated minimum JDK version to 1.6
+ * Improved Date Deserialization by accepting many date formats
+ * Added support for `java.util.Currency`, `AtomicLong`, `AtomicLongArray`, `AtomicInteger`, `AtomicIntegerArray`, `AtomicBoolean`. This change is backward-incompatible because the earlier version of Gson used the default serialization which wasn't intuitive. We hope that these classes are not used enough to actually cause problems in the field.
+ * Improved debugging information when some exceptions are thrown
+
+
+## Version 2.4
+
+_2015-10-04_
+
+ * **Drop `IOException` from `TypeAdapter.toJson()`.** This is a binary-compatible change, but may
+   cause compiler errors where `IOExceptions` are being caught but no longer thrown. The correct fix
+   for this problem is to remove the unnecessary `catch` clause.
+ * New: `Gson.newJsonWriter` method returns configured `JsonWriter` instances.
+ * New: `@SerializedName` now works with [AutoValue’s][autovalue] abstract property methods.
+ * New: `@SerializedName` permits alternate names when deserializing.
+ * New: `JsonWriter#jsonValue` writes raw JSON values.
+ * New: APIs to add primitives directly to `JsonArray` instances.
+ * New: ISO 8601 date type adapter. Find this in _extras_.
+ * Fix: `FieldNamingPolicy` now works properly when running on a device with a Turkish locale.
+  [autovalue]: https://github.com/google/auto/tree/master/value
+
+
+## Version 2.3.1
+
+_2014-11-20_
+
+ * Added support to serialize objects with self-referential fields. The self-referential field is set to null in JSON. Previous version of Gson threw a StackOverflowException on encountering any self-referential fields.
+   * The most visible impact of this is that Gson can now serialize Throwable (Exception and Error)
+ * Added support for @JsonAdapter annotation on enums which are user defined types
+ * Fixed bug in getPath() with array of objects and arrays of arrays
+ * Other smaller bug fixes
+
+
+## Version 2.3
+
+_2014-08-11_
+
+ * The new @JsonAdapter annotation to specify a Json TypeAdapter for a class field
+ * JsonPath support: JsonReader.getPath() method returns the JsonPath expression
+ * New public methods in JsonArray (similar to the java.util.List): `contains(JsonElement), remove(JsonElement), remove(int index), set(int index, JsonElement element)`
+ * Many other smaller bug fixes
+
+
+## Version 2.2.4
+
+_2013-05-13_
+
+ * Fix internal map (LinkedHashTreeMap) hashing bug.
+ * Bug fix (Issue 511)
+
+
+## Version 2.2.3
+
+_2013-04-12_
+
+ * Fixes for possible DoS attack due to poor String hashing
+
+
+## Version 2.2.2
+
+_2012-07-02_
+
+ * Gson now allows a user to override default type adapters for Primitives and Strings. This behavior was allowed in earlier versions of Gson but was prohibited started Gson 2.0. We decided to allow it again: This enables a user to parse 1/0 as boolean values for compatibility with iOS JSON libraries.
+ * (Incompatible behavior change in `JsonParser`): In the past, if `JsonParser` encountered a stream that terminated prematurely, it returned `JsonNull`. This behavior wasn't correct because the stream had invalid JSON, not a null. `JsonParser` is now changed to throw `JsonSyntaxException` in this case. Note that if JsonParser (or Gson) encounter an empty stream, they still return `JsonNull`.
+
+
+## Version 2.2.1
+
+_2012-05-05_
+
+ * Very minor fixes
+
+
+## Version 2.2
+
+_2012-05-05_
+
+ * Added getDelegateAdapter in Gson class
+ * Fixed a security bug related to denial of service attack with Java HashMap String collisions.
+
+
+## Version 2.1
+
+_2011-12-30_ (Targeted Dec 31, 2011)
+
+ * Support for user-defined streaming type adapters
+ * continued performance enhancements
+ * Dropped support for type hierarchy instance creators. We don't expect this to be a problem. We'll also detect fewer errors where multiple type adapters can serialize the same type. With APIs like getNextTypeAdapter, this might actually be an improvement!
+
+
+## Version 2.0
+
+_2011-11-13_
+
+#### Faster
+
+ * Previous versions first parsed complete document into a DOM-style model (JsonObject or JsonArray) and then bound data against that. Gson 2 does data binding directly from the stream parser.
+
+#### More Predictable
+
+ * Objects are serialized and deserialized in the same way, regardless of where they occur in the object graph.
+
+#### Changes to watch out for
+
+  * Gson 1.7 would serialize top-level nulls as "". 2.0 serializes them as "null".
+    ```
+    String json = gson.toJson(null, Foo.class);
+    1.7: json == ""
+    2.0: json == "null"
+    ```
+
+  * Gson 1.7 permitted duplicate map keys. 2.0 forbids them.
+    ```
+    String json = "{'a':1,'a':2}";
+    Map<String, Integer> map = gson.fromJson(json, mapType);
+    1.7: map == {a=2}
+    2.0: JsonSyntaxException thrown
+    ```
+
+  * Gson 1.7 won’t serialize subclass fields in collection elements. 2.0 adds this extra information.
+    ```
+    List<Point2d> points = new ArrayList<Point2d>();
+    points.add(new Point3d(1, 2, 3));
+    String json = gson.toJson(points,
+        new TypeToken<List<Point2d>>() {}.getType());
+    1.7: json == "[{'x':1,'y':2}]"
+    2.0: json == "[{'x':1,'y':2,'z':3}]"
+    ```
+
+  * Gson 1.7 binds single-element arrays as their contents. 2.0 doesn’t.
+    ```
+    Integer i = gson.fromJson("[42]", Integer.class);
+    1.7: i == 42
+    2.0: JsonSyntaxException thrown
+    ```
+
+#### Other changes to be aware of
+ * Gson 2.0 doesn’t support type adapters for primitive types.
+ * Gson 1.7 uses arbitrary precision for primitive type conversion (so -122.08e-2132 != 0). Gson 2.0 uses double precision (so -122.08e-2132 == 0).
+ * Gson 1.7 sets subclass fields when an InstanceCreator returns a subclass when the value is a field of another object. Gson 2.0 sets fields of the requested type only.
+ * Gson 1.7 versioning never skips the top-level object. Gson 2.0 versioning applies to all objects.
+ * Gson 1.7 truncates oversized large integers. Gson 2.0 fails on them.
+ * Gson 2.0 permits integers to have .0 fractions like "1.0".
+ * Gson 1.7 throws IllegalStateException on circular references. Gson 2.0 lets the runtime throw a StackOverflowError.
+
+
+## Version 1.7.2
+
+_2011-09-30_ (Unplanned release)
+ * Fixed a threading issue in FieldAttributes (Issue 354)
+
+
+## Version 1.7.1
+
+_2011-04-13_ (Unplanned release)
+
+ * Fixed Gson jars in Maven Central repository
+ * Removed assembly-descriptor.xml and maven pom.xml/pom.properties files from Gson binary jar. This also ensures that jarjar can be run correctly on Gson.
+
+
+## Version 1.7
+
+_2011-04-12_ (Targeted: Jan 2011)
+
+ * No need to define no-args constructors for classes serialized with Gson
+ * Ability to register a hierarchical type adapter
+ * Support for serialization and deserialization of maps with complex keys
+ * Serialization and deserialization specific exclusion strategies
+ * Allow concrete data structure fields without type adapters
+ * Fixes "type" management (i.e. Wildcards, etc.)
+ * Major performance enhancements by reducing the need for Java reflection
+See detailed announcement at this thread in the Gson Google Group.
+
+
+## Version 1.6
+
+_2010-11-24_ (Targeted: Oct, 2010)
+
+ * New stream parser APIs
+ * New parser that improves parsing performance significantly
+
+
+## Version 1.5
+
+_2010-08-19_ (Target Date: Aug 18, 2010)
+
+ * Added `UPPER_CAMEL_CASE_WITH_SPACES` naming policy
+ * Added SQL date and time support
+ * A number of performance improvements: Using caching of field annotations for speeding up reflection, replacing recursive calls in the parser with a for loop.
+
+
+## Version 1.4 BETA
+
+_2009_10_09_
+
+ * JsonStreamParser: A streaming parser API class to deserialize multiple JSON objects on a stream (such as a pipelined HTTP response)
+ * Raised the deserialization limit for byte and object arrays and collection to over 11MB from 80KB. See issue 96.
+ * While serializing, Gson now uses the actual type of a field. This allows serialization of base-class references holding sub-classes to the JSON for the sub-class. It also allows serialization of raw collections. See Issue 155, 156.
+ * Added a `Gson.toJsonTree()` method that serializes a Java object to a tree of JsonElements. See issue 110.
+ * Added a `Gson.fromJson(JsonElement)` method that deserializes from a Json parse tree.
+ * Updated `Expose` annotation to contain parameters serialize and deserialize to control whether a field gets serialized or deserialized. See issue 146.
+ * Added a new naming policy `LOWER_CASE_WITH_DASHES`
+ * Default date type adapter is now thread-safe. See Issue 162.
+ * `JsonElement.toString()` now outputs valid JSON after escaping characters properly. See issue 154.
+ * `JsonPrimitive.equals()` now returns true for two numbers if their values are equal. All integral types (long, int, short, byte, BigDecimal, Long, Integer, Short, Byte) are treated equivalent for comparison. Similarly, floating point types (double, float, BigDecimal, Double, Float) are treated equivalent as well. See issue 147.
+ * Fixed bugs in pretty printing. See issue 153.
+ * If a field causes circular reference error, Gson lists the field name instead of the object value. See issue 118.
+ * Gson now serializes a list with null elements correctly. See issue 117.
+ * Fixed issue 121, 123, 126.
+ * Support user defined exclusion strategies (Feature Request 138).
+
+
+## Version 1.3
+
+_2009-04-01_
+
+ * Fix security token to remove the `<data>` element.
+ * Changed JsonParser.parse method to be non-static
+ * Throw JsonParseExceptions instead of ClassCastExceptions and UnsupportedOperationExceptions
+
+
+## Version 1.3 beta3
+
+_2009-03-17_
+
+ * Supported custom mapping of field names by making `FieldNamingStrategy` public and allowing `FieldNamingStrategy` to be set in GsonBuilder. See issue 104.
+ * Added a new GsonBuilder setting `generateNonExecutableJson()` that prefixes the generated JSON with some text to make the output non-executable Javascript. Gson now recognizes this text from input while deserializing and filters it out. This feature is meant to prevent script sourcing attacks. See Issue 42.
+ * Supported deserialization of sets with elements that do not implement Comparable. See Issue 100
+ * Supported deserialization of floating point numbers without a sign after E. See Issue 94
+
+
+## Version 1.3 beta2
+
+_2009-02-05_
+
+ * Added a new Parser API. See issue 65
+ * Supported deserialization of java.util.Properties. See Issue 87
+ * Fixed the pretty printing of maps. See Issue 93
+ * Supported automatic conversion of strings into numeric and boolean types if possible. See Issue 89
+ * Supported deserialization of longs into strings. See Issue 82
+
+
+## Version 1.3 beta1
+
+_2009_01_ (Target Date Friday, Dec 15, 2008)
+
+ * Made JSON parser lenient by allowing unquoted member names while parsing. See Issue 41
+ * Better precision handling for floating points. See Issue 71, 72
+ * Support for deserialization of special double values: NaN, infinity and negative infinity. See Issue 81
+ * Backward compatibility issue found with serialization of `Collection<Object>` type.  See Issue 73 and 83.
+ * Able to serialize null keys and/or values within a Map.  See Issue 77
+ * Deserializing non-String value keys for Maps.  See Issue 85.
+
+ * Support for clashing field name.  See Issue 76.
+ * Removed the need to invoke instance creator if a deserializer is registered. See issues 37 and 69.
+ * Added default support for java.util.UUID. See Issue 79
+ * Changed `Gson.toJson()` methods to use `Appendable` instead of `Writer`. Issue 52. This requires that clients recompile their source code that uses Gson.
+
+
+## Version 1.2.3
+
+_2008-11-15_ (Target Date Friday, Oct 31, 2008)
+
+ * Added support to serialize raw maps. See issue 45
+ * Made Gson thread-safe by fixing Issue 63
+ * Fixed Issue 68 to allow default type adapters for primitive types to be replaced by custom type adapters.
+ * Relaxed the JSON parser to accept escaped slash (\/) as a valid character in the string. See Issue 66
+
+
+## Version 1.2.2
+
+_2008-10-14_ (Target Date: None, Unplanned)
+
+ * This version was released to fix Issue 58 which caused a regression bug in version 1.2.1. It includes the contents from the release 1.2.1
+
+
+## Version 1.2.1
+
+_2008-10-13_ (Target Date Friday, Oct 7, 2008)
+
+**Note:** This release was abandoned since it caused a regression (Issue 58) bug.
+
+ * Includes updated parser for JSON that supports much larger strings. For example, Gson 1.2 failed at parsing a 100k string, Gson 1.2.1 has successfully parsed strings of size 15-20MB. The parser also is faster and consumes less memory since it uses a token match instead of a recursion-based Grammar production match. See Issue 47.
+ * Gson now supports field names with single quotes ' in addition to double quotes ". See Issue 55.
+ * Includes bug fixes for issue 46, 49, 51, 53, 54, and 56.
+
+
+## Version 1.2
+
+_2008-08-29_ (Target Date Tuesday Aug 26, 2008)
+
+ * Includes support for feature requests 21, 24, 29
+ * Includes bug fixes for Issue 22, Issue 23, Issue 25, Issue 26, Issue 32 , Issue 34, Issue 35, Issue 36, Issue 37, Issue 38, Issue 39
+ * Performance enhancements (see r137)
+ * Documentation updates
+
+
+## Version 1.1.1
+
+_2008-07-18_ (Target Date Friday, Aug 1, 2008)
+
+ * Includes fixes for Issue 19, Partial fix for Issue 20
+
+
+## Version 1.1
+
+_2008-07-01_ (Target Date Thursday, July 3, 2008)
+
+ * Includes fixes for Issue 9, Issue 16, Issue 18
+
+
+## Version 1.0.1
+
+_2008-06-17_ (Target Date Friday,  Jun 13, 2008)
+
+ * Includes fixes for Issue 15, Issue 14, Issue 3, Issue 8
+ * Javadoc improvements
diff --git a/GsonDesignDocument.md b/GsonDesignDocument.md
new file mode 100644
index 0000000..2c3702e
--- /dev/null
+++ b/GsonDesignDocument.md
@@ -0,0 +1,57 @@
+# Gson Design Document
+
+This document presents issues that we faced while designing Gson. It is meant for advanced users or developers working on Gson. If you are interested in learning how to use Gson, see its user guide. 
+
+**Navigating the Json tree or the target Type Tree while deserializing**
+
+When you are deserializing a Json string into an object of desired type, you can either navigate the tree of the input, or the type tree of the desired type. Gson uses the latter approach of navigating the type of the target object. This keeps you in tight control of instantiating only the type of objects that you are expecting (essentially validating the input against the expected "schema"). By doing this, you also ignore any extra fields that the Json input has but were not expected. 
+
+As part of Gson, we wrote a general purpose ObjectNavigator that can take any object and navigate through its fields calling a visitor of your choice. 
+
+**Supporting richer serialization semantics than deserialization semantics**
+
+Gson supports serialization of arbitrary collections, but can only deserialize genericized collections. this means that Gson can, in some cases, fail to deserialize Json that it wrote. This is primarily a limitation of the Java type system since when you encounter a Json array of arbitrary types there is no way to detect the types of individual elements. We could have chosen to restrict the serialization to support only generic collections, but chose not to.This is because often the user of the library are concerned with either serialization or deserialization, but not both. In such cases, there is no need to artificially restrict the serialization capabilities. 
+
+**Supporting serialization and deserialization of classes that are not under your control and hence can not be modified**
+
+Some Json libraries use annotations on fields or methods to indicate which fields should be used for Json serialization. That approach essentially precludes the use of classes from JDK or third-party libraries. We solved this problem by defining the notion of Custom serializers and deserializers. This approach is not new, and was used by the JAX-RPC technology to solve essentially the same problem. 
+
+**Using Checked vs Unchecked exceptions to indicate a parsing error**
+
+We chose to use unchecked exceptions to indicate a parsing failure. This is primarily done because usually the client can not recover from bad input, and hence forcing them to catch a checked exception results in sloppy code in the catch() block. 
+
+**Creating class instances for deserialization**
+
+Gson needs to create a dummy class instance before it can deserialize Json data into its fields. We could have used Guice to get such an instance, but that would have resulted in a dependency on Guice. Moreover, it probably would have done the wrong thing since Guice is expected to return a valid instance, whereas we need to create a dummy one. Worse, Gson would overwrite the fields of that instance with the incoming data there by modifying the instance for all subsequent Guice injections. This is clearly not a desired behavior. Hence, we create class instances by invoking the parameterless constructor. We also handle the primitive types, enums, collections, sets, maps and trees as a special case. 
+
+To solve the problem of supporting unmodifiable types, we use custom instance creators. So, if you want to use a library types that does not define a default constructor (for example, Money class), then you can register an instance creator that returns a dummy instance when asked.
+
+**Using fields vs getters to indicate Json elements**
+
+Some Json libraries use the getters of a type to deduce the Json elements. We chose to use all fields (up the inheritance hierarchy) that are not transient, static, or synthetic. We did this because not all classes are written with suitably named getters. Moreover, getXXX or isXXX might be semantic rather than indicating properties. 
+
+However, there are good arguments to support properties as well. We intend to enhance Gson in a latter version to support properties as an alternate mapping for indicating Json fields. For now, Gson is fields-based. 
+
+**Why are most classes in Gson marked as final?**
+
+While Gson provides a fairly extensible architecture by providing pluggable serializers and deserializers, Gson classes were not specifically designed to be extensible. Providing non-final classes would have allowed a user to legitimately extend Gson classes, and then expect that behavior to work in all subsequent revisions. We chose to limit such use-cases by marking classes as final, and waiting until a good use-case emerges to allow extensibility. Marking a class final also has a minor benefit of providing additional optimization opportunities to Java compiler and virtual machine. 
+
+**Why are inner interfaces and classes used heavily in Gson?**
+
+Gson uses inner classes substantially. Many of the public interfaces are inner interfaces too (see JsonSerializer.Context or JsonDeserializer.Context as an example). These are primarily done as a matter of style. For example, we could have moved JsonSerializer.Context to be a top-level class JsonSerializerContext, but chose not to do so. However, if you can give us good reasons to rename it alternately, we are open to changing this philosophy. 
+
+**Why do you provide two ways of constructing Gson?**
+
+Gson can be constructed in two ways: by invoking new Gson() or by using a GsonBuilder. We chose to provide a simple no-args constructor to handle simple use-cases for Gson where you want to use default options, and quickly want to get going with writing code. For all other situations, where you need to configure Gson with options such as formatters, version controls etc, we use a builder pattern. The builder pattern allows a user to specify multiple optional settings for what essentially become constructor parameters for Gson. 
+
+**Comparing Gson with Alternate Approaches**
+
+Note that these comparisons were done while developing Gson so these date back to mid to late 2007.
+
+__Comparing Gson with org.json library__
+
+org.json is a much lower-level library that can be used to write a toJson() method in a class. If you can not use Gson directly (may be because of platform restrictions regarding reflection), you could use org.json to hand-code a toJson method in each object. 
+
+__Comparing Gson with org.json.simple library__
+
+org.json.simple library is very similar to org.json library and hence fairly low level. The key issue with this library is that it does not handle exceptions very well. In some cases it appeared to just eat the exception while in other cases it throws an "Error" rather than an exception.
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..d645695
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,202 @@
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
diff --git a/METADATA b/METADATA
new file mode 100644
index 0000000..71e9085
--- /dev/null
+++ b/METADATA
@@ -0,0 +1,20 @@
+name: "gson"
+description:
+    "A Java serialization/deserialization library to convert Java Objects into JSON and back"
+
+third_party {
+  url {
+    type: HOMEPAGE
+    value: "https://github.com/google/gson"
+  }
+  url {
+    type: GIT
+    value: "https://github.com/google/gson.git"
+  }
+  version: "2.9.1"
+  last_upgrade_date { year: 2022 month: 8 day: 9 }
+  license_type: NOTICE
+  security {
+    tag: "NVD-CPE2.3:cpe:/a:google:gson:2.9.1"
+  }
+}
\ No newline at end of file
diff --git a/MODULE_LICENSE_APACHE2 b/MODULE_LICENSE_APACHE2
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/MODULE_LICENSE_APACHE2
diff --git a/OWNERS b/OWNERS
new file mode 100644
index 0000000..e3acf80
--- /dev/null
+++ b/OWNERS
@@ -0,0 +1,3 @@
+krzysio@google.com
+joeo@google.com
+ccross@android.com
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..b3c5b55
--- /dev/null
+++ b/README.md
@@ -0,0 +1,93 @@
+# Gson
+
+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.
+
+There are a few open-source projects that can convert Java objects to JSON. However, most of them require that you place Java annotations in your classes; something that you can not do if you do not have access to the source-code. Most also do not fully support the use of Java Generics. Gson considers both of these as very important design goals.
+
+:information_source: Gson is currently in maintenance mode; existing bugs will be fixed, but large new features will likely not be added. If you want to add a new feature, please first search for existing GitHub issues, or create a new one to discuss the feature and get feedback.
+
+### Goals
+  * Provide simple `toJson()` and `fromJson()` methods to convert Java objects to JSON and vice-versa
+  * Allow pre-existing unmodifiable objects to be converted to and from JSON
+  * Extensive support of Java Generics
+  * Allow custom representations for objects
+  * Support arbitrarily complex objects (with deep inheritance hierarchies and extensive use of generic types)
+
+### Download
+
+Gradle:
+```gradle
+dependencies {
+  implementation 'com.google.code.gson:gson:2.9.0'
+}
+```
+
+Maven:
+```xml
+<dependency>
+  <groupId>com.google.code.gson</groupId>
+  <artifactId>gson</artifactId>
+  <version>2.9.0</version>
+</dependency>
+```
+
+[Gson jar downloads](https://maven-badges.herokuapp.com/maven-central/com.google.code.gson/gson) are available from Maven Central.
+
+![Build Status](https://github.com/google/gson/actions/workflows/build.yml/badge.svg)
+
+### Requirements
+#### Minimum Java version
+- Gson 2.9.0 and newer: Java 7
+- Gson 2.8.9 and older: Java 6
+
+Despite supporting older Java versions, Gson also provides a JPMS module descriptor (module name `com.google.gson`) for users of Java 9 or newer.
+
+#### JPMS dependencies (Java 9+)
+These are the optional Java Platform Module System (JPMS) JDK modules which Gson depends on.
+This only applies when running Java 9 or newer.
+
+- `java.sql` (optional since Gson 2.8.9)  
+When this module is present, Gson provides default adapters for some SQL date and time classes.
+
+- `jdk.unsupported`, respectively class `sun.misc.Unsafe` (optional)  
+When this module is present, Gson can use the `Unsafe` class to create instances of classes without no-args constructor.
+However, care should be taken when relying on this. `Unsafe` is not available in all environments and its usage has some pitfalls,
+see [`GsonBuilder.disableJdkUnsafe()`](https://javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/GsonBuilder.html#disableJdkUnsafe()).
+
+### Documentation
+  * [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.
+  * [Change log](https://github.com/google/gson/blob/master/CHANGELOG.md): Changes in the recent versions
+  * [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
+
+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.
+
+### Related Content Created by Third Parties
+  * [Gson Tutorial](https://www.studytrails.com/java/json/java-google-json-introduction/) by `StudyTrails`
+  * [Gson Tutorial Series](https://futurestud.io/tutorials/gson-getting-started-with-java-json-serialization-deserialization) by `Future Studio`
+  * [Gson API Report](https://abi-laboratory.pro/java/tracker/timeline/gson/)
+
+### License
+
+Gson is released under the [Apache 2.0 license](LICENSE).
+
+```
+Copyright 2008 Google Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+```
+
+### Disclaimer
+
+This is not an officially supported Google product.
diff --git a/ReleaseProcess.md b/ReleaseProcess.md
new file mode 100644
index 0000000..4b85f4d
--- /dev/null
+++ b/ReleaseProcess.md
@@ -0,0 +1,59 @@
+# Gson Release Process
+
+The following is a step-by-step procedure for releasing a new version of Google-Gson.
+
+1. Go through all open bugs and identify which will be fixed in this release. Mark all others with an appropriate release tag. Identify duplicates, and close the bugs that will never be fixed. Fix all bugs for the release, and mark them fixed.
+1. Ensure all changelists are code-reviewed and have +1
+1. `cd gson` to the parent directory; ensure there are no open files and all changes are committed.
+1. Run `mvn release:clean`
+1. Do a dry run: `mvn release:prepare -DdryRun=true`
+1. Start the release: `mvn release:prepare`
+   * Answer questions: usually the defaults are fine.
+   * This will do a full build, change version from `-SNAPSHOT` to the released version, commit and create the tags. It will then change the version to `-SNAPSHOT` for the next release.
+1. Complete the release: `mvn release:perform`
+1. [Log in to Nexus repository manager](https://oss.sonatype.org/index.html#welcome) at Sonatype and close the staging repository for Gson.
+1. Download and sanity check all downloads. Do not skip this step! Once you release the staging repository, there is no going back. It will get synced with Maven central and you will not be able to update or delete anything. Your only recourse will be to release a new version of Gson and hope that no one uses the old one.
+1. Release the staging repository for Gson. Gson will now get synced to Maven central with-in the next hour. For issues consult [Sonatype Guide](https://docs.sonatype.org/display/Repository/Sonatype+OSS+Maven+Repository+Usage+Guide#SonatypeOSSMavenRepositoryUsageGuide-8.ReleaseIt).
+
+1. Update the version in the [Using Gson with Maven2 page](https://github.com/google/gson/blob/master/UserGuide.md#TOC-Gson-With-Maven)
+1. Update [Gson Changelog](https://github.com/google/gson/blob/master/CHANGELOG.md). Also, look at all bugs that were fixed and add a few lines describing what changed in the release.
+1. Create a post on the [Gson Discussion Forum](https://groups.google.com/group/google-gson)
+1. Update the release version in [Wikipedia](https://en.wikipedia.org/wiki/GSON) and update the current "stable" release.
+
+## Configuring a machine for deployment to Sonatype Repository
+
+This section was borrowed heavily from [Doclava release process](https://code.google.com/archive/p/doclava/wikis/ProcessRelease.wiki).
+
+1. Install/Configure GPG following this [guide](https://blog.sonatype.com/2010/01/how-to-generate-pgp-signatures-with-maven/).
+1. [Create encrypted passwords](https://maven.apache.org/guides/mini/guide-encryption.html).
+1. Create `~/.m2/settings.xml` similar to as described in [Doclava release process](https://code.google.com/p/doclava/wiki/ProcessRelease).
+1. Now for deploying a snapshot repository, use `mvn deploy`.
+
+## Getting Maven Publishing Privileges
+
+Based on [Gson group thread](https://groups.google.com/d/topic/google-gson/DHWJHVFpIBg/discussion):
+
+1. [Sign up for a Sonatype account](https://docs.sonatype.org/display/Repository/Sonatype+OSS+Maven+Repository+Usage+Guide) following instructions under (2) on that page
+1. Ask one of the existing members of the repository to create a JIRA ticket (Step 3 of above document) to add you to the publisher list.
+
+## Running Benchmarks or Tests on Android
+
+* Download vogar
+* Put `adb` on your `$PATH` and run:
+
+  ```bash
+  vogar --benchmark --classpath gson.jar path/to/Benchmark.java
+  ```
+
+For example, here is how to run the [CollectionsDeserializationBenchmark](gson/src/main/java/com/google/gson/metrics/CollectionsDeserializationBenchmark.java):
+
+```bash
+export ANDROID_HOME=~/apps/android-sdk-mac_x86
+export PATH=$PATH:$ANDROID_HOME/platform-tools/:$ANDROID_HOME/android-sdk-mac_x86/tools/
+$VOGAR_HOME/bin/vogar \
+    --benchmark \
+    --sourcepath ../gson/src/main/java/ \
+    src/main/java/com/google/gson/metrics/CollectionsDeserializationBenchmark.java \
+    -- \
+    --vm "app_process -Xgc:noconcurrent,app_process"
+```
diff --git a/UserGuide.md b/UserGuide.md
new file mode 100644
index 0000000..3764b82
--- /dev/null
+++ b/UserGuide.md
@@ -0,0 +1,744 @@
+# Gson User Guide
+
+1. [Overview](#TOC-Overview)
+2. [Goals for Gson](#TOC-Goals-for-Gson)
+3. [Gson Performance and Scalability](#TOC-Gson-Performance-and-Scalability)
+4. [Gson Users](#TOC-Gson-Users)
+5. [Using Gson](#TOC-Using-Gson)
+   * [Using Gson with Gradle/Android](#TOC-Gson-With-Gradle)
+   * [Using Gson with Maven](#TOC-Gson-With-Maven)
+   * [Primitives Examples](#TOC-Primitives-Examples)
+   * [Object Examples](#TOC-Object-Examples)
+   * [Finer Points with Objects](#TOC-Finer-Points-with-Objects)
+   * [Nested Classes (including Inner Classes)](#TOC-Nested-Classes-including-Inner-Classes-)
+   * [Array Examples](#TOC-Array-Examples)
+   * [Collections Examples](#TOC-Collections-Examples)
+     * [Collections Limitations](#TOC-Collections-Limitations)
+   * [Maps Examples](#TOC-Maps-Examples)
+   * [Serializing and Deserializing Generic Types](#TOC-Serializing-and-Deserializing-Generic-Types)
+   * [Serializing and Deserializing Collection with Objects of Arbitrary Types](#TOC-Serializing-and-Deserializing-Collection-with-Objects-of-Arbitrary-Types)
+   * [Built-in Serializers and Deserializers](#TOC-Built-in-Serializers-and-Deserializers)
+   * [Custom Serialization and Deserialization](#TOC-Custom-Serialization-and-Deserialization)
+     * [Writing a Serializer](#TOC-Writing-a-Serializer)
+     * [Writing a Deserializer](#TOC-Writing-a-Deserializer)
+   * [Writing an Instance Creator](#TOC-Writing-an-Instance-Creator)
+     * [InstanceCreator for a Parameterized Type](#TOC-InstanceCreator-for-a-Parameterized-Type)
+   * [Compact Vs. Pretty Printing for JSON Output Format](#TOC-Compact-Vs.-Pretty-Printing-for-JSON-Output-Format)
+   * [Null Object Support](#TOC-Null-Object-Support)
+   * [Versioning Support](#TOC-Versioning-Support)
+   * [Excluding Fields From Serialization and Deserialization](#TOC-Excluding-Fields-From-Serialization-and-Deserialization)
+     * [Java Modifier Exclusion](#TOC-Java-Modifier-Exclusion)
+     * [Gson's `@Expose`](#TOC-Gson-s-Expose)
+     * [User Defined Exclusion Strategies](#TOC-User-Defined-Exclusion-Strategies)
+   * [JSON Field Naming Support](#TOC-JSON-Field-Naming-Support)
+   * [Sharing State Across Custom Serializers and Deserializers](#TOC-Sharing-State-Across-Custom-Serializers-and-Deserializers)
+   * [Streaming](#TOC-Streaming)
+6. [Issues in Designing Gson](#TOC-Issues-in-Designing-Gson)
+7. [Future Enhancements to Gson](#TOC-Future-Enhancements-to-Gson)
+
+## <a name="TOC-Overview"></a>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 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
+
+* 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 custom representations for objects
+* Support arbitrarily complex objects
+* Generate compact and readable JSON output
+
+## <a name="TOC-Gson-Performance-and-Scalability"></a>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).
+
+* Strings: Deserialized strings of over 25MB without any problems (see `disabled_testStringDeserializationPerformance` method in `PerformanceTest`)
+* Large collections:
+  * Serialized a collection of 1.4 million objects (see `disabled_testLargeCollectionSerialization` method in `PerformanceTest`)
+  * Deserialized a collection of 87,000 objects (see `disabled_testLargeCollectionDeserialization` in `PerformanceTest`)
+* Gson 1.4 raised the deserialization limit for byte arrays and collection to over 11MB from 80KB.
+
+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 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
+
+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.
+
+## <a name="TOC-Gson-With-Gradle"></a>Using Gson with Gradle/Android
+
+```gradle
+dependencies {
+    implementation 'com.google.code.gson:gson:2.9.0'
+}
+```
+
+## <a name="TOC-Gson-With-Maven"></a>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:
+
+```xml
+<dependencies>
+    <!--  Gson: Java to JSON conversion -->
+    <dependency>
+      <groupId>com.google.code.gson</groupId>
+      <artifactId>gson</artifactId>
+      <version>2.9.0</version>
+      <scope>compile</scope>
+    </dependency>
+</dependencies>
+```
+
+That is it, now your Maven project is Gson enabled.
+
+### <a name="TOC-Primitives-Examples"></a>Primitives Examples
+
+```java
+// Serialization
+Gson gson = new Gson();
+gson.toJson(1);            // ==> 1
+gson.toJson("abcd");       // ==> "abcd"
+gson.toJson(new Long(10)); // ==> 10
+int[] values = { 1 };
+gson.toJson(values);       // ==> [1]
+
+// Deserialization
+int one = gson.fromJson("1", int.class);
+Integer one = gson.fromJson("1", Integer.class);
+Long one = gson.fromJson("1", Long.class);
+Boolean false = gson.fromJson("false", Boolean.class);
+String str = gson.fromJson("\"abc\"", String.class);
+String[] anotherStr = gson.fromJson("[\"abc\"]", String[].class);
+```
+
+### <a name="TOC-Object-Examples"></a>Object Examples
+
+```java
+class BagOfPrimitives {
+  private int value1 = 1;
+  private String value2 = "abc";
+  private transient int value3 = 3;
+  BagOfPrimitives() {
+    // no-args constructor
+  }
+}
+
+// Serialization
+BagOfPrimitives obj = new BagOfPrimitives();
+Gson gson = new Gson();
+String json = gson.toJson(obj);
+
+// ==> json is {"value1":1,"value2":"abc"}
+```
+
+Note that you can not serialize objects with circular references since that will result in infinite recursion.
+
+```java
+// Deserialization
+BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
+// ==> obj2 is just like obj
+```
+
+#### <a name="TOC-Finer-Points-with-Objects"></a>**Finer Points with Objects**
+
+* 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.
+* If a field is marked transient, (by default) it is ignored and not included in the JSON serialization or deserialization.
+* This implementation handles nulls correctly.
+  * While serializing, a null field is omitted from the output.
+  * While deserializing, a missing entry in JSON results in setting the corresponding field in the object to its default value: null for object types, zero for numeric types, and false for booleans.
+* If a field is _synthetic_, it is ignored and not included in JSON serialization or deserialization.
+* Fields corresponding to the outer classes in inner classes, anonymous classes, and local classes are ignored and not included in serialization or deserialization.
+
+### <a name="TOC-Nested-Classes-including-Inner-Classes-"></a>Nested Classes (including Inner Classes)
+
+Gson can serialize static nested classes quite easily.
+
+Gson can also deserialize static nested classes. However, Gson can **not** automatically deserialize the **pure inner classes since their no-args constructor also need a reference to the containing Object** which is not available at the time of deserialization. You can address this problem by either making the inner class static or by providing a custom InstanceCreator for it. Here is an example:
+
+```java
+public class A {
+  public String a;
+
+  class B {
+
+    public String b;
+
+    public B() {
+      // No args constructor for B
+    }
+  }
+}
+```
+
+**NOTE**: The above class B can not (by default) be serialized with Gson.
+
+Gson can not deserialize `{"b":"abc"}` into an instance of B since the class B is an inner class. If it was defined as static class B then Gson would have been able to deserialize the string. Another solution is to write a custom instance creator for B.
+
+```java
+public class InstanceCreatorForB implements InstanceCreator<A.B> {
+  private final A a;
+  public InstanceCreatorForB(A a)  {
+    this.a = a;
+  }
+  public A.B createInstance(Type type) {
+    return a.new B();
+  }
+}
+```
+
+The above is possible, but not recommended.
+
+### <a name="TOC-Array-Examples"></a>Array Examples
+
+```java
+Gson gson = new Gson();
+int[] ints = {1, 2, 3, 4, 5};
+String[] strings = {"abc", "def", "ghi"};
+
+// Serialization
+gson.toJson(ints);     // ==> [1,2,3,4,5]
+gson.toJson(strings);  // ==> ["abc", "def", "ghi"]
+
+// Deserialization
+int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class);
+// ==> ints2 will be same as ints
+```
+
+We also support multi-dimensional arrays, with arbitrarily complex element types.
+
+### <a name="TOC-Collections-Examples"></a>Collections Examples
+
+```java
+Gson gson = new Gson();
+Collection<Integer> ints = Arrays.asList(1,2,3,4,5);
+
+// Serialization
+String json = gson.toJson(ints);  // ==> json is [1,2,3,4,5]
+
+// Deserialization
+Type collectionType = new TypeToken<Collection<Integer>>(){}.getType();
+Collection<Integer> ints2 = gson.fromJson(json, collectionType);
+// ==> ints2 is same as ints
+```
+
+Fairly hideous: note how we define the type of collection.
+Unfortunately, there is no way to get around this in Java.
+
+#### <a name="TOC-Collections-Limitations"></a>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.
+This makes sense, and is rarely a problem when following good Java coding practices.
+
+### <a name="TOC-Maps-Examples"></a>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:
+
+```java
+Gson gson = new Gson();
+Map<String, String> stringMap = new LinkedHashMap<>();
+stringMap.put("key", "value");
+stringMap.put(null, "null-entry");
+
+// Serialization
+String json = gson.toJson(stringMap); // ==> json is {"key":"value","null":"null-entry"}
+
+Map<Integer, Integer> intMap = new LinkedHashMap<>();
+intMap.put(2, 4);
+intMap.put(3, 6);
+
+// Serialization
+String json = gson.toJson(intMap); // ==> json is {"2":4,"3":6}
+```
+
+For deserialization Gson uses the `read` method of the `TypeAdapter` registered for the Map key type. Similar to the Collection example shown above, for deserialization a `TypeToken` has to be used to tell Gson what types the Map keys and values have:
+
+```java
+Gson gson = new Gson();
+Type mapType = new TypeToken<Map<String, String>>(){}.getType();
+String json = "{\"key\": \"value\"}";
+
+// Deserialization
+Map<String, String> stringMap = gson.fromJson(json, mapType);
+// ==> stringMap is {key=value}
+```
+
+Gson also supports using complex types as Map keys. This feature can be enabled with [`GsonBuilder.enableComplexMapKeySerialization()`](https://javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/GsonBuilder.html#enableComplexMapKeySerialization()). If enabled, Gson uses the `write` method of the `TypeAdapter` registered for the Map key type to serialize the keys, instead of using `toString()`. When any of the keys is serialized by the adapter as JSON array or JSON object, Gson will serialize the complete Map as JSON array, consisting of key-value pairs (encoded as JSON array). Otherwise, if none of the keys is serialized as a JSON array or JSON object, Gson will use a JSON object to encode the Map:
+
+```java
+class PersonName {
+  String firstName;
+  String lastName;
+
+  PersonName(String firstName, String lastName) {
+    this.firstName = firstName;
+    this.lastName = lastName;
+  }
+
+  // ... equals and hashCode
+}
+
+Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
+Map<PersonName, Integer> complexMap = new LinkedHashMap<>();
+complexMap.put(new PersonName("John", "Doe"), 30);
+complexMap.put(new PersonName("Jane", "Doe"), 35);
+
+// Serialization; complex map is serialized as a JSON array containing key-value pairs (as JSON arrays)
+String json = gson.toJson(complexMap);
+// ==> json is [[{"firstName":"John","lastName":"Doe"},30],[{"firstName":"Jane","lastName":"Doe"},35]]
+
+Map<String, String> stringMap = new LinkedHashMap<>();
+stringMap.put("key", "value");
+// Serialization; non-complex map is serialized as a regular JSON object
+String json = gson.toJson(stringMap); // json is {"key":"value"}
+```
+
+**Important:** Because Gson by default uses `toString()` to serialize Map keys, this can lead to malformed encoded keys or can cause mismatch between serialization and deserialization of the keys, for example when `toString()` is not properly implemented. A workaround for this can be to use `enableComplexMapKeySerialization()` to make sure the `TypeAdapter` registered for the Map key type is used for deserialization _and_ serialization. As shown in the example above, when none of the keys are serialized by the adapter as JSON array or JSON object, the Map is serialized as a regular JSON object, as desired.
+
+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
+
+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:
+
+```java
+class Foo<T> {
+  T value;
+}
+Gson gson = new Gson();
+Foo<Bar> foo = new Foo<Bar>();
+gson.toJson(foo); // May not serialize foo.value correctly
+
+gson.fromJson(json, foo.getClass()); // Fails to deserialize foo.value as Bar
+```
+
+The above code fails to interpret value as type Bar because Gson invokes `foo.getClass()` to get its class information, but this method returns a raw class, `Foo.class`. This means that Gson has no way of knowing that this is an object of type `Foo<Bar>`, and not just plain `Foo`.
+
+You can solve this problem by specifying the correct parameterized type for your generic type. You can do this by using the [`TypeToken`](https://javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/reflect/TypeToken.html) class.
+
+```java
+Type fooType = new TypeToken<Foo<Bar>>() {}.getType();
+gson.toJson(foo, fooType);
+
+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.
+
+### <a name="TOC-Serializing-and-Deserializing-Collection-with-Objects-of-Arbitrary-Types"></a>Serializing and Deserializing Collection with Objects of Arbitrary Types
+
+Sometimes you are dealing with JSON array that contains mixed types. For example:
+`['hello',5,{name:'GREETINGS',source:'guest'}]`
+
+The equivalent `Collection` containing this is:
+
+```java
+Collection collection = new ArrayList();
+collection.add("hello");
+collection.add(5);
+collection.add(new Event("GREETINGS", "guest"));
+```
+
+where the `Event` class is defined as:
+
+```java
+class Event {
+  private String name;
+  private String source;
+  private Event(String name, String source) {
+    this.name = name;
+    this.source = source;
+  }
+}
+```
+
+You can serialize the collection with Gson without doing anything specific: `toJson(collection)` would write out the desired output.
+
+However, deserialization with `fromJson(json, Collection.class)` will not work since Gson has no way of knowing how to map the input to the types. Gson requires that you provide a genericised version of collection type in `fromJson()`. So, you have three options:
+
+1. Use Gson's parser API (low-level streaming parser or the DOM parser JsonParser) to parse the array elements and then use `Gson.fromJson()` on each of the array elements.This is the preferred approach. [Here is an example](extras/src/main/java/com/google/gson/extras/examples/rawcollections/RawCollectionsExample.java) that demonstrates how to do this.
+
+2. Register a type adapter for `Collection.class` that looks at each of the array members and maps them to appropriate objects. The disadvantage of this approach is that it will screw up deserialization of other collection types in Gson.
+
+3. Register a type adapter for `MyCollectionMemberType` and use `fromJson()` with `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
+
+Gson has built-in serializers and deserializers for commonly used classes whose default representation may be inappropriate, for instance
+
+* `java.net.URL` to match it with strings like `"https://github.com/google/gson/"`
+* `java.net.URI` to match it with strings like `"/google/gson/"`
+
+For many more, see the internal class [`TypeAdapters`](gson/src/main/java/com/google/gson/internal/bind/TypeAdapters.java).
+
+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
+
+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:
+
+* JSON Serializers: Need to define custom serialization for an object
+* JSON Deserializers: Needed to define custom deserialization for a type
+
+* Instance Creators: Not needed if no-args constructor is available or a deserializer is registered
+
+```java
+GsonBuilder gson = new GsonBuilder();
+gson.registerTypeAdapter(MyType2.class, new MyTypeAdapter());
+gson.registerTypeAdapter(MyType.class, new MySerializer());
+gson.registerTypeAdapter(MyType.class, new MyDeserializer());
+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.
+
+#### <a name="TOC-Writing-a-Serializer"></a>Writing a Serializer
+
+Here is an example of how to write a custom serializer for JodaTime `DateTime` class.
+
+```java
+private class DateTimeSerializer implements JsonSerializer<DateTime> {
+  public JsonElement serialize(DateTime src, Type typeOfSrc, JsonSerializationContext context) {
+    return new JsonPrimitive(src.toString());
+  }
+}
+```
+
+Gson calls `serialize()` when it runs into a `DateTime` object during serialization.
+
+#### <a name="TOC-Writing-a-Deserializer"></a>Writing a Deserializer
+
+Here is an example of how to write a custom deserializer for JodaTime DateTime class.
+
+```java
+private class DateTimeDeserializer implements JsonDeserializer<DateTime> {
+  public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
+      throws JsonParseException {
+    return new DateTime(json.getAsJsonPrimitive().getAsString());
+  }
+}
+```
+
+Gson calls `deserialize` when it needs to deserialize a JSON string fragment into a DateTime object
+
+**Finer points with Serializers and Deserializers**
+
+Often you want to register a single handler for all generic types corresponding to a raw type
+
+* For example, suppose you have an `Id` class for id representation/translation (i.e. an internal vs. external representation).
+* `Id<T>` type that has same serialization for all generic types
+  * Essentially write out the id value
+* Deserialization is very similar but not exactly the same
+  * Need to call `new Id(Class<T>, String)` which returns an instance of `Id<T>`
+
+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.
+
+### <a name="TOC-Writing-an-Instance-Creator"></a>Writing an Instance Creator
+
+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.
+
+* Doesn't matter whether public or private
+
+Typically, Instance Creators are needed when you are dealing with a library class that does NOT define a no-argument constructor
+
+**Instance Creator Example**
+
+```java
+private class MoneyInstanceCreator implements InstanceCreator<Money> {
+  public Money createInstance(Type type) {
+    return new Money("1000000", CurrencyCode.USD);
+  }
+}
+```
+
+Type could be of a corresponding generic type
+
+* 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
+
+#### <a name="TOC-InstanceCreator-for-a-Parameterized-Type"></a>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:
+
+```java
+class MyList<T> extends ArrayList<T> {
+}
+
+class MyListInstanceCreator implements InstanceCreator<MyList<?>> {
+    @SuppressWarnings("unchecked")
+  public MyList<?> createInstance(Type type) {
+    // No need to use a parameterized list since the actual instance will have the raw type anyway.
+    return new MyList();
+  }
+}
+```
+
+However, sometimes you do need to create instance based on the actual parameterized type. In this case, you can use the type parameter being passed to the `createInstance` method. Here is an example:
+
+```java
+public class Id<T> {
+  private final Class<T> classOfId;
+  private final long value;
+  public Id(Class<T> classOfId, long value) {
+    this.classOfId = classOfId;
+    this.value = value;
+  }
+}
+
+class IdInstanceCreator implements InstanceCreator<Id<?>> {
+  public Id<?> createInstance(Type type) {
+    Type[] typeParameters = ((ParameterizedType)type).getActualTypeArguments();
+    Type idType = typeParameters[0]; // Id has only one parameterized type T
+    return new Id((Class)idType, 0L);
+  }
+}
+```
+
+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
+
+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.
+
+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.
+
+The following is an example shows how to configure a `Gson` instance to use the default `JsonPrintFormatter` instead of the `JsonCompactFormatter`:
+
+```java
+Gson gson = new GsonBuilder().setPrettyPrinting().create();
+String jsonOutput = gson.toJson(someObject);
+```
+
+### <a name="TOC-Null-Object-Support"></a>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.
+
+Here's how you would configure a `Gson` instance to output null:
+
+```java
+Gson gson = new GsonBuilder().serializeNulls().create();
+```
+
+NOTE: when serializing `null`s with Gson, it will add a `JsonNull` element to the `JsonElement` structure. Therefore, this object can be used in custom serialization/deserialization.
+
+Here's an example:
+
+```java
+public class Foo {
+  private final String s;
+  private final int i;
+
+  public Foo() {
+    this(null, 5);
+  }
+
+  public Foo(String s, int i) {
+    this.s = s;
+    this.i = i;
+  }
+}
+
+Gson gson = new GsonBuilder().serializeNulls().create();
+Foo foo = new Foo();
+String json = gson.toJson(foo);
+System.out.println(json);
+
+json = gson.toJson(null);
+System.out.println(json);
+```
+
+The output is:
+
+```
+{"s":null,"i":5}
+null
+```
+
+### <a name="TOC-Versioning-Support"></a>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.
+
+```java
+public class VersionedClass {
+  @Since(1.1) private final String newerField;
+  @Since(1.0) private final String newField;
+  private final String field;
+
+  public VersionedClass() {
+    this.newerField = "newer";
+    this.newField = "new";
+    this.field = "old";
+  }
+}
+
+VersionedClass versionedObject = new VersionedClass();
+Gson gson = new GsonBuilder().setVersion(1.0).create();
+String jsonOutput = gson.toJson(versionedObject);
+System.out.println(jsonOutput);
+System.out.println();
+
+gson = new Gson();
+jsonOutput = gson.toJson(versionedObject);
+System.out.println(jsonOutput);
+```
+
+The output is:
+
+```
+{"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
+
+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).
+
+#### <a name="TOC-Java-Modifier-Exclusion"></a>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:
+
+```java
+import java.lang.reflect.Modifier;
+Gson gson = new GsonBuilder()
+    .excludeFieldsWithModifiers(Modifier.STATIC)
+    .create();
+```
+
+NOTE: you can give any number of the `Modifier` constants to the `excludeFieldsWithModifiers` method. For example:
+
+```java
+Gson gson = new GsonBuilder()
+    .excludeFieldsWithModifiers(Modifier.STATIC, Modifier.TRANSIENT, Modifier.VOLATILE)
+    .create();
+```
+
+#### <a name="TOC-Gson-s-Expose"></a>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.
+
+#### <a name="TOC-User-Defined-Exclusion-Strategies"></a>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.
+
+The following example shows how to exclude fields marked with a specific `@Foo` annotation and excludes top-level types (or declared field type) of class `String`.
+
+```java
+@Retention(RetentionPolicy.RUNTIME)
+@Target({ElementType.FIELD})
+public @interface Foo {
+  // Field tag only annotation
+}
+
+public class SampleObjectForTest {
+  @Foo private final int annotatedField;
+  private final String stringField;
+  private final long longField;
+  private final Class<?> clazzField;
+
+  public SampleObjectForTest() {
+    annotatedField = 5;
+    stringField = "someDefaultValue";
+    longField = 1234;
+  }
+}
+
+public class MyExclusionStrategy implements ExclusionStrategy {
+  private final Class<?> typeToSkip;
+
+  private MyExclusionStrategy(Class<?> typeToSkip) {
+    this.typeToSkip = typeToSkip;
+  }
+
+  public boolean shouldSkipClass(Class<?> clazz) {
+    return (clazz == typeToSkip);
+  }
+
+  public boolean shouldSkipField(FieldAttributes f) {
+    return f.getAnnotation(Foo.class) != null;
+  }
+}
+
+public static void main(String[] args) {
+  Gson gson = new GsonBuilder()
+      .setExclusionStrategies(new MyExclusionStrategy(String.class))
+      .serializeNulls()
+      .create();
+  SampleObjectForTest src = new SampleObjectForTest();
+  String json = gson.toJson(src);
+  System.out.println(json);
+}
+```
+
+The output is:
+
+```json
+{"longField":1234}
+```
+
+### <a name="TOC-JSON-Field-Naming-Support"></a>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.
+
+It also has an annotation based strategy to allows clients to define custom names on a per field basis. Note, that the annotation based strategy has field name validation which will raise "Runtime" exceptions if an invalid field name is provided as the annotation value.
+
+The following is an example of how to use both Gson naming policy features:
+
+```java
+private class SomeObject {
+  @SerializedName("custom_naming") private final String someField;
+  private final String someOtherField;
+
+  public SomeObject(String a, String b) {
+    this.someField = a;
+    this.someOtherField = b;
+  }
+}
+
+SomeObject someObject = new SomeObject("first", "second");
+Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
+String jsonRepresentation = gson.toJson(someObject);
+System.out.println(jsonRepresentation);
+```
+
+The output is:
+
+```json
+{"custom_naming":"first","SomeOtherField":"second"}
+```
+
+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
+
+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:
+
+1. Store shared state in static fields
+2. Declare the serializer/deserializer as inner classes of a parent type, and use the instance fields of parent type to store shared state
+3. Use Java `ThreadLocal`
+
+1 and 2 are not thread-safe options, but 3 is.
+
+### <a name="TOC-Streaming"></a>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.
+
+## <a name="TOC-Issues-in-Designing-Gson"></a>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.
+
+## <a name="TOC-Future-Enhancements-to-Gson"></a>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.
diff --git a/examples/android-proguard-example/AndroidManifest.xml b/examples/android-proguard-example/AndroidManifest.xml
new file mode 100644
index 0000000..7e9b1d8
--- /dev/null
+++ b/examples/android-proguard-example/AndroidManifest.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+  package="com.google.gson.examples.android"
+  android:versionCode="1"
+  android:versionName="1.0">
+  <uses-sdk android:minSdkVersion="3"/>
+  <application android:icon="@drawable/icon" android:label="@string/app_name">
+    <activity android:name=".GsonProguardExampleActivity" 
+              android:label="@string/app_name" 
+              android:exported="true" 
+              android:icon="@drawable/icon"
+              android:configChanges="keyboardHidden|orientation" 
+              android:enabled="true">
+      <intent-filter>
+        <action android:name="android.intent.action.MAIN" />
+        <category android:name="android.intent.category.LAUNCHER" />
+      </intent-filter>
+    </activity>
+  </application>
+  <uses-permission android:name="android.permission.INTERNET" />
+</manifest> 
diff --git a/examples/android-proguard-example/README.md b/examples/android-proguard-example/README.md
new file mode 100644
index 0000000..093c8ee
--- /dev/null
+++ b/examples/android-proguard-example/README.md
@@ -0,0 +1,12 @@
+# android-proguard-example
+
+Example Android project showing how to properly configure [ProGuard](https://www.guardsquare.com/proguard).
+ProGuard is a tool for 'shrinking' and obfuscating compiled classes. It can rename methods and fields,
+or remove them if they appear to be unused. This can cause issues for Gson which uses Java reflection to
+access the fields of a class. It is necessary to configure ProGuard to make sure that Gson works correctly.
+
+Also have a look at the [ProGuard manual](https://www.guardsquare.com/manual/configuration/usage#keepoverview)
+for more details on how ProGuard can be configured.
+
+The R8 code shrinker uses the same rule format as ProGuard, but there are differences between these two
+tools. Have a look at R8's Compatibility FAQ, and especially at the [Gson section](https://r8.googlesource.com/r8/+/refs/heads/main/compatibility-faq.md#gson).
diff --git a/examples/android-proguard-example/default.properties b/examples/android-proguard-example/default.properties
new file mode 100644
index 0000000..7d4fed0
--- /dev/null
+++ b/examples/android-proguard-example/default.properties
@@ -0,0 +1,12 @@
+# This file is automatically generated by Android Tools.
+# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
+#
+# This file must be checked in Version Control Systems.
+#
+# To customize properties used by the Ant build system use,
+# "build.properties", and override values to adapt the script to your
+# project structure.
+
+# Project target.
+target=android-3
+proguard.config=proguard.cfg
\ No newline at end of file
diff --git a/examples/android-proguard-example/proguard.cfg b/examples/android-proguard-example/proguard.cfg
new file mode 100644
index 0000000..95f31ec
--- /dev/null
+++ b/examples/android-proguard-example/proguard.cfg
@@ -0,0 +1,32 @@
+##---------------Begin: proguard configuration for Gson  ----------
+# Gson uses generic type information stored in a class file when working with fields. Proguard
+# removes such information by default, so configure it to keep all of it.
+-keepattributes Signature
+
+# For using GSON @Expose annotation
+-keepattributes *Annotation*
+
+# Gson specific classes
+-dontwarn sun.misc.**
+#-keep class com.google.gson.stream.** { *; }
+
+# Application classes that will be serialized/deserialized over Gson
+-keep class com.google.gson.examples.android.model.** { <fields>; }
+
+# Prevent proguard from stripping interface information from TypeAdapter, TypeAdapterFactory,
+# JsonSerializer, JsonDeserializer instances (so they can be used in @JsonAdapter)
+-keep class * extends com.google.gson.TypeAdapter
+-keep class * implements com.google.gson.TypeAdapterFactory
+-keep class * implements com.google.gson.JsonSerializer
+-keep class * implements com.google.gson.JsonDeserializer
+
+# Prevent R8 from leaving Data object members always null
+-keepclassmembers,allowobfuscation class * {
+  @com.google.gson.annotations.SerializedName <fields>;
+}
+
+# Retain generic signatures of TypeToken and its subclasses with R8 version 3.0 and higher.
+-keep,allowobfuscation,allowshrinking class com.google.gson.reflect.TypeToken
+-keep,allowobfuscation,allowshrinking class * extends com.google.gson.reflect.TypeToken
+
+##---------------End: proguard configuration for Gson  ----------
diff --git a/examples/android-proguard-example/res/drawable/icon.png b/examples/android-proguard-example/res/drawable/icon.png
new file mode 100644
index 0000000..a07c69f
--- /dev/null
+++ b/examples/android-proguard-example/res/drawable/icon.png
Binary files differ
diff --git a/examples/android-proguard-example/res/layout/main.xml b/examples/android-proguard-example/res/layout/main.xml
new file mode 100644
index 0000000..0ac46e6
--- /dev/null
+++ b/examples/android-proguard-example/res/layout/main.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+
+<LinearLayout
+  xmlns:android="http://schemas.android.com/apk/res/android" 
+  android:orientation="vertical"
+  android:layout_width="fill_parent"
+  android:layout_height="fill_parent">
+  
+  <TextView android:id="@+id/tv"
+    android:layout_width="fill_parent"
+    android:layout_height="wrap_content" />
+</LinearLayout>
\ No newline at end of file
diff --git a/examples/android-proguard-example/res/values/strings.xml b/examples/android-proguard-example/res/values/strings.xml
new file mode 100644
index 0000000..ba3be81
--- /dev/null
+++ b/examples/android-proguard-example/res/values/strings.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+  <string name="app_name">Gson Proguard Example</string>
+</resources>
+
diff --git a/examples/android-proguard-example/src/com/google/gson/examples/android/GsonProguardExampleActivity.java b/examples/android-proguard-example/src/com/google/gson/examples/android/GsonProguardExampleActivity.java
new file mode 100644
index 0000000..3ac740e
--- /dev/null
+++ b/examples/android-proguard-example/src/com/google/gson/examples/android/GsonProguardExampleActivity.java
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.examples.android;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import android.app.Activity;
+import android.os.Bundle;
+import android.widget.TextView;
+
+import com.google.gson.Gson;
+import com.google.gson.examples.android.model.Cart;
+import com.google.gson.examples.android.model.LineItem;
+
+/**
+ * Activity class illustrating how to use proguard with Gson
+ *
+ * @author Inderjeet Singh
+ */
+public class GsonProguardExampleActivity extends Activity {
+  @Override
+  public void onCreate(Bundle icicle) {
+    super.onCreate(icicle);
+    setContentView(R.layout.main);
+    TextView tv = (TextView) findViewById(R.id.tv);
+    Gson gson = new Gson();
+    Cart cart = buildCart();
+    StringBuilder sb = new StringBuilder();
+    sb.append("Gson.toJson() example: \n");
+    sb.append("  Cart Object: ").append(cart).append("\n");
+    sb.append("  Cart JSON: ").append(gson.toJson(cart)).append("\n");
+    sb.append("\n\nGson.fromJson() example: \n");
+    String json = "{buyer:'Happy Camper',creditCard:'4111-1111-1111-1111',"
+      + "lineItems:[{name:'nails',priceInMicros:100000,quantity:100,currencyCode:'USD'}]}";
+    sb.append("Cart JSON: ").append(json).append("\n");
+    sb.append("Cart Object: ").append(gson.fromJson(json, Cart.class)).append("\n");
+    tv.setText(sb.toString());
+    tv.invalidate();
+  }
+
+  private Cart buildCart() {
+    List<LineItem> lineItems = new ArrayList<>();
+    lineItems.add(new LineItem("hammer", 1, 12000000, "USD"));
+    return new Cart(lineItems, "Happy Buyer", "4111-1111-1111-1111");
+  }
+}
diff --git a/examples/android-proguard-example/src/com/google/gson/examples/android/model/Cart.java b/examples/android-proguard-example/src/com/google/gson/examples/android/model/Cart.java
new file mode 100644
index 0000000..7582036
--- /dev/null
+++ b/examples/android-proguard-example/src/com/google/gson/examples/android/model/Cart.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.examples.android.model;
+
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.lang.reflect.WildcardType;
+import java.util.List;
+
+import com.google.gson.annotations.SerializedName;
+
+/**
+ * A model object representing a cart that can be posted to an order-processing server
+ * 
+ * @author Inderjeet Singh
+ */
+public class Cart {
+  public final List<LineItem> lineItems;
+
+  @SerializedName("buyer")
+  private final String buyerName;
+
+  private final String creditCard;
+
+  public Cart(List<LineItem> lineItems, String buyerName, String creditCard) {
+    this.lineItems = lineItems;
+    this.buyerName = buyerName;
+    this.creditCard = creditCard;
+  }
+
+  public List<LineItem> getLineItems() {
+    return lineItems;
+  }
+
+  public String getBuyerName() {
+    return buyerName;
+  }
+
+  public String getCreditCard() {
+    return creditCard;
+  }
+
+  @Override
+  public String toString() {
+    StringBuilder itemsText = new StringBuilder();
+    boolean first = true;
+    if (lineItems != null) {
+      try {
+        Class<?> fieldType = Cart.class.getField("lineItems").getType();
+        System.out.println("LineItems CLASS: " + getSimpleTypeName(fieldType));
+      } catch (SecurityException e) {
+      } catch (NoSuchFieldException e) {
+      }
+      for (LineItem item : lineItems) {
+        if (first) {
+          first = false;
+        } else {
+          itemsText.append("; ");
+        }
+        itemsText.append(item);
+      }
+    }
+    return "[BUYER: " + buyerName + "; CC: " + creditCard + "; "
+    + "LINE_ITEMS: " + itemsText.toString() + "]";
+  }
+
+  @SuppressWarnings("unchecked")
+  public static String getSimpleTypeName(Type type) {
+    if (type == null) {
+      return "null";
+    }
+    if (type instanceof Class) {
+      return ((Class)type).getSimpleName();
+    } else if (type instanceof ParameterizedType) {
+      ParameterizedType pType = (ParameterizedType) type;
+      StringBuilder sb = new StringBuilder(getSimpleTypeName(pType.getRawType()));
+      sb.append('<');
+      boolean first = true;
+      for (Type argumentType : pType.getActualTypeArguments()) {
+        if (first) {
+          first = false;
+        } else {
+          sb.append(',');
+        }
+        sb.append(getSimpleTypeName(argumentType));
+      }
+      sb.append('>');
+      return sb.toString();
+    } else if (type instanceof WildcardType) {
+      return "?";
+    }
+    return type.toString();
+  }
+
+}
diff --git a/examples/android-proguard-example/src/com/google/gson/examples/android/model/LineItem.java b/examples/android-proguard-example/src/com/google/gson/examples/android/model/LineItem.java
new file mode 100644
index 0000000..1273ec9
--- /dev/null
+++ b/examples/android-proguard-example/src/com/google/gson/examples/android/model/LineItem.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.examples.android.model;
+
+/**
+ * A line item in a cart. This is not a rest resource, just a dependent object
+ *
+ * @author Inderjeet Singh
+ */
+public class LineItem {
+  private final String name;
+  private final int quantity;
+  private final long priceInMicros;
+  private final String currencyCode;
+
+  public LineItem(String name, int quantity, long priceInMicros, String currencyCode) {
+    this.name = name;
+    this.quantity = quantity;
+    this.priceInMicros = priceInMicros;
+    this.currencyCode = currencyCode;
+  }
+
+  public String getName() {
+    return name;
+  }
+
+  public int getQuantity() {
+    return quantity;
+  }
+
+  public long getPriceInMicros() {
+    return priceInMicros;
+  }
+
+  public String getCurrencyCode() {
+    return currencyCode;
+  }
+
+  @Override
+  public String toString() {
+    return String.format("(item: %s, qty: %s, price: %.2f %s)",
+        name, quantity, priceInMicros / 1000000d, currencyCode);
+  }
+}
diff --git a/extras/README.md b/extras/README.md
new file mode 100644
index 0000000..4144772
--- /dev/null
+++ b/extras/README.md
@@ -0,0 +1,6 @@
+# extras
+
+This Maven module contains the source code for supplementary Gson features which
+are not included by default.
+
+The artifacts created by this module are currently not deployed to Maven Central.
diff --git a/extras/pom.xml b/extras/pom.xml
new file mode 100644
index 0000000..da752f1
--- /dev/null
+++ b/extras/pom.xml
@@ -0,0 +1,73 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+  <modelVersion>4.0.0</modelVersion>
+  <parent>
+    <groupId>com.google.code.gson</groupId>
+    <artifactId>gson-parent</artifactId>
+    <version>2.9.1</version>
+  </parent>
+
+  <artifactId>gson-extras</artifactId>
+  <inceptionYear>2008</inceptionYear>
+  <name>Gson Extras</name>
+  <description>Google Gson grab bag of utilities, type adapters, etc.</description>
+
+  <licenses>
+    <license>
+      <name>Apache-2.0</name>
+      <url>https://www.apache.org/licenses/LICENSE-2.0.txt</url>
+    </license>
+  </licenses>
+
+  <organization>
+    <name>Google, Inc.</name>
+    <url>https://www.google.com</url>
+  </organization>
+
+  <dependencies>
+    <dependency>
+      <groupId>com.google.code.gson</groupId>
+      <artifactId>gson</artifactId>
+      <version>${project.parent.version}</version>
+    </dependency>
+    <dependency>
+      <groupId>javax.annotation</groupId>
+      <artifactId>jsr250-api</artifactId>
+      <version>1.0</version>
+    </dependency>
+    <dependency>
+      <groupId>junit</groupId>
+      <artifactId>junit</artifactId>
+      <scope>test</scope>
+    </dependency>
+  </dependencies>
+
+  <build>
+    <pluginManagement>
+      <plugins>
+        <plugin>
+          <groupId>org.apache.maven.plugins</groupId>
+          <artifactId>maven-deploy-plugin</artifactId>
+          <version>3.0.0</version>
+          <configuration>
+            <!-- Currently not deployed -->
+            <skip>true</skip>
+          </configuration>
+        </plugin>
+      </plugins>
+    </pluginManagement>
+  </build>
+
+  <developers>
+    <developer>
+      <name>Inderjeet Singh</name>
+    </developer>
+    <developer>
+      <name>Joel Leitch</name>
+      <organization>Google Inc.</organization>
+    </developer>
+    <developer>
+      <name>Jesse Wilson</name>
+      <organization>Square Inc.</organization>
+    </developer>
+  </developers>
+</project>
diff --git a/extras/src/main/java/com/google/gson/extras/examples/rawcollections/RawCollectionsExample.java b/extras/src/main/java/com/google/gson/extras/examples/rawcollections/RawCollectionsExample.java
new file mode 100644
index 0000000..9ea350c
--- /dev/null
+++ b/extras/src/main/java/com/google/gson/extras/examples/rawcollections/RawCollectionsExample.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.extras.examples.rawcollections;
+
+import java.util.ArrayList;
+import java.util.Collection;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonParser;
+
+public class RawCollectionsExample {
+  static class Event {
+    private String name;
+    private String source;
+    private Event(String name, String source) {
+      this.name = name;
+      this.source = source;
+    }
+    @Override
+    public String toString() {
+      return String.format("(name=%s, source=%s)", name, source);
+    }
+  }
+
+  @SuppressWarnings({ "unchecked", "rawtypes" })
+  public static void main(String[] args) {
+    Gson gson = new Gson();
+    Collection collection = new ArrayList();
+    collection.add("hello");
+    collection.add(5);
+    collection.add(new Event("GREETINGS", "guest"));
+    String json = gson.toJson(collection);
+    System.out.println("Using Gson.toJson() on a raw collection: " + json);
+    JsonArray array = JsonParser.parseString(json).getAsJsonArray();
+    String message = gson.fromJson(array.get(0), String.class);
+    int number = gson.fromJson(array.get(1), int.class);
+    Event event = gson.fromJson(array.get(2), Event.class);
+    System.out.printf("Using Gson.fromJson() to get: %s, %d, %s", message, number, event);
+  }
+}
diff --git a/extras/src/main/java/com/google/gson/graph/GraphAdapterBuilder.java b/extras/src/main/java/com/google/gson/graph/GraphAdapterBuilder.java
new file mode 100644
index 0000000..e6a07f1
--- /dev/null
+++ b/extras/src/main/java/com/google/gson/graph/GraphAdapterBuilder.java
@@ -0,0 +1,313 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.graph;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.InstanceCreator;
+import com.google.gson.JsonElement;
+import com.google.gson.ReflectionAccessFilter;
+import com.google.gson.TypeAdapter;
+import com.google.gson.TypeAdapterFactory;
+import com.google.gson.internal.ConstructorConstructor;
+import com.google.gson.internal.ObjectConstructor;
+import com.google.gson.reflect.TypeToken;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonToken;
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
+import java.lang.reflect.Type;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.IdentityHashMap;
+import java.util.LinkedList;
+import java.util.Map;
+import java.util.Queue;
+
+/**
+ * Writes a graph of objects as a list of named nodes.
+ */
+// TODO: proper documentation
+@SuppressWarnings("rawtypes")
+public final class GraphAdapterBuilder {
+  private final Map<Type, InstanceCreator<?>> instanceCreators;
+  private final ConstructorConstructor constructorConstructor;
+
+  public GraphAdapterBuilder() {
+      this.instanceCreators = new HashMap<>();
+      this.constructorConstructor = new ConstructorConstructor(instanceCreators, true, Collections.<ReflectionAccessFilter>emptyList());
+  }
+  public GraphAdapterBuilder addType(Type type) {
+    final ObjectConstructor<?> objectConstructor = constructorConstructor.get(TypeToken.get(type));
+    InstanceCreator<Object> instanceCreator = new InstanceCreator<Object>() {
+      @Override
+      public Object createInstance(Type type) {
+        return objectConstructor.construct();
+      }
+    };
+    return addType(type, instanceCreator);
+  }
+
+  public GraphAdapterBuilder addType(Type type, InstanceCreator<?> instanceCreator) {
+    if (type == null || instanceCreator == null) {
+      throw new NullPointerException();
+    }
+    instanceCreators.put(type, instanceCreator);
+    return this;
+  }
+
+  public void registerOn(GsonBuilder gsonBuilder) {
+    Factory factory = new Factory(instanceCreators);
+    gsonBuilder.registerTypeAdapterFactory(factory);
+    for (Map.Entry<Type, InstanceCreator<?>> entry : instanceCreators.entrySet()) {
+      gsonBuilder.registerTypeAdapter(entry.getKey(), factory);
+    }
+  }
+
+  static class Factory implements TypeAdapterFactory, InstanceCreator {
+    private final Map<Type, InstanceCreator<?>> instanceCreators;
+    private final ThreadLocal<Graph> graphThreadLocal = new ThreadLocal<>();
+
+    Factory(Map<Type, InstanceCreator<?>> instanceCreators) {
+      this.instanceCreators = instanceCreators;
+    }
+
+    @Override
+    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
+      if (!instanceCreators.containsKey(type.getType())) {
+        return null;
+      }
+
+      final TypeAdapter<T> typeAdapter = gson.getDelegateAdapter(this, type);
+      final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
+      return new TypeAdapter<T>() {
+        @Override public void write(JsonWriter out, T value) throws IOException {
+          if (value == null) {
+            out.nullValue();
+            return;
+          }
+
+          Graph graph = graphThreadLocal.get();
+          boolean writeEntireGraph = false;
+
+          /*
+           * We have one of two cases:
+           *  1. We've encountered the first known object in this graph. Write
+           *     out the graph, starting with that object.
+           *  2. We've encountered another graph object in the course of #1.
+           *     Just write out this object's name. We'll circle back to writing
+           *     out the object's value as a part of #1.
+           */
+
+          if (graph == null) {
+            writeEntireGraph = true;
+            graph = new Graph(new IdentityHashMap<Object, Element<?>>());
+          }
+
+          @SuppressWarnings("unchecked") // graph.map guarantees consistency between value and T
+          Element<T> element = (Element<T>) graph.map.get(value);
+          if (element == null) {
+            element = new Element<>(value, graph.nextName(), typeAdapter, null);
+            graph.map.put(value, element);
+            graph.queue.add(element);
+          }
+
+          if (writeEntireGraph) {
+            graphThreadLocal.set(graph);
+            try {
+              out.beginObject();
+              Element<?> current;
+              while ((current = graph.queue.poll()) != null) {
+                out.name(current.id);
+                current.write(out);
+              }
+              out.endObject();
+            } finally {
+              graphThreadLocal.remove();
+            }
+          } else {
+            out.value(element.id);
+          }
+        }
+
+        @Override public T read(JsonReader in) throws IOException {
+          if (in.peek() == JsonToken.NULL) {
+            in.nextNull();
+            return null;
+          }
+
+          /*
+           * Again we have one of two cases:
+           *  1. We've encountered the first known object in this graph. Read
+           *     the entire graph in as a map from names to their JsonElements.
+           *     Then convert the first JsonElement to its Java object.
+           *  2. We've encountered another graph object in the course of #1.
+           *     Read in its name, then deserialize its value from the
+           *     JsonElement in our map. We need to do this lazily because we
+           *     don't know which TypeAdapter to use until a value is
+           *     encountered in the wild.
+           */
+
+          String currentName = null;
+          Graph graph = graphThreadLocal.get();
+          boolean readEntireGraph = false;
+
+          if (graph == null) {
+            graph = new Graph(new HashMap<Object, Element<?>>());
+            readEntireGraph = true;
+
+            // read the entire tree into memory
+            in.beginObject();
+            while (in.hasNext()) {
+              String name = in.nextName();
+              if (currentName == null) {
+                currentName = name;
+              }
+              JsonElement element = elementAdapter.read(in);
+              graph.map.put(name, new Element<>(null, name, typeAdapter, element));
+            }
+            in.endObject();
+          } else {
+            currentName = in.nextString();
+          }
+
+          if (readEntireGraph) {
+            graphThreadLocal.set(graph);
+          }
+          try {
+            @SuppressWarnings("unchecked") // graph.map guarantees consistency between value and T
+            Element<T> element = (Element<T>) graph.map.get(currentName);
+            // now that we know the typeAdapter for this name, go from JsonElement to 'T'
+            if (element.value == null) {
+              element.typeAdapter = typeAdapter;
+              element.read(graph);
+            }
+            return element.value;
+          } finally {
+            if (readEntireGraph) {
+              graphThreadLocal.remove();
+            }
+          }
+        }
+      };
+    }
+
+    /**
+     * Hook for the graph adapter to get a reference to a deserialized value
+     * before that value is fully populated. This is useful to deserialize
+     * values that directly or indirectly reference themselves: we can hand
+     * out an instance before read() returns.
+     *
+     * <p>Gson should only ever call this method when we're expecting it to;
+     * that is only when we've called back into Gson to deserialize a tree.
+     */
+    @SuppressWarnings("unchecked")
+    @Override
+    public Object createInstance(Type type) {
+      Graph graph = graphThreadLocal.get();
+      if (graph == null || graph.nextCreate == null) {
+        throw new IllegalStateException("Unexpected call to createInstance() for " + type);
+      }
+      InstanceCreator<?> creator = instanceCreators.get(type);
+      Object result = creator.createInstance(type);
+      graph.nextCreate.value = result;
+      graph.nextCreate = null;
+      return result;
+    }
+  }
+
+  static class Graph {
+    /**
+     * The graph elements. On serialization keys are objects (using an identity
+     * hash map) and on deserialization keys are the string names (using a
+     * standard hash map).
+     */
+    private final Map<Object, Element<?>> map;
+
+    /**
+     * The queue of elements to write during serialization. Unused during
+     * deserialization.
+     */
+    private final Queue<Element> queue = new LinkedList<>();
+
+    /**
+     * The instance currently being deserialized. Used as a backdoor between
+     * the graph traversal (which needs to know instances) and instance creators
+     * which create them.
+     */
+    private Element nextCreate;
+
+    private Graph(Map<Object, Element<?>> map) {
+      this.map = map;
+    }
+
+    /**
+     * Returns a unique name for an element to be inserted into the graph.
+     */
+    public String nextName() {
+      return "0x" + Integer.toHexString(map.size() + 1);
+    }
+  }
+
+  /**
+   * An element of the graph during serialization or deserialization.
+   */
+  static class Element<T> {
+    /**
+     * This element's name in the top level graph object.
+     */
+    private final String id;
+
+    /**
+     * The value if known. During deserialization this is lazily populated.
+     */
+    private T value;
+
+    /**
+     * This element's type adapter if known. During deserialization this is
+     * lazily populated.
+     */
+    private TypeAdapter<T> typeAdapter;
+
+    /**
+     * The element to deserialize. Unused in serialization.
+     */
+    private final JsonElement element;
+
+    Element(T value, String id, TypeAdapter<T> typeAdapter, JsonElement element) {
+      this.value = value;
+      this.id = id;
+      this.typeAdapter = typeAdapter;
+      this.element = element;
+    }
+
+    void write(JsonWriter out) throws IOException {
+      typeAdapter.write(out, value);
+    }
+
+    void read(Graph graph) throws IOException {
+      if (graph.nextCreate != null) {
+        throw new IllegalStateException("Unexpected recursive call to read() for " + id);
+      }
+      graph.nextCreate = this;
+      value = typeAdapter.fromJsonTree(element);
+      if (value == null) {
+        throw new IllegalStateException("non-null value deserialized to null: " + element);
+      }
+    }
+  }
+}
diff --git a/extras/src/main/java/com/google/gson/interceptors/Intercept.java b/extras/src/main/java/com/google/gson/interceptors/Intercept.java
new file mode 100644
index 0000000..fef29cb
--- /dev/null
+++ b/extras/src/main/java/com/google/gson/interceptors/Intercept.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2012 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.interceptors;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+
+/**
+ * Use this annotation to indicate various interceptors for class instances after
+ * they have been processed by Gson. For example, you can use it to validate an instance
+ * after it has been deserialized from Json.
+ * Here is an example of how this annotation is used:
+ * <p>Here is an example of how this annotation is used:
+ * <pre>
+ * &#64;Intercept(postDeserialize=UserValidator.class)
+ * public class User {
+ *   String name;
+ *   String password;
+ *   String emailAddress;
+ * }
+ *
+ * public class UserValidator implements JsonPostDeserializer&lt;User&gt; {
+ *   public void postDeserialize(User user) {
+ *     // Do some checks on user
+ *     if (user.name == null || user.password == null) {
+ *       throw new JsonParseException("name and password are required fields.");
+ *     }
+ *     if (user.emailAddress == null) {
+ *       emailAddress = "unknown"; // assign a default value.
+ *     }
+ *   }
+ * }
+ * </pre>
+ *
+ * @author Inderjeet Singh
+ */
+@Retention(RetentionPolicy.RUNTIME)
+@Target(ElementType.TYPE)
+public @interface Intercept {
+
+  /**
+   * Specify the class that provides the methods that should be invoked after an instance
+   * has been deserialized.
+   */
+  @SuppressWarnings("rawtypes")
+  public Class<? extends JsonPostDeserializer> postDeserialize();
+}
diff --git a/extras/src/main/java/com/google/gson/interceptors/InterceptorFactory.java b/extras/src/main/java/com/google/gson/interceptors/InterceptorFactory.java
new file mode 100644
index 0000000..51916c2
--- /dev/null
+++ b/extras/src/main/java/com/google/gson/interceptors/InterceptorFactory.java
@@ -0,0 +1,49 @@
+package com.google.gson.interceptors;
+
+import com.google.gson.Gson;
+import com.google.gson.TypeAdapter;
+import com.google.gson.TypeAdapterFactory;
+import com.google.gson.reflect.TypeToken;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
+
+/**
+ * A type adapter factory that implements {@code @Intercept}.
+ */
+public final class InterceptorFactory implements TypeAdapterFactory {
+  @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
+    Intercept intercept = type.getRawType().getAnnotation(Intercept.class);
+    if (intercept == null) {
+      return null;
+    }
+
+    TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
+    return new InterceptorAdapter<>(delegate, intercept);
+  }
+
+  static class InterceptorAdapter<T> extends TypeAdapter<T> {
+    private final TypeAdapter<T> delegate;
+    private final JsonPostDeserializer<T> postDeserializer;
+
+    @SuppressWarnings("unchecked") // ?
+    public InterceptorAdapter(TypeAdapter<T> delegate, Intercept intercept) {
+      try {
+        this.delegate = delegate;
+        this.postDeserializer = intercept.postDeserialize().newInstance();
+      } catch (Exception e) {
+        throw new RuntimeException(e);
+      }
+    }
+
+    @Override public void write(JsonWriter out, T value) throws IOException {
+      delegate.write(out, value);
+    }
+
+    @Override public T read(JsonReader in) throws IOException {
+      T result = delegate.read(in);
+      postDeserializer.postDeserialize(result);
+      return result;
+    }
+  }
+}
diff --git a/extras/src/main/java/com/google/gson/interceptors/JsonPostDeserializer.java b/extras/src/main/java/com/google/gson/interceptors/JsonPostDeserializer.java
new file mode 100644
index 0000000..0f3a72c
--- /dev/null
+++ b/extras/src/main/java/com/google/gson/interceptors/JsonPostDeserializer.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2012 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.interceptors;
+
+import com.google.gson.InstanceCreator;
+
+/**
+ * This interface is implemented by a class that wishes to inspect or modify an object
+ * after it has been deserialized. You must define a no-args constructor or register an
+ * {@link InstanceCreator} for such a class.
+ *
+ * @author Inderjeet Singh
+ */
+public interface JsonPostDeserializer<T> {
+
+  /**
+   * This method is called by Gson after the object has been deserialized from Json.
+   */
+  public void postDeserialize(T object);
+}
diff --git a/extras/src/main/java/com/google/gson/typeadapters/PostConstructAdapterFactory.java b/extras/src/main/java/com/google/gson/typeadapters/PostConstructAdapterFactory.java
new file mode 100644
index 0000000..450ebba
--- /dev/null
+++ b/extras/src/main/java/com/google/gson/typeadapters/PostConstructAdapterFactory.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2016 Gson Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.typeadapters;
+
+import java.io.IOException;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+
+import javax.annotation.PostConstruct;
+
+import com.google.gson.Gson;
+import com.google.gson.TypeAdapter;
+import com.google.gson.TypeAdapterFactory;
+import com.google.gson.reflect.TypeToken;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonWriter;
+
+public class PostConstructAdapterFactory implements TypeAdapterFactory {
+    // copied from https://gist.github.com/swankjesse/20df26adaf639ed7fd160f145a0b661a
+    @Override
+    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
+        for (Class<?> t = type.getRawType(); (t != Object.class) && (t.getSuperclass() != null); t = t.getSuperclass()) {
+            for (Method m : t.getDeclaredMethods()) {
+                if (m.isAnnotationPresent(PostConstruct.class)) {
+                    m.setAccessible(true);
+                    TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
+                    return new PostConstructAdapter<>(delegate, m);
+                }
+            }
+        }
+        return null;
+    }
+
+    final static class PostConstructAdapter<T> extends TypeAdapter<T> {
+        private final TypeAdapter<T> delegate;
+        private final Method method;
+
+        public PostConstructAdapter(TypeAdapter<T> delegate, Method method) {
+            this.delegate = delegate;
+            this.method = method;
+        }
+
+        @Override public T read(JsonReader in) throws IOException {
+            T result = delegate.read(in);
+            if (result != null) {
+                try {
+                    method.invoke(result);
+                } catch (IllegalAccessException e) {
+                    throw new AssertionError();
+                } catch (InvocationTargetException e) {
+                    if (e.getCause() instanceof RuntimeException) throw (RuntimeException) e.getCause();
+                    throw new RuntimeException(e.getCause());
+                }
+            }
+            return result;
+        }
+
+        @Override public void write(JsonWriter out, T value) throws IOException {
+            delegate.write(out, value);
+        }
+    }
+}
diff --git a/extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java b/extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java
new file mode 100644
index 0000000..502ad4e
--- /dev/null
+++ b/extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java
@@ -0,0 +1,293 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.typeadapters;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParseException;
+import com.google.gson.JsonPrimitive;
+import com.google.gson.TypeAdapter;
+import com.google.gson.TypeAdapterFactory;
+import com.google.gson.reflect.TypeToken;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * Adapts values whose runtime type may differ from their declaration type. This
+ * is necessary when a field's type is not the same type that GSON should create
+ * when deserializing that field. For example, consider these types:
+ * <pre>   {@code
+ *   abstract class Shape {
+ *     int x;
+ *     int y;
+ *   }
+ *   class Circle extends Shape {
+ *     int radius;
+ *   }
+ *   class Rectangle extends Shape {
+ *     int width;
+ *     int height;
+ *   }
+ *   class Diamond extends Shape {
+ *     int width;
+ *     int height;
+ *   }
+ *   class Drawing {
+ *     Shape bottomShape;
+ *     Shape topShape;
+ *   }
+ * }</pre>
+ * <p>Without additional type information, the serialized JSON is ambiguous. Is
+ * the bottom shape in this drawing a rectangle or a diamond? <pre>   {@code
+ *   {
+ *     "bottomShape": {
+ *       "width": 10,
+ *       "height": 5,
+ *       "x": 0,
+ *       "y": 0
+ *     },
+ *     "topShape": {
+ *       "radius": 2,
+ *       "x": 4,
+ *       "y": 1
+ *     }
+ *   }}</pre>
+ * This class addresses this problem by adding type information to the
+ * serialized JSON and honoring that type information when the JSON is
+ * deserialized: <pre>   {@code
+ *   {
+ *     "bottomShape": {
+ *       "type": "Diamond",
+ *       "width": 10,
+ *       "height": 5,
+ *       "x": 0,
+ *       "y": 0
+ *     },
+ *     "topShape": {
+ *       "type": "Circle",
+ *       "radius": 2,
+ *       "x": 4,
+ *       "y": 1
+ *     }
+ *   }}</pre>
+ * Both the type field name ({@code "type"}) and the type labels ({@code
+ * "Rectangle"}) are configurable.
+ *
+ * <h3>Registering Types</h3>
+ * Create a {@code RuntimeTypeAdapterFactory} by passing the base type and type field
+ * name to the {@link #of} factory method. If you don't supply an explicit type
+ * field name, {@code "type"} will be used. <pre>   {@code
+ *   RuntimeTypeAdapterFactory<Shape> shapeAdapterFactory
+ *       = RuntimeTypeAdapterFactory.of(Shape.class, "type");
+ * }</pre>
+ * Next register all of your subtypes. Every subtype must be explicitly
+ * registered. This protects your application from injection attacks. If you
+ * don't supply an explicit type label, the type's simple name will be used.
+ * <pre>   {@code
+ *   shapeAdapterFactory.registerSubtype(Rectangle.class, "Rectangle");
+ *   shapeAdapterFactory.registerSubtype(Circle.class, "Circle");
+ *   shapeAdapterFactory.registerSubtype(Diamond.class, "Diamond");
+ * }</pre>
+ * Finally, register the type adapter factory in your application's GSON builder:
+ * <pre>   {@code
+ *   Gson gson = new GsonBuilder()
+ *       .registerTypeAdapterFactory(shapeAdapterFactory)
+ *       .create();
+ * }</pre>
+ * Like {@code GsonBuilder}, this API supports chaining: <pre>   {@code
+ *   RuntimeTypeAdapterFactory<Shape> shapeAdapterFactory = RuntimeTypeAdapterFactory.of(Shape.class)
+ *       .registerSubtype(Rectangle.class)
+ *       .registerSubtype(Circle.class)
+ *       .registerSubtype(Diamond.class);
+ * }</pre>
+ *
+ * <h3>Serialization and deserialization</h3>
+ * In order to serialize and deserialize a polymorphic object,
+ * you must specify the base type explicitly.
+ * <pre>   {@code
+ *   Diamond diamond = new Diamond();
+ *   String json = gson.toJson(diamond, Shape.class);
+ * }</pre>
+ * And then:
+ * <pre>   {@code
+ *   Shape shape = gson.fromJson(json, Shape.class);
+ * }</pre>
+ */
+public final class RuntimeTypeAdapterFactory<T> implements TypeAdapterFactory {
+  private final Class<?> baseType;
+  private final String typeFieldName;
+  private final Map<String, Class<?>> labelToSubtype = new LinkedHashMap<>();
+  private final Map<Class<?>, String> subtypeToLabel = new LinkedHashMap<>();
+  private final boolean maintainType;
+  private boolean recognizeSubtypes;
+
+  private RuntimeTypeAdapterFactory(
+      Class<?> baseType, String typeFieldName, boolean maintainType) {
+    if (typeFieldName == null || baseType == null) {
+      throw new NullPointerException();
+    }
+    this.baseType = baseType;
+    this.typeFieldName = typeFieldName;
+    this.maintainType = maintainType;
+  }
+
+  /**
+   * Creates a new runtime type adapter using for {@code baseType} using {@code
+   * typeFieldName} as the type field name. Type field names are case sensitive.
+   *
+   * @param maintainType true if the type field should be included in deserialized objects
+   */
+  public static <T> RuntimeTypeAdapterFactory<T> of(Class<T> baseType, String typeFieldName, boolean maintainType) {
+    return new RuntimeTypeAdapterFactory<>(baseType, typeFieldName, maintainType);
+  }
+  
+  /**
+   * Creates a new runtime type adapter using for {@code baseType} using {@code
+   * typeFieldName} as the type field name. Type field names are case sensitive.
+   */
+  public static <T> RuntimeTypeAdapterFactory<T> of(Class<T> baseType, String typeFieldName) {
+    return new RuntimeTypeAdapterFactory<>(baseType, typeFieldName, false);
+  }
+
+  /**
+   * Creates a new runtime type adapter for {@code baseType} using {@code "type"} as
+   * the type field name.
+   */
+  public static <T> RuntimeTypeAdapterFactory<T> of(Class<T> baseType) {
+    return new RuntimeTypeAdapterFactory<>(baseType, "type", false);
+  }
+
+  /**
+   * Ensures that this factory will handle not just the given {@code baseType}, but any subtype
+   * of that type.
+   */
+  public RuntimeTypeAdapterFactory<T> recognizeSubtypes() {
+    this.recognizeSubtypes = true;
+    return this;
+  }
+
+  /**
+   * Registers {@code type} identified by {@code label}. Labels are case
+   * sensitive.
+   *
+   * @throws IllegalArgumentException if either {@code type} or {@code label}
+   *     have already been registered on this type adapter.
+   */
+  public RuntimeTypeAdapterFactory<T> registerSubtype(Class<? extends T> type, String label) {
+    if (type == null || label == null) {
+      throw new NullPointerException();
+    }
+    if (subtypeToLabel.containsKey(type) || labelToSubtype.containsKey(label)) {
+      throw new IllegalArgumentException("types and labels must be unique");
+    }
+    labelToSubtype.put(label, type);
+    subtypeToLabel.put(type, label);
+    return this;
+  }
+
+  /**
+   * Registers {@code type} identified by its {@link Class#getSimpleName simple
+   * name}. Labels are case sensitive.
+   *
+   * @throws IllegalArgumentException if either {@code type} or its simple name
+   *     have already been registered on this type adapter.
+   */
+  public RuntimeTypeAdapterFactory<T> registerSubtype(Class<? extends T> type) {
+    return registerSubtype(type, type.getSimpleName());
+  }
+
+  @Override
+  public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
+    if (type == null) {
+      return null;
+    }
+    Class<?> rawType = type.getRawType();
+    boolean handle =
+        recognizeSubtypes ? baseType.isAssignableFrom(rawType) : baseType.equals(rawType);
+    if (!handle) {
+      return null;
+    }
+
+    final TypeAdapter<JsonElement> jsonElementAdapter = gson.getAdapter(JsonElement.class);
+    final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<>();
+    final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<>();
+    for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
+      TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue()));
+      labelToDelegate.put(entry.getKey(), delegate);
+      subtypeToDelegate.put(entry.getValue(), delegate);
+    }
+
+    return new TypeAdapter<R>() {
+      @Override public R read(JsonReader in) throws IOException {
+        JsonElement jsonElement = jsonElementAdapter.read(in);
+        JsonElement labelJsonElement;
+        if (maintainType) {
+            labelJsonElement = jsonElement.getAsJsonObject().get(typeFieldName);
+        } else {
+            labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName);
+        }
+        
+        if (labelJsonElement == null) {
+          throw new JsonParseException("cannot deserialize " + baseType
+              + " because it does not define a field named " + typeFieldName);
+        }
+        String label = labelJsonElement.getAsString();
+        @SuppressWarnings("unchecked") // registration requires that subtype extends T
+        TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label);
+        if (delegate == null) {
+          throw new JsonParseException("cannot deserialize " + baseType + " subtype named "
+              + label + "; did you forget to register a subtype?");
+        }
+        return delegate.fromJsonTree(jsonElement);
+      }
+
+      @Override public void write(JsonWriter out, R value) throws IOException {
+        Class<?> srcType = value.getClass();
+        String label = subtypeToLabel.get(srcType);
+        @SuppressWarnings("unchecked") // registration requires that subtype extends T
+        TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType);
+        if (delegate == null) {
+          throw new JsonParseException("cannot serialize " + srcType.getName()
+              + "; did you forget to register a subtype?");
+        }
+        JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject();
+
+        if (maintainType) {
+          jsonElementAdapter.write(out, jsonObject);
+          return;
+        }
+
+        JsonObject clone = new JsonObject();
+
+        if (jsonObject.has(typeFieldName)) {
+          throw new JsonParseException("cannot serialize " + srcType.getName()
+              + " because it already defines a field named " + typeFieldName);
+        }
+        clone.add(typeFieldName, new JsonPrimitive(label));
+        
+        for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
+          clone.add(e.getKey(), e.getValue());
+        }
+        jsonElementAdapter.write(out, clone);
+      }
+    }.nullSafe();
+  }
+}
diff --git a/extras/src/main/java/com/google/gson/typeadapters/UtcDateTypeAdapter.java b/extras/src/main/java/com/google/gson/typeadapters/UtcDateTypeAdapter.java
new file mode 100644
index 0000000..1e889d3
--- /dev/null
+++ b/extras/src/main/java/com/google/gson/typeadapters/UtcDateTypeAdapter.java
@@ -0,0 +1,282 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.typeadapters;
+
+import java.io.IOException;
+import java.text.ParseException;
+import java.text.ParsePosition;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.Locale;
+import java.util.TimeZone;
+
+import com.google.gson.JsonParseException;
+import com.google.gson.TypeAdapter;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonWriter;
+
+public final class UtcDateTypeAdapter extends TypeAdapter<Date> {
+  private final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("UTC");
+
+  @Override
+  public void write(JsonWriter out, Date date) throws IOException {
+    if (date == null) {
+      out.nullValue();
+    } else {
+      String value = format(date, true, UTC_TIME_ZONE);
+      out.value(value);
+    }
+  }
+
+  @Override
+  public Date read(JsonReader in) throws IOException {
+    try {
+      switch (in.peek()) {
+      case NULL:
+        in.nextNull();
+        return null;
+      default:
+        String date = in.nextString();
+        // Instead of using iso8601Format.parse(value), we use Jackson's date parsing
+        // This is because Android doesn't support XXX because it is JDK 1.6
+        return parse(date, new ParsePosition(0));
+      }
+    } catch (ParseException e) {
+      throw new JsonParseException(e);
+    }
+  }
+
+  // Date parsing code from Jackson databind ISO8601Utils.java
+  // https://github.com/FasterXML/jackson-databind/blob/master/src/main/java/com/fasterxml/jackson/databind/util/ISO8601Utils.java
+  private static final String GMT_ID = "GMT";
+
+  /**
+   * Format date into yyyy-MM-ddThh:mm:ss[.sss][Z|[+-]hh:mm]
+   *
+   * @param date the date to format
+   * @param millis true to include millis precision otherwise false
+   * @param tz timezone to use for the formatting (GMT will produce 'Z')
+   * @return the date formatted as yyyy-MM-ddThh:mm:ss[.sss][Z|[+-]hh:mm]
+   */
+  private static String format(Date date, boolean millis, TimeZone tz) {
+      Calendar calendar = new GregorianCalendar(tz, Locale.US);
+      calendar.setTime(date);
+
+      // estimate capacity of buffer as close as we can (yeah, that's pedantic ;)
+      int capacity = "yyyy-MM-ddThh:mm:ss".length();
+      capacity += millis ? ".sss".length() : 0;
+      capacity += tz.getRawOffset() == 0 ? "Z".length() : "+hh:mm".length();
+      StringBuilder formatted = new StringBuilder(capacity);
+
+      padInt(formatted, calendar.get(Calendar.YEAR), "yyyy".length());
+      formatted.append('-');
+      padInt(formatted, calendar.get(Calendar.MONTH) + 1, "MM".length());
+      formatted.append('-');
+      padInt(formatted, calendar.get(Calendar.DAY_OF_MONTH), "dd".length());
+      formatted.append('T');
+      padInt(formatted, calendar.get(Calendar.HOUR_OF_DAY), "hh".length());
+      formatted.append(':');
+      padInt(formatted, calendar.get(Calendar.MINUTE), "mm".length());
+      formatted.append(':');
+      padInt(formatted, calendar.get(Calendar.SECOND), "ss".length());
+      if (millis) {
+          formatted.append('.');
+          padInt(formatted, calendar.get(Calendar.MILLISECOND), "sss".length());
+      }
+
+      int offset = tz.getOffset(calendar.getTimeInMillis());
+      if (offset != 0) {
+          int hours = Math.abs((offset / (60 * 1000)) / 60);
+          int minutes = Math.abs((offset / (60 * 1000)) % 60);
+          formatted.append(offset < 0 ? '-' : '+');
+          padInt(formatted, hours, "hh".length());
+          formatted.append(':');
+          padInt(formatted, minutes, "mm".length());
+      } else {
+          formatted.append('Z');
+      }
+
+      return formatted.toString();
+  }
+  /**
+   * Zero pad a number to a specified length
+   *
+   * @param buffer buffer to use for padding
+   * @param value the integer value to pad if necessary.
+   * @param length the length of the string we should zero pad
+   */
+  private static void padInt(StringBuilder buffer, int value, int length) {
+      String strValue = Integer.toString(value);
+      for (int i = length - strValue.length(); i > 0; i--) {
+          buffer.append('0');
+      }
+      buffer.append(strValue);
+  }
+
+  /**
+   * Parse a date from ISO-8601 formatted string. It expects a format
+   * [yyyy-MM-dd|yyyyMMdd][T(hh:mm[:ss[.sss]]|hhmm[ss[.sss]])]?[Z|[+-]hh:mm]]
+   *
+   * @param date ISO string to parse in the appropriate format.
+   * @param pos The position to start parsing from, updated to where parsing stopped.
+   * @return the parsed date
+   * @throws ParseException if the date is not in the appropriate format
+   */
+  private static Date parse(String date, ParsePosition pos) throws ParseException {
+    Exception fail = null;
+    try {
+      int offset = pos.getIndex();
+
+      // extract year
+      int year = parseInt(date, offset, offset += 4);
+      if (checkOffset(date, offset, '-')) {
+        offset += 1;
+      }
+
+      // extract month
+      int month = parseInt(date, offset, offset += 2);
+      if (checkOffset(date, offset, '-')) {
+        offset += 1;
+      }
+
+      // extract day
+      int day = parseInt(date, offset, offset += 2);
+      // default time value
+      int hour = 0;
+      int minutes = 0;
+      int seconds = 0;
+      int milliseconds = 0; // always use 0 otherwise returned date will include millis of current time
+      if (checkOffset(date, offset, 'T')) {
+
+        // extract hours, minutes, seconds and milliseconds
+        hour = parseInt(date, offset += 1, offset += 2);
+        if (checkOffset(date, offset, ':')) {
+          offset += 1;
+        }
+
+        minutes = parseInt(date, offset, offset += 2);
+        if (checkOffset(date, offset, ':')) {
+          offset += 1;
+        }
+        // second and milliseconds can be optional
+        if (date.length() > offset) {
+          char c = date.charAt(offset);
+          if (c != 'Z' && c != '+' && c != '-') {
+            seconds = parseInt(date, offset, offset += 2);
+            // milliseconds can be optional in the format
+            if (checkOffset(date, offset, '.')) {
+              milliseconds = parseInt(date, offset += 1, offset += 3);
+            }
+          }
+        }
+      }
+
+      // extract timezone
+      String timezoneId;
+      if (date.length() <= offset) {
+        throw new IllegalArgumentException("No time zone indicator");
+      }
+      char timezoneIndicator = date.charAt(offset);
+      if (timezoneIndicator == '+' || timezoneIndicator == '-') {
+        String timezoneOffset = date.substring(offset);
+        timezoneId = GMT_ID + timezoneOffset;
+        offset += timezoneOffset.length();
+      } else if (timezoneIndicator == 'Z') {
+        timezoneId = GMT_ID;
+        offset += 1;
+      } else {
+        throw new IndexOutOfBoundsException("Invalid time zone indicator " + timezoneIndicator);
+      }
+
+      TimeZone timezone = TimeZone.getTimeZone(timezoneId);
+      if (!timezone.getID().equals(timezoneId)) {
+        throw new IndexOutOfBoundsException();
+      }
+
+      Calendar calendar = new GregorianCalendar(timezone);
+      calendar.setLenient(false);
+      calendar.set(Calendar.YEAR, year);
+      calendar.set(Calendar.MONTH, month - 1);
+      calendar.set(Calendar.DAY_OF_MONTH, day);
+      calendar.set(Calendar.HOUR_OF_DAY, hour);
+      calendar.set(Calendar.MINUTE, minutes);
+      calendar.set(Calendar.SECOND, seconds);
+      calendar.set(Calendar.MILLISECOND, milliseconds);
+
+      pos.setIndex(offset);
+      return calendar.getTime();
+      // If we get a ParseException it'll already have the right message/offset.
+      // Other exception types can convert here.
+    } catch (IndexOutOfBoundsException e) {
+      fail = e;
+    } catch (NumberFormatException e) {
+      fail = e;
+    } catch (IllegalArgumentException e) {
+      fail = e;
+    }
+    String input = (date == null) ? null : ("'" + date + "'");
+    throw new ParseException("Failed to parse date [" + input + "]: " + fail.getMessage(), pos.getIndex());
+  }
+
+  /**
+   * Check if the expected character exist at the given offset in the value.
+   *
+   * @param value the string to check at the specified offset
+   * @param offset the offset to look for the expected character
+   * @param expected the expected character
+   * @return true if the expected character exist at the given offset
+   */
+  private static boolean checkOffset(String value, int offset, char expected) {
+    return (offset < value.length()) && (value.charAt(offset) == expected);
+  }
+
+  /**
+   * Parse an integer located between 2 given offsets in a string
+   *
+   * @param value the string to parse
+   * @param beginIndex the start index for the integer in the string
+   * @param endIndex the end index for the integer in the string
+   * @return the int
+   * @throws NumberFormatException if the value is not a number
+   */
+  private static int parseInt(String value, int beginIndex, int endIndex) throws NumberFormatException {
+    if (beginIndex < 0 || endIndex > value.length() || beginIndex > endIndex) {
+      throw new NumberFormatException(value);
+    }
+    // use same logic as in Integer.parseInt() but less generic we're not supporting negative values
+    int i = beginIndex;
+    int result = 0;
+    int digit;
+    if (i < endIndex) {
+      digit = Character.digit(value.charAt(i++), 10);
+      if (digit < 0) {
+        throw new NumberFormatException("Invalid number: " + value);
+      }
+      result = -digit;
+    }
+    while (i < endIndex) {
+      digit = Character.digit(value.charAt(i++), 10);
+      if (digit < 0) {
+        throw new NumberFormatException("Invalid number: " + value);
+      }
+      result *= 10;
+      result -= digit;
+    }
+    return -result;
+  }
+}
diff --git a/extras/src/test/java/com/google/gson/graph/GraphAdapterBuilderTest.java b/extras/src/test/java/com/google/gson/graph/GraphAdapterBuilderTest.java
new file mode 100644
index 0000000..3b2425e
--- /dev/null
+++ b/extras/src/test/java/com/google/gson/graph/GraphAdapterBuilderTest.java
@@ -0,0 +1,195 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.graph;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertSame;
+
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import org.junit.Test;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.reflect.TypeToken;
+
+public final class GraphAdapterBuilderTest {
+  @Test
+  public void testSerialization() {
+    Roshambo rock = new Roshambo("ROCK");
+    Roshambo scissors = new Roshambo("SCISSORS");
+    Roshambo paper = new Roshambo("PAPER");
+    rock.beats = scissors;
+    scissors.beats = paper;
+    paper.beats = rock;
+
+    GsonBuilder gsonBuilder = new GsonBuilder();
+    new GraphAdapterBuilder()
+        .addType(Roshambo.class)
+        .registerOn(gsonBuilder);
+    Gson gson = gsonBuilder.create();
+
+    assertEquals("{'0x1':{'name':'ROCK','beats':'0x2'}," +
+        "'0x2':{'name':'SCISSORS','beats':'0x3'}," +
+        "'0x3':{'name':'PAPER','beats':'0x1'}}",
+        gson.toJson(rock).replace('"', '\''));
+  }
+
+  @Test
+  public void testDeserialization() {
+    String json = "{'0x1':{'name':'ROCK','beats':'0x2'}," +
+        "'0x2':{'name':'SCISSORS','beats':'0x3'}," +
+        "'0x3':{'name':'PAPER','beats':'0x1'}}";
+
+    GsonBuilder gsonBuilder = new GsonBuilder();
+    new GraphAdapterBuilder()
+        .addType(Roshambo.class)
+        .registerOn(gsonBuilder);
+    Gson gson = gsonBuilder.create();
+
+    Roshambo rock = gson.fromJson(json, Roshambo.class);
+    assertEquals("ROCK", rock.name);
+    Roshambo scissors = rock.beats;
+    assertEquals("SCISSORS", scissors.name);
+    Roshambo paper = scissors.beats;
+    assertEquals("PAPER", paper.name);
+    assertSame(rock, paper.beats);
+  }
+
+  @Test
+  public void testDeserializationDirectSelfReference() {
+    String json = "{'0x1':{'name':'SUICIDE','beats':'0x1'}}";
+
+    GsonBuilder gsonBuilder = new GsonBuilder();
+    new GraphAdapterBuilder()
+        .addType(Roshambo.class)
+        .registerOn(gsonBuilder);
+    Gson gson = gsonBuilder.create();
+
+    Roshambo suicide = gson.fromJson(json, Roshambo.class);
+    assertEquals("SUICIDE", suicide.name);
+    assertSame(suicide, suicide.beats);
+  }
+
+  @Test
+  public void testSerializeListOfLists() {
+    Type listOfListsType = new TypeToken<List<List<?>>>() {}.getType();
+    Type listOfAnyType = new TypeToken<List<?>>() {}.getType();
+
+    List<List<?>> listOfLists = new ArrayList<>();
+    listOfLists.add(listOfLists);
+    listOfLists.add(new ArrayList<>());
+
+    GsonBuilder gsonBuilder = new GsonBuilder();
+    new GraphAdapterBuilder()
+        .addType(listOfListsType)
+        .addType(listOfAnyType)
+        .registerOn(gsonBuilder);
+    Gson gson = gsonBuilder.create();
+
+    String json = gson.toJson(listOfLists, listOfListsType);
+    assertEquals("{'0x1':['0x1','0x2'],'0x2':[]}", json.replace('"', '\''));
+  }
+
+  @Test
+  public void testDeserializeListOfLists() {
+    Type listOfAnyType = new TypeToken<List<?>>() {}.getType();
+    Type listOfListsType = new TypeToken<List<List<?>>>() {}.getType();
+
+    GsonBuilder gsonBuilder = new GsonBuilder();
+    new GraphAdapterBuilder()
+        .addType(listOfListsType)
+        .addType(listOfAnyType)
+        .registerOn(gsonBuilder);
+    Gson gson = gsonBuilder.create();
+
+    List<List<?>> listOfLists = gson.fromJson("{'0x1':['0x1','0x2'],'0x2':[]}", listOfListsType);
+    assertEquals(2, listOfLists.size());
+    assertSame(listOfLists, listOfLists.get(0));
+    assertEquals(Collections.emptyList(), listOfLists.get(1));
+  }
+
+  @Test
+  public void testSerializationWithMultipleTypes() {
+    Company google = new Company("Google");
+    new Employee("Jesse", google);
+    new Employee("Joel", google);
+
+    GsonBuilder gsonBuilder = new GsonBuilder();
+    new GraphAdapterBuilder()
+        .addType(Company.class)
+        .addType(Employee.class)
+        .registerOn(gsonBuilder);
+    Gson gson = gsonBuilder.create();
+
+    assertEquals("{'0x1':{'name':'Google','employees':['0x2','0x3']},"
+        + "'0x2':{'name':'Jesse','company':'0x1'},"
+        + "'0x3':{'name':'Joel','company':'0x1'}}",
+        gson.toJson(google).replace('"', '\''));
+  }
+
+  @Test
+  public void testDeserializationWithMultipleTypes() {
+    GsonBuilder gsonBuilder = new GsonBuilder();
+    new GraphAdapterBuilder()
+        .addType(Company.class)
+        .addType(Employee.class)
+        .registerOn(gsonBuilder);
+    Gson gson = gsonBuilder.create();
+
+    String json = "{'0x1':{'name':'Google','employees':['0x2','0x3']},"
+        + "'0x2':{'name':'Jesse','company':'0x1'},"
+        + "'0x3':{'name':'Joel','company':'0x1'}}";
+    Company company = gson.fromJson(json, Company.class);
+    assertEquals("Google", company.name);
+    Employee jesse = company.employees.get(0);
+    assertEquals("Jesse", jesse.name);
+    assertEquals(company, jesse.company);
+    Employee joel = company.employees.get(1);
+    assertEquals("Joel", joel.name);
+    assertEquals(company, joel.company);
+  }
+
+  static class Roshambo {
+    String name;
+    Roshambo beats;
+    Roshambo(String name) {
+      this.name = name;
+    }
+  }
+
+  static class Employee {
+    final String name;
+    final Company company;
+    Employee(String name, Company company) {
+      this.name = name;
+      this.company = company;
+      this.company.employees.add(this);
+    }
+  }
+
+  static class Company {
+    final String name;
+    final List<Employee> employees = new ArrayList<>();
+    Company(String name) {
+      this.name = name;
+    }
+  }
+}
diff --git a/extras/src/test/java/com/google/gson/interceptors/InterceptorTest.java b/extras/src/test/java/com/google/gson/interceptors/InterceptorTest.java
new file mode 100644
index 0000000..39d618a
--- /dev/null
+++ b/extras/src/test/java/com/google/gson/interceptors/InterceptorTest.java
@@ -0,0 +1,171 @@
+/*
+ * Copyright (C) 2012 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.interceptors;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonParseException;
+import com.google.gson.JsonSyntaxException;
+import com.google.gson.TypeAdapter;
+import com.google.gson.reflect.TypeToken;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
+import java.lang.reflect.Type;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import junit.framework.TestCase;
+
+/**
+ * Unit tests for {@link Intercept} and {@link JsonPostDeserializer}.
+ *
+ * @author Inderjeet Singh
+ */
+public final class InterceptorTest extends TestCase {
+
+  private Gson gson;
+
+  @Override
+  public void setUp() throws Exception {
+    super.setUp();
+    this.gson = new GsonBuilder()
+        .registerTypeAdapterFactory(new InterceptorFactory())
+        .enableComplexMapKeySerialization()
+        .create();
+  }
+
+  public void testExceptionsPropagated() {
+    try {
+      gson.fromJson("{}", User.class);
+      fail();
+    } catch (JsonParseException expected) {}
+  }
+
+  public void testTopLevelClass() {
+    User user = gson.fromJson("{name:'bob',password:'pwd'}", User.class);
+    assertEquals(User.DEFAULT_EMAIL, user.email);
+  }
+
+  public void testList() {
+    List<User> list = gson.fromJson("[{name:'bob',password:'pwd'}]", new TypeToken<List<User>>(){}.getType());
+    User user = list.get(0);
+    assertEquals(User.DEFAULT_EMAIL, user.email);
+  }
+
+  public void testCollection() {
+    Collection<User> list = gson.fromJson("[{name:'bob',password:'pwd'}]", new TypeToken<Collection<User>>(){}.getType());
+    User user = list.iterator().next();
+    assertEquals(User.DEFAULT_EMAIL, user.email);
+  }
+
+  public void testMapKeyAndValues() {
+    Type mapType = new TypeToken<Map<User, Address>>(){}.getType();
+    try {
+      gson.fromJson("[[{name:'bob',password:'pwd'},{}]]", mapType);
+      fail();
+    } catch (JsonSyntaxException expected) {}
+    Map<User, Address> map = gson.fromJson("[[{name:'bob',password:'pwd'},{city:'Mountain View',state:'CA',zip:'94043'}]]",
+        mapType);
+    Entry<User, Address> entry = map.entrySet().iterator().next();
+    assertEquals(User.DEFAULT_EMAIL, entry.getKey().email);
+    assertEquals(Address.DEFAULT_FIRST_LINE, entry.getValue().firstLine);
+  }
+
+  public void testField() {
+    UserGroup userGroup = gson.fromJson("{user:{name:'bob',password:'pwd'}}", UserGroup.class);
+    assertEquals(User.DEFAULT_EMAIL, userGroup.user.email);
+  }
+
+  public void testCustomTypeAdapter() {
+    Gson gson = new GsonBuilder()
+        .registerTypeAdapter(User.class, new TypeAdapter<User>() {
+          @Override public void write(JsonWriter out, User value) throws IOException {
+            throw new UnsupportedOperationException();
+          }
+
+          @Override public User read(JsonReader in) throws IOException {
+            in.beginObject();
+            in.nextName();
+            String name = in.nextString();
+            in.nextName();
+            String password = in.nextString();
+            in.endObject();
+            return new User(name, password);
+          }
+        })
+        .registerTypeAdapterFactory(new InterceptorFactory())
+        .create();
+    UserGroup userGroup = gson.fromJson("{user:{name:'bob',password:'pwd'}}", UserGroup.class);
+    assertEquals(User.DEFAULT_EMAIL, userGroup.user.email);
+  }
+
+  public void testDirectInvocationOfTypeAdapter() throws Exception {
+    TypeAdapter<UserGroup> adapter = gson.getAdapter(UserGroup.class);
+    UserGroup userGroup = adapter.fromJson("{\"user\":{\"name\":\"bob\",\"password\":\"pwd\"}}");
+    assertEquals(User.DEFAULT_EMAIL, userGroup.user.email);
+  }
+
+  @SuppressWarnings("unused")
+  private static final class UserGroup {
+    User user;
+    String city;
+  }
+
+  @Intercept(postDeserialize = UserValidator.class)
+  @SuppressWarnings("unused")
+  private static final class User {
+    static final String DEFAULT_EMAIL = "invalid@invalid.com";
+    String name;
+    String password;
+    String email;
+    Address address;
+    public User(String name, String password) {
+      this.name = name;
+      this.password = password;
+    }
+  }
+
+  public static final class UserValidator implements JsonPostDeserializer<User> {
+    @Override public void postDeserialize(User user) {
+      if (user.name == null || user.password == null) {
+        throw new JsonSyntaxException("name and password are required fields.");
+      }
+      if (user.email == null) user.email = User.DEFAULT_EMAIL;
+    }
+  }
+
+  @Intercept(postDeserialize = AddressValidator.class)
+  @SuppressWarnings("unused")
+  private static final class Address {
+    static final String DEFAULT_FIRST_LINE = "unknown";
+    String firstLine;
+    String secondLine;
+    String city;
+    String state;
+    String zip;
+  }
+
+  public static final class AddressValidator implements JsonPostDeserializer<Address> {
+    @Override public void postDeserialize(Address address) {
+      if (address.city == null || address.state == null || address.zip == null) {
+        throw new JsonSyntaxException("Address city, state and zip are required fields.");
+      }
+      if (address.firstLine == null) address.firstLine = Address.DEFAULT_FIRST_LINE;
+    }
+  }
+}
diff --git a/extras/src/test/java/com/google/gson/typeadapters/PostConstructAdapterFactoryTest.java b/extras/src/test/java/com/google/gson/typeadapters/PostConstructAdapterFactoryTest.java
new file mode 100644
index 0000000..e3574bb
--- /dev/null
+++ b/extras/src/test/java/com/google/gson/typeadapters/PostConstructAdapterFactoryTest.java
@@ -0,0 +1,114 @@
+/*
+ * Copyright (C) 2016 Gson Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.typeadapters;
+
+import javax.annotation.PostConstruct;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+import junit.framework.TestCase;
+
+import java.util.Arrays;
+import java.util.List;
+
+public class PostConstructAdapterFactoryTest extends TestCase {
+    public void test() throws Exception {
+        Gson gson = new GsonBuilder()
+                .registerTypeAdapterFactory(new PostConstructAdapterFactory())
+                .create();
+        gson.fromJson("{\"bread\": \"white\", \"cheese\": \"cheddar\"}", Sandwich.class);
+        try {
+            gson.fromJson("{\"bread\": \"cheesey bread\", \"cheese\": \"swiss\"}", Sandwich.class);
+            fail();
+        } catch (IllegalArgumentException expected) {
+            assertEquals("too cheesey", expected.getMessage());
+        }
+    }
+
+    public void testList() {
+        MultipleSandwiches sandwiches = new MultipleSandwiches(Arrays.asList(
+            new Sandwich("white", "cheddar"),
+            new Sandwich("whole wheat", "swiss")));
+
+        Gson gson = new GsonBuilder().registerTypeAdapterFactory(new PostConstructAdapterFactory()).create();
+
+        // Throws NullPointerException without the fix in https://github.com/google/gson/pull/1103
+        String json = gson.toJson(sandwiches);
+        assertEquals("{\"sandwiches\":[{\"bread\":\"white\",\"cheese\":\"cheddar\"},{\"bread\":\"whole wheat\",\"cheese\":\"swiss\"}]}", json);
+
+        MultipleSandwiches sandwichesFromJson = gson.fromJson(json, MultipleSandwiches.class);
+        assertEquals(sandwiches, sandwichesFromJson);
+    }
+
+    static class Sandwich {
+        public String bread;
+        public String cheese;
+
+        public Sandwich(String bread, String cheese) {
+            this.bread = bread;
+            this.cheese = cheese;
+        }
+
+        @PostConstruct private void validate() {
+            if (bread.equals("cheesey bread") && cheese != null) {
+                throw new IllegalArgumentException("too cheesey");
+            }
+        }
+
+        @Override
+        public boolean equals(Object o) {
+            if (o == this) {
+                return true;
+            }
+            if (!(o instanceof Sandwich)) {
+                return false;
+            }
+            final Sandwich other = (Sandwich) o;
+            if (this.bread == null ? other.bread != null : !this.bread.equals(other.bread)) {
+                return false;
+            }
+            if (this.cheese == null ? other.cheese != null : !this.cheese.equals(other.cheese)) {
+                return false;
+            }
+            return true;
+        }
+    }
+
+    static class MultipleSandwiches {
+        public List<Sandwich> sandwiches;
+
+        public MultipleSandwiches(List<Sandwich> sandwiches) {
+            this.sandwiches = sandwiches;
+        }
+
+        @Override
+        public boolean equals(Object o) {
+            if (o == this) {
+                return true;
+            }
+            if (!(o instanceof MultipleSandwiches)) {
+                return false;
+            }
+            final MultipleSandwiches other = (MultipleSandwiches) o;
+            if (this.sandwiches == null ? other.sandwiches != null : !this.sandwiches.equals(other.sandwiches)) {
+                return false;
+            }
+            return true;
+        }
+    }
+}
diff --git a/extras/src/test/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactoryTest.java b/extras/src/test/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactoryTest.java
new file mode 100644
index 0000000..5159001
--- /dev/null
+++ b/extras/src/test/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactoryTest.java
@@ -0,0 +1,232 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.typeadapters;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonParseException;
+import com.google.gson.TypeAdapterFactory;
+import junit.framework.TestCase;
+
+public final class RuntimeTypeAdapterFactoryTest extends TestCase {
+
+  public void testRuntimeTypeAdapter() {
+    RuntimeTypeAdapterFactory<BillingInstrument> rta = RuntimeTypeAdapterFactory.of(
+        BillingInstrument.class)
+        .registerSubtype(CreditCard.class);
+    Gson gson = new GsonBuilder()
+        .registerTypeAdapterFactory(rta)
+        .create();
+
+    CreditCard original = new CreditCard("Jesse", 234);
+    assertEquals("{\"type\":\"CreditCard\",\"cvv\":234,\"ownerName\":\"Jesse\"}",
+        gson.toJson(original, BillingInstrument.class));
+    BillingInstrument deserialized = gson.fromJson(
+        "{type:'CreditCard',cvv:234,ownerName:'Jesse'}", BillingInstrument.class);
+    assertEquals("Jesse", deserialized.ownerName);
+    assertTrue(deserialized instanceof CreditCard);
+  }
+
+  public void testRuntimeTypeAdapterRecognizeSubtypes() {
+    // We don't have an explicit factory for CreditCard.class, but we do have one for
+    // BillingInstrument.class that has recognizeSubtypes(). So it should recognize CreditCard, and
+    // when we call gson.toJson(original) below, without an explicit type, it should be invoked.
+    RuntimeTypeAdapterFactory<BillingInstrument> rta = RuntimeTypeAdapterFactory.of(
+        BillingInstrument.class)
+        .recognizeSubtypes()
+        .registerSubtype(CreditCard.class);
+    Gson gson = new GsonBuilder()
+        .registerTypeAdapterFactory(rta)
+        .create();
+
+    CreditCard original = new CreditCard("Jesse", 234);
+    assertEquals("{\"type\":\"CreditCard\",\"cvv\":234,\"ownerName\":\"Jesse\"}",
+        gson.toJson(original));
+    BillingInstrument deserialized = gson.fromJson(
+        "{type:'CreditCard',cvv:234,ownerName:'Jesse'}", BillingInstrument.class);
+    assertEquals("Jesse", deserialized.ownerName);
+    assertTrue(deserialized instanceof CreditCard);
+  }
+
+  public void testRuntimeTypeIsBaseType() {
+    TypeAdapterFactory rta = RuntimeTypeAdapterFactory.of(
+        BillingInstrument.class)
+        .registerSubtype(BillingInstrument.class);
+    Gson gson = new GsonBuilder()
+        .registerTypeAdapterFactory(rta)
+        .create();
+
+    BillingInstrument original = new BillingInstrument("Jesse");
+    assertEquals("{\"type\":\"BillingInstrument\",\"ownerName\":\"Jesse\"}",
+        gson.toJson(original, BillingInstrument.class));
+    BillingInstrument deserialized = gson.fromJson(
+        "{type:'BillingInstrument',ownerName:'Jesse'}", BillingInstrument.class);
+    assertEquals("Jesse", deserialized.ownerName);
+  }
+
+  public void testNullBaseType() {
+    try {
+      RuntimeTypeAdapterFactory.of(null);
+      fail();
+    } catch (NullPointerException expected) {
+    }
+  }
+
+  public void testNullTypeFieldName() {
+    try {
+      RuntimeTypeAdapterFactory.of(BillingInstrument.class, null);
+      fail();
+    } catch (NullPointerException expected) {
+    }
+  }
+
+  public void testNullSubtype() {
+    RuntimeTypeAdapterFactory<BillingInstrument> rta = RuntimeTypeAdapterFactory.of(
+        BillingInstrument.class);
+    try {
+      rta.registerSubtype(null);
+      fail();
+    } catch (NullPointerException expected) {
+    }
+  }
+
+  public void testNullLabel() {
+    RuntimeTypeAdapterFactory<BillingInstrument> rta = RuntimeTypeAdapterFactory.of(
+        BillingInstrument.class);
+    try {
+      rta.registerSubtype(CreditCard.class, null);
+      fail();
+    } catch (NullPointerException expected) {
+    }
+  }
+
+  public void testDuplicateSubtype() {
+    RuntimeTypeAdapterFactory<BillingInstrument> rta = RuntimeTypeAdapterFactory.of(
+        BillingInstrument.class);
+    rta.registerSubtype(CreditCard.class, "CC");
+    try {
+      rta.registerSubtype(CreditCard.class, "Visa");
+      fail();
+    } catch (IllegalArgumentException expected) {
+    }
+  }
+
+  public void testDuplicateLabel() {
+    RuntimeTypeAdapterFactory<BillingInstrument> rta = RuntimeTypeAdapterFactory.of(
+        BillingInstrument.class);
+    rta.registerSubtype(CreditCard.class, "CC");
+    try {
+      rta.registerSubtype(BankTransfer.class, "CC");
+      fail();
+    } catch (IllegalArgumentException expected) {
+    }
+  }
+
+  public void testDeserializeMissingTypeField() {
+    TypeAdapterFactory billingAdapter = RuntimeTypeAdapterFactory.of(BillingInstrument.class)
+        .registerSubtype(CreditCard.class);
+    Gson gson = new GsonBuilder()
+        .registerTypeAdapterFactory(billingAdapter)
+        .create();
+    try {
+      gson.fromJson("{ownerName:'Jesse'}", BillingInstrument.class);
+      fail();
+    } catch (JsonParseException expected) {
+    }
+  }
+
+  public void testDeserializeMissingSubtype() {
+    TypeAdapterFactory billingAdapter = RuntimeTypeAdapterFactory.of(BillingInstrument.class)
+        .registerSubtype(BankTransfer.class);
+    Gson gson = new GsonBuilder()
+        .registerTypeAdapterFactory(billingAdapter)
+        .create();
+    try {
+      gson.fromJson("{type:'CreditCard',ownerName:'Jesse'}", BillingInstrument.class);
+      fail();
+    } catch (JsonParseException expected) {
+    }
+  }
+
+  public void testSerializeMissingSubtype() {
+    TypeAdapterFactory billingAdapter = RuntimeTypeAdapterFactory.of(BillingInstrument.class)
+        .registerSubtype(BankTransfer.class);
+    Gson gson = new GsonBuilder()
+        .registerTypeAdapterFactory(billingAdapter)
+        .create();
+    try {
+      gson.toJson(new CreditCard("Jesse", 456), BillingInstrument.class);
+      fail();
+    } catch (JsonParseException expected) {
+    }
+  }
+
+  public void testSerializeCollidingTypeFieldName() {
+    TypeAdapterFactory billingAdapter = RuntimeTypeAdapterFactory.of(BillingInstrument.class, "cvv")
+        .registerSubtype(CreditCard.class);
+    Gson gson = new GsonBuilder()
+        .registerTypeAdapterFactory(billingAdapter)
+        .create();
+    try {
+      gson.toJson(new CreditCard("Jesse", 456), BillingInstrument.class);
+      fail();
+    } catch (JsonParseException expected) {
+    }
+  }
+
+  public void testSerializeWrappedNullValue() {
+    TypeAdapterFactory billingAdapter = RuntimeTypeAdapterFactory.of(BillingInstrument.class)
+        .registerSubtype(CreditCard.class)
+        .registerSubtype(BankTransfer.class);    
+    Gson gson = new GsonBuilder()
+        .registerTypeAdapterFactory(billingAdapter)
+        .create();    
+    String serialized = gson.toJson(new BillingInstrumentWrapper(null), BillingInstrumentWrapper.class);
+    BillingInstrumentWrapper deserialized = gson.fromJson(serialized, BillingInstrumentWrapper.class);
+    assertNull(deserialized.instrument);
+  }
+
+  static class BillingInstrumentWrapper {
+    BillingInstrument instrument;
+    BillingInstrumentWrapper(BillingInstrument instrument) {
+      this.instrument = instrument;
+    }
+  }
+
+  static class BillingInstrument {
+    private final String ownerName;
+    BillingInstrument(String ownerName) {
+      this.ownerName = ownerName;
+    }
+  }
+
+  static class CreditCard extends BillingInstrument {
+    int cvv;
+    CreditCard(String ownerName, int cvv) {
+      super(ownerName);
+      this.cvv = cvv;
+    }
+  }
+
+  static class BankTransfer extends BillingInstrument {
+    int bankAccount;
+    BankTransfer(String ownerName, int bankAccount) {
+      super(ownerName);
+      this.bankAccount = bankAccount;
+    }
+  }
+}
diff --git a/extras/src/test/java/com/google/gson/typeadapters/UtcDateTypeAdapterTest.java b/extras/src/test/java/com/google/gson/typeadapters/UtcDateTypeAdapterTest.java
new file mode 100644
index 0000000..fe4104f
--- /dev/null
+++ b/extras/src/test/java/com/google/gson/typeadapters/UtcDateTypeAdapterTest.java
@@ -0,0 +1,87 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.typeadapters;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonParseException;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.Locale;
+import java.util.TimeZone;
+import junit.framework.TestCase;
+
+public final class UtcDateTypeAdapterTest extends TestCase {
+  private final Gson gson = new GsonBuilder()
+    .registerTypeAdapter(Date.class, new UtcDateTypeAdapter())
+    .create();
+
+  public void testLocalTimeZone() {
+    Date expected = new Date();
+    String json = gson.toJson(expected);
+    Date actual = gson.fromJson(json, Date.class);
+    assertEquals(expected.getTime(), actual.getTime());
+  }
+
+  public void testDifferentTimeZones() {
+    for (String timeZone : TimeZone.getAvailableIDs()) {
+      Calendar cal = Calendar.getInstance(TimeZone.getTimeZone(timeZone));
+      Date expected = cal.getTime();
+      String json = gson.toJson(expected);
+      // System.out.println(json + ": " + timeZone);
+      Date actual = gson.fromJson(json, Date.class);
+      assertEquals(expected.getTime(), actual.getTime());
+    }
+  }
+
+  /**
+   * JDK 1.7 introduced support for XXX format to indicate UTC date. But Android is older JDK.
+   * We want to make sure that this date is parseable in Android.
+   */
+  public void testUtcDatesOnJdkBefore1_7() {
+    Gson gson = new GsonBuilder()
+      .registerTypeAdapter(Date.class, new UtcDateTypeAdapter())
+      .create();
+    gson.fromJson("'2014-12-05T04:00:00.000Z'", Date.class);
+  }
+
+  public void testUtcWithJdk7Default() {
+    Date expected = new Date();
+    SimpleDateFormat iso8601Format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.US);
+    iso8601Format.setTimeZone(TimeZone.getTimeZone("UTC"));
+    String expectedJson = "\"" + iso8601Format.format(expected) + "\"";
+    String actualJson = gson.toJson(expected);
+    assertEquals(expectedJson, actualJson);
+    Date actual = gson.fromJson(expectedJson, Date.class);
+    assertEquals(expected.getTime(), actual.getTime());
+  }
+
+  public void testNullDateSerialization() {
+    String json = gson.toJson(null, Date.class);
+    assertEquals("null", json);
+  }
+
+  public void testWellFormedParseException() {
+    try {
+      gson.fromJson("2017-06-20T14:32:30", Date.class);
+      fail("No exception");
+    } catch (JsonParseException exe) {
+      assertEquals("java.text.ParseException: Failed to parse date ['2017-06-20T14']: 2017-06-20T14", exe.getMessage());
+    }
+  }
+}
diff --git a/gson/LICENSE b/gson/LICENSE
new file mode 100644
index 0000000..892eaed
--- /dev/null
+++ b/gson/LICENSE
@@ -0,0 +1,203 @@
+Google Gson

+

+                                 Apache License

+                           Version 2.0, January 2004

+                        http://www.apache.org/licenses/

+

+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

+

+   1. Definitions.

+

+      "License" shall mean the terms and conditions for use, reproduction,

+      and distribution as defined by Sections 1 through 9 of this document.

+

+      "Licensor" shall mean the copyright owner or entity authorized by

+      the copyright owner that is granting the License.

+

+      "Legal Entity" shall mean the union of the acting entity and all

+      other entities that control, are controlled by, or are under common

+      control with that entity. For the purposes of this definition,

+      "control" means (i) the power, direct or indirect, to cause the

+      direction or management of such entity, whether by contract or

+      otherwise, or (ii) ownership of fifty percent (50%) or more of the

+      outstanding shares, or (iii) beneficial ownership of such entity.

+

+      "You" (or "Your") shall mean an individual or Legal Entity

+      exercising permissions granted by this License.

+

+      "Source" form shall mean the preferred form for making modifications,

+      including but not limited to software source code, documentation

+      source, and configuration files.

+

+      "Object" form shall mean any form resulting from mechanical

+      transformation or translation of a Source form, including but

+      not limited to compiled object code, generated documentation,

+      and conversions to other media types.

+

+      "Work" shall mean the work of authorship, whether in Source or

+      Object form, made available under the License, as indicated by a

+      copyright notice that is included in or attached to the work

+      (an example is provided in the Appendix below).

+

+      "Derivative Works" shall mean any work, whether in Source or Object

+      form, that is based on (or derived from) the Work and for which the

+      editorial revisions, annotations, elaborations, or other modifications

+      represent, as a whole, an original work of authorship. For the purposes

+      of this License, Derivative Works shall not include works that remain

+      separable from, or merely link (or bind by name) to the interfaces of,

+      the Work and Derivative Works thereof.

+

+      "Contribution" shall mean any work of authorship, including

+      the original version of the Work and any modifications or additions

+      to that Work or Derivative Works thereof, that is intentionally

+      submitted to Licensor for inclusion in the Work by the copyright owner

+      or by an individual or Legal Entity authorized to submit on behalf of

+      the copyright owner. For the purposes of this definition, "submitted"

+      means any form of electronic, verbal, or written communication sent

+      to the Licensor or its representatives, including but not limited to

+      communication on electronic mailing lists, source code control systems,

+      and issue tracking systems that are managed by, or on behalf of, the

+      Licensor for the purpose of discussing and improving the Work, but

+      excluding communication that is conspicuously marked or otherwise

+      designated in writing by the copyright owner as "Not a Contribution."

+

+      "Contributor" shall mean Licensor and any individual or Legal Entity

+      on behalf of whom a Contribution has been received by Licensor and

+      subsequently incorporated within the Work.

+

+   2. Grant of Copyright License. Subject to the terms and conditions of

+      this License, each Contributor hereby grants to You a perpetual,

+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable

+      copyright license to reproduce, prepare Derivative Works of,

+      publicly display, publicly perform, sublicense, and distribute the

+      Work and such Derivative Works in Source or Object form.

+

+   3. Grant of Patent License. Subject to the terms and conditions of

+      this License, each Contributor hereby grants to You a perpetual,

+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable

+      (except as stated in this section) patent license to make, have made,

+      use, offer to sell, sell, import, and otherwise transfer the Work,

+      where such license applies only to those patent claims licensable

+      by such Contributor that are necessarily infringed by their

+      Contribution(s) alone or by combination of their Contribution(s)

+      with the Work to which such Contribution(s) was submitted. If You

+      institute patent litigation against any entity (including a

+      cross-claim or counterclaim in a lawsuit) alleging that the Work

+      or a Contribution incorporated within the Work constitutes direct

+      or contributory patent infringement, then any patent licenses

+      granted to You under this License for that Work shall terminate

+      as of the date such litigation is filed.

+

+   4. Redistribution. You may reproduce and distribute copies of the

+      Work or Derivative Works thereof in any medium, with or without

+      modifications, and in Source or Object form, provided that You

+      meet the following conditions:

+

+      (a) You must give any other recipients of the Work or

+          Derivative Works a copy of this License; and

+

+      (b) You must cause any modified files to carry prominent notices

+          stating that You changed the files; and

+

+      (c) You must retain, in the Source form of any Derivative Works

+          that You distribute, all copyright, patent, trademark, and

+          attribution notices from the Source form of the Work,

+          excluding those notices that do not pertain to any part of

+          the Derivative Works; and

+

+      (d) If the Work includes a "NOTICE" text file as part of its

+          distribution, then any Derivative Works that You distribute must

+          include a readable copy of the attribution notices contained

+          within such NOTICE file, excluding those notices that do not

+          pertain to any part of the Derivative Works, in at least one

+          of the following places: within a NOTICE text file distributed

+          as part of the Derivative Works; within the Source form or

+          documentation, if provided along with the Derivative Works; or,

+          within a display generated by the Derivative Works, if and

+          wherever such third-party notices normally appear. The contents

+          of the NOTICE file are for informational purposes only and

+          do not modify the License. You may add Your own attribution

+          notices within Derivative Works that You distribute, alongside

+          or as an addendum to the NOTICE text from the Work, provided

+          that such additional attribution notices cannot be construed

+          as modifying the License.

+

+      You may add Your own copyright statement to Your modifications and

+      may provide additional or different license terms and conditions

+      for use, reproduction, or distribution of Your modifications, or

+      for any such Derivative Works as a whole, provided Your use,

+      reproduction, and distribution of the Work otherwise complies with

+      the conditions stated in this License.

+

+   5. Submission of Contributions. Unless You explicitly state otherwise,

+      any Contribution intentionally submitted for inclusion in the Work

+      by You to the Licensor shall be under the terms and conditions of

+      this License, without any additional terms or conditions.

+      Notwithstanding the above, nothing herein shall supersede or modify

+      the terms of any separate license agreement you may have executed

+      with Licensor regarding such Contributions.

+

+   6. Trademarks. This License does not grant permission to use the trade

+      names, trademarks, service marks, or product names of the Licensor,

+      except as required for reasonable and customary use in describing the

+      origin of the Work and reproducing the content of the NOTICE file.

+

+   7. Disclaimer of Warranty. Unless required by applicable law or

+      agreed to in writing, Licensor provides the Work (and each

+      Contributor provides its Contributions) on an "AS IS" BASIS,

+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or

+      implied, including, without limitation, any warranties or conditions

+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A

+      PARTICULAR PURPOSE. You are solely responsible for determining the

+      appropriateness of using or redistributing the Work and assume any

+      risks associated with Your exercise of permissions under this License.

+

+   8. Limitation of Liability. In no event and under no legal theory,

+      whether in tort (including negligence), contract, or otherwise,

+      unless required by applicable law (such as deliberate and grossly

+      negligent acts) or agreed to in writing, shall any Contributor be

+      liable to You for damages, including any direct, indirect, special,

+      incidental, or consequential damages of any character arising as a

+      result of this License or out of the use or inability to use the

+      Work (including but not limited to damages for loss of goodwill,

+      work stoppage, computer failure or malfunction, or any and all

+      other commercial damages or losses), even if such Contributor

+      has been advised of the possibility of such damages.

+

+   9. Accepting Warranty or Additional Liability. While redistributing

+      the Work or Derivative Works thereof, You may choose to offer,

+      and charge a fee for, acceptance of support, warranty, indemnity,

+      or other liability obligations and/or rights consistent with this

+      License. However, in accepting such obligations, You may act only

+      on Your own behalf and on Your sole responsibility, not on behalf

+      of any other Contributor, and only if You agree to indemnify,

+      defend, and hold each Contributor harmless for any liability

+      incurred by, or claims asserted against, such Contributor by reason

+      of your accepting any such warranty or additional liability.

+

+   END OF TERMS AND CONDITIONS

+

+   APPENDIX: How to apply the Apache License to your work.

+

+      To apply the Apache License to your work, attach the following

+      boilerplate notice, with the fields enclosed by brackets "[]"

+      replaced with your own identifying information. (Don't include

+      the brackets!)  The text should be enclosed in the appropriate

+      comment syntax for the file format. We also recommend that a

+      file or class name and description of purpose be included on the

+      same "printed page" as the copyright notice for easier

+      identification within third-party archives.

+

+   Copyright 2008-2011 Google Inc.

+

+   Licensed under the Apache License, Version 2.0 (the "License");

+   you may not use this file except in compliance with the License.

+   You may obtain a copy of the License at

+

+       http://www.apache.org/licenses/LICENSE-2.0

+

+   Unless required by applicable law or agreed to in writing, software

+   distributed under the License is distributed on an "AS IS" BASIS,

+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

+   See the License for the specific language governing permissions and

+   limitations under the License.

diff --git a/gson/README.md b/gson/README.md
new file mode 100644
index 0000000..75ec9fc
--- /dev/null
+++ b/gson/README.md
@@ -0,0 +1,4 @@
+# gson
+
+This Maven module contains the Gson source code. The artifacts created by this module
+are deployed to Maven Central under the coordinates `com.google.code.gson:gson`.
diff --git a/gson/bnd.bnd b/gson/bnd.bnd
new file mode 100644
index 0000000..626a0c5
--- /dev/null
+++ b/gson/bnd.bnd
@@ -0,0 +1,19 @@
+Bundle-SymbolicName: com.google.gson
+Bundle-Name: ${project.name}
+Bundle-Description: ${project.description}
+Bundle-Vendor: Google Gson Project
+Bundle-ContactAddress: ${project.parent.url}
+Bundle-RequiredExecutionEnvironment: JavaSE-1.7, JavaSE-1.8
+Require-Capability: osgi.ee;filter:="(&(osgi.ee=JavaSE)(version=1.7))"
+
+# Optional dependency for JDK's sun.misc.Unsafe
+# https://bnd.bndtools.org/chapters/920-faq.html#remove-unwanted-imports-
+Import-Package: sun.misc;resolution:=optional, *
+
+-removeheaders: Private-Package
+
+-exportcontents:\
+    com.google.gson,\
+    com.google.gson.annotations,\
+    com.google.gson.reflect,\
+    com.google.gson.stream
diff --git a/gson/pom.xml b/gson/pom.xml
new file mode 100644
index 0000000..04af473
--- /dev/null
+++ b/gson/pom.xml
@@ -0,0 +1,211 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+  <modelVersion>4.0.0</modelVersion>
+
+  <parent>
+    <groupId>com.google.code.gson</groupId>
+    <artifactId>gson-parent</artifactId>
+    <version>2.9.1</version>
+  </parent>
+
+  <artifactId>gson</artifactId>
+  <name>Gson</name>
+
+  <licenses>
+    <license>
+      <name>Apache-2.0</name>
+      <url>https://www.apache.org/licenses/LICENSE-2.0.txt</url>
+    </license>
+  </licenses>
+
+  <dependencies>
+    <dependency>
+      <groupId>junit</groupId>
+      <artifactId>junit</artifactId>
+      <scope>test</scope>
+    </dependency>
+  </dependencies>
+
+  <build>
+    <plugins>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-compiler-plugin</artifactId>
+        <executions>
+          <execution>
+            <id>default-compile</id>
+            <configuration>
+              <excludes>
+                <!-- module-info.java is compiled using ModiTect -->
+                <exclude>module-info.java</exclude>
+              </excludes>
+            </configuration>
+          </execution>
+        </executions>
+      </plugin>
+      <!-- Note: Javadoc plugin has to be run in combination with >= `package` 
+        phase, e.g. `mvn package javadoc:javadoc`, otherwise it fails with
+        "Aggregator report contains named and unnamed modules" -->
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-surefire-plugin</artifactId>
+        <version>3.0.0-M7</version>
+        <configuration>
+          <!-- Deny illegal access, this is required for ReflectionAccessTest -->
+          <!-- Requires Java >= 9; Important: In case future Java versions 
+            don't support this flag anymore, don't remove it unless CI also runs with 
+            that Java version. Ideally would use toolchain to specify that this should 
+            run with e.g. Java 11, but Maven toolchain requirements (unlike Gradle ones) 
+            don't seem to be portable (every developer would have to set up toolchain 
+            configuration locally). -->
+          <argLine>--illegal-access=deny</argLine>
+        </configuration>
+      </plugin>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-javadoc-plugin</artifactId>
+        <configuration>
+          <excludePackageNames>com.google.gson.internal:com.google.gson.internal.bind</excludePackageNames>
+        </configuration>
+      </plugin>
+      <!-- Add module-info to JAR, see https://github.com/moditect/moditect#adding-module-descriptors-to-existing-jar-files -->
+      <!-- Uses ModiTect instead of separate maven-compiler-plugin executions 
+        for better Eclipse IDE support, see https://github.com/eclipse-m2e/m2e-core/issues/393 -->
+      <plugin>
+        <groupId>org.moditect</groupId>
+        <artifactId>moditect-maven-plugin</artifactId>
+        <version>1.0.0.RC2</version>
+        <executions>
+          <execution>
+            <id>add-module-info</id>
+            <phase>package</phase>
+            <goals>
+              <goal>add-module-info</goal>
+            </goals>
+            <configuration>
+              <jvmVersion>9</jvmVersion>
+              <module>
+                <moduleInfoFile>${project.build.sourceDirectory}/module-info.java</moduleInfoFile>
+              </module>
+              <!-- Overwrite the previously generated JAR file, if any -->
+              <overwriteExistingFiles>true</overwriteExistingFiles>
+            </configuration>
+          </execution>
+        </executions>
+      </plugin>
+      <plugin>
+        <groupId>biz.aQute.bnd</groupId>
+        <artifactId>bnd-maven-plugin</artifactId>
+        <version>6.3.1</version>
+        <executions>
+          <execution>
+            <goals>
+              <goal>bnd-process</goal>
+            </goals>
+          </execution>
+        </executions>
+      </plugin>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-jar-plugin</artifactId>
+        <configuration>
+          <archive>
+            <!-- Use existing manifest generated by BND plugin -->
+            <manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
+          </archive>
+        </configuration>
+      </plugin>
+      <plugin>
+        <groupId>org.codehaus.mojo</groupId>
+        <artifactId>templating-maven-plugin</artifactId>
+        <version>1.0.0</version>
+        <executions>
+          <execution>
+            <id>filtering-java-templates</id>
+            <goals>
+              <goal>filter-sources</goal>
+            </goals>
+            <configuration>
+              <sourceDirectory>${basedir}/src/main/java-templates</sourceDirectory>
+              <outputDirectory>${project.build.directory}/generated-sources/java-templates</outputDirectory>
+            </configuration>
+          </execution>
+        </executions>
+      </plugin>
+      <plugin>
+        <groupId>com.coderplus.maven.plugins</groupId>
+        <artifactId>copy-rename-maven-plugin</artifactId>
+        <version>1.0.1</version>
+        <executions>
+          <execution>
+            <id>pre-obfuscate-class</id>
+            <phase>process-test-classes</phase>
+            <goals>
+              <goal>rename</goal>
+            </goals>
+            <configuration>
+              <fileSets>
+                <fileSet>
+                  <sourceFile>${project.build.directory}/test-classes/com/google/gson/functional/EnumWithObfuscatedTest.class</sourceFile>
+                  <destinationFile>${project.build.directory}/test-classes-obfuscated-injar/com/google/gson/functional/EnumWithObfuscatedTest.class</destinationFile>
+                </fileSet>
+                <fileSet>
+                  <sourceFile>${project.build.directory}/test-classes/com/google/gson/functional/EnumWithObfuscatedTest$Gender.class</sourceFile>
+                  <destinationFile>${project.build.directory}/test-classes-obfuscated-injar/com/google/gson/functional/EnumWithObfuscatedTest$Gender.class</destinationFile>
+                </fileSet>
+              </fileSets>
+            </configuration>
+          </execution>
+        </executions>
+      </plugin>
+      <plugin>
+        <groupId>com.github.wvengen</groupId>
+        <artifactId>proguard-maven-plugin</artifactId>
+        <version>2.6.0</version>
+        <executions>
+          <execution>
+            <phase>process-test-classes</phase>
+            <goals>
+              <goal>proguard</goal>
+            </goals>
+          </execution>
+        </executions>
+        <configuration>
+          <obfuscate>true</obfuscate>
+          <injar>test-classes-obfuscated-injar</injar>
+          <outjar>test-classes-obfuscated-outjar</outjar>
+          <inFilter>**/*.class</inFilter>
+          <proguardInclude>${basedir}/src/test/resources/testcases-proguard.conf</proguardInclude>
+          <libs>
+            <lib>${project.build.directory}/classes</lib>
+            <lib>${java.home}/jmods/java.base.jmod</lib>
+          </libs>
+        </configuration>
+      </plugin>
+      <plugin>
+        <artifactId>maven-resources-plugin</artifactId>
+        <version>3.3.0</version>
+        <executions>
+          <execution>
+            <id>post-obfuscate-class</id>
+            <phase>process-test-classes</phase>
+            <goals>
+              <goal>copy-resources</goal>
+            </goals>
+            <configuration>
+              <outputDirectory>${project.build.directory}/test-classes/com/google/gson/functional</outputDirectory>
+              <resources>
+                <resource>
+                  <directory>${project.build.directory}/test-classes-obfuscated-outjar/com/google/gson/functional</directory>
+                  <includes>
+                    <include>EnumWithObfuscatedTest.class</include>
+                    <include>EnumWithObfuscatedTest$Gender.class</include>
+                  </includes>
+                </resource>
+              </resources>
+            </configuration>
+          </execution>
+        </executions>
+      </plugin>
+    </plugins>
+  </build>
+</project>
diff --git a/gson/src/main/java-templates/com/google/gson/internal/GsonBuildConfig.java b/gson/src/main/java-templates/com/google/gson/internal/GsonBuildConfig.java
new file mode 100644
index 0000000..a94c96b
--- /dev/null
+++ b/gson/src/main/java-templates/com/google/gson/internal/GsonBuildConfig.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2018 The Gson authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.internal;
+
+/**
+ * Build configuration for Gson. This file is automatically populated by
+ * templating-maven-plugin and .java/.class files are generated for use in Gson.
+ *
+ * @author Inderjeet Singh
+ */
+public final class GsonBuildConfig {
+  // Based on https://stackoverflow.com/questions/2469922/generate-a-version-java-file-in-maven
+
+  /** This field is automatically populated by Maven when a build is triggered */
+  public static final String VERSION = "${project.version}";
+
+  private GsonBuildConfig() { }
+}
diff --git a/gson/src/main/java/com/google/gson/ExclusionStrategy.java b/gson/src/main/java/com/google/gson/ExclusionStrategy.java
new file mode 100644
index 0000000..bc0dc74
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/ExclusionStrategy.java
@@ -0,0 +1,109 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+/**
+ * A strategy (or policy) definition that is used to decide whether or not a field or top-level
+ * class should be serialized or deserialized as part of the JSON output/input. For serialization,
+ * if the {@link #shouldSkipClass(Class)} method returns true then that class or field type
+ * will not be part of the JSON output. For deserialization, if {@link #shouldSkipClass(Class)}
+ * returns true, then it will not be set as part of the Java object structure.
+ *
+ * <p>The following are a few examples that shows how you can use this exclusion mechanism.
+ *
+ * <p><strong>Exclude fields and objects based on a particular class type:</strong>
+ * <pre class="code">
+ * private static class SpecificClassExclusionStrategy implements ExclusionStrategy {
+ *   private final Class&lt;?&gt; excludedThisClass;
+ *
+ *   public SpecificClassExclusionStrategy(Class&lt;?&gt; excludedThisClass) {
+ *     this.excludedThisClass = excludedThisClass;
+ *   }
+ *
+ *   public boolean shouldSkipClass(Class&lt;?&gt; clazz) {
+ *     return excludedThisClass.equals(clazz);
+ *   }
+ *
+ *   public boolean shouldSkipField(FieldAttributes f) {
+ *     return excludedThisClass.equals(f.getDeclaredClass());
+ *   }
+ * }
+ * </pre>
+ *
+ * <p><strong>Excludes fields and objects based on a particular annotation:</strong>
+ * <pre class="code">
+ * public &#64;interface FooAnnotation {
+ *   // some implementation here
+ * }
+ *
+ * // Excludes any field (or class) that is tagged with an "&#64;FooAnnotation"
+ * private static class FooAnnotationExclusionStrategy implements ExclusionStrategy {
+ *   public boolean shouldSkipClass(Class&lt;?&gt; clazz) {
+ *     return clazz.getAnnotation(FooAnnotation.class) != null;
+ *   }
+ *
+ *   public boolean shouldSkipField(FieldAttributes f) {
+ *     return f.getAnnotation(FooAnnotation.class) != null;
+ *   }
+ * }
+ * </pre>
+ *
+ * <p>Now if you want to configure {@code Gson} to use a user defined exclusion strategy, then
+ * the {@code GsonBuilder} is required. The following is an example of how you can use the
+ * {@code GsonBuilder} to configure Gson to use one of the above sample:
+ * <pre class="code">
+ * ExclusionStrategy excludeStrings = new UserDefinedExclusionStrategy(String.class);
+ * Gson gson = new GsonBuilder()
+ *     .setExclusionStrategies(excludeStrings)
+ *     .create();
+ * </pre>
+ *
+ * <p>For certain model classes, you may only want to serialize a field, but exclude it for
+ * deserialization. To do that, you can write an {@code ExclusionStrategy} as per normal;
+ * however, you would register it with the
+ * {@link GsonBuilder#addDeserializationExclusionStrategy(ExclusionStrategy)} method.
+ * For example:
+ * <pre class="code">
+ * ExclusionStrategy excludeStrings = new UserDefinedExclusionStrategy(String.class);
+ * Gson gson = new GsonBuilder()
+ *     .addDeserializationExclusionStrategy(excludeStrings)
+ *     .create();
+ * </pre>
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ *
+ * @see GsonBuilder#setExclusionStrategies(ExclusionStrategy...)
+ * @see GsonBuilder#addDeserializationExclusionStrategy(ExclusionStrategy)
+ * @see GsonBuilder#addSerializationExclusionStrategy(ExclusionStrategy)
+ *
+ * @since 1.4
+ */
+public interface ExclusionStrategy {
+
+  /**
+   * @param f the field object that is under test
+   * @return true if the field should be ignored; otherwise false
+   */
+  public boolean shouldSkipField(FieldAttributes f);
+
+  /**
+   * @param clazz the class object that is under test
+   * @return true if the class should be ignored; otherwise false
+   */
+  public boolean shouldSkipClass(Class<?> clazz);
+}
diff --git a/gson/src/main/java/com/google/gson/FieldAttributes.java b/gson/src/main/java/com/google/gson/FieldAttributes.java
new file mode 100644
index 0000000..9fb93f7
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/FieldAttributes.java
@@ -0,0 +1,142 @@
+/*
+ * Copyright (C) 2009 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import com.google.gson.internal.$Gson$Preconditions;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Field;
+import java.lang.reflect.Type;
+import java.util.Arrays;
+import java.util.Collection;
+
+/**
+ * A data object that stores attributes of a field.
+ *
+ * <p>This class is immutable; therefore, it can be safely shared across threads.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ *
+ * @since 1.4
+ */
+public final class FieldAttributes {
+  private final Field field;
+
+  /**
+   * Constructs a Field Attributes object from the {@code f}.
+   *
+   * @param f the field to pull attributes from
+   */
+  public FieldAttributes(Field f) {
+    $Gson$Preconditions.checkNotNull(f);
+    this.field = f;
+  }
+
+  /**
+   * @return the declaring class that contains this field
+   */
+  public Class<?> getDeclaringClass() {
+    return field.getDeclaringClass();
+  }
+
+  /**
+   * @return the name of the field
+   */
+  public String getName() {
+    return field.getName();
+  }
+
+  /**
+   * <p>For example, assume the following class definition:
+   * <pre class="code">
+   * public class Foo {
+   *   private String bar;
+   *   private List&lt;String&gt; red;
+   * }
+   *
+   * Type listParameterizedType = new TypeToken&lt;List&lt;String&gt;&gt;() {}.getType();
+   * </pre>
+   *
+   * <p>This method would return {@code String.class} for the {@code bar} field and
+   * {@code listParameterizedType} for the {@code red} field.
+   *
+   * @return the specific type declared for this field
+   */
+  public Type getDeclaredType() {
+    return field.getGenericType();
+  }
+
+  /**
+   * Returns the {@code Class} object that was declared for this field.
+   *
+   * <p>For example, assume the following class definition:
+   * <pre class="code">
+   * public class Foo {
+   *   private String bar;
+   *   private List&lt;String&gt; red;
+   * }
+   * </pre>
+   *
+   * <p>This method would return {@code String.class} for the {@code bar} field and
+   * {@code List.class} for the {@code red} field.
+   *
+   * @return the specific class object that was declared for the field
+   */
+  public Class<?> getDeclaredClass() {
+    return field.getType();
+  }
+
+  /**
+   * Return the {@code T} annotation object from this field if it exist; otherwise returns
+   * {@code null}.
+   *
+   * @param annotation the class of the annotation that will be retrieved
+   * @return the annotation instance if it is bound to the field; otherwise {@code null}
+   */
+  public <T extends Annotation> T getAnnotation(Class<T> annotation) {
+    return field.getAnnotation(annotation);
+  }
+
+  /**
+   * Return the annotations that are present on this field.
+   *
+   * @return an array of all the annotations set on the field
+   * @since 1.4
+   */
+  public Collection<Annotation> getAnnotations() {
+    return Arrays.asList(field.getAnnotations());
+  }
+
+  /**
+   * Returns {@code true} if the field is defined with the {@code modifier}.
+   *
+   * <p>This method is meant to be called as:
+   * <pre class="code">
+   * boolean hasPublicModifier = fieldAttribute.hasModifier(java.lang.reflect.Modifier.PUBLIC);
+   * </pre>
+   *
+   * @see java.lang.reflect.Modifier
+   */
+  public boolean hasModifier(int modifier) {
+    return (field.getModifiers() & modifier) != 0;
+  }
+
+  @Override
+  public String toString() {
+    return field.toString();
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/FieldNamingPolicy.java b/gson/src/main/java/com/google/gson/FieldNamingPolicy.java
new file mode 100644
index 0000000..a4fa7c2
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/FieldNamingPolicy.java
@@ -0,0 +1,200 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import java.lang.reflect.Field;
+import java.util.Locale;
+
+/**
+ * An enumeration that defines a few standard naming conventions for JSON field names.
+ * This enumeration should be used in conjunction with {@link com.google.gson.GsonBuilder}
+ * to configure a {@link com.google.gson.Gson} instance to properly translate Java field
+ * names into the desired JSON field names.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public enum FieldNamingPolicy implements FieldNamingStrategy {
+
+  /**
+   * Using this naming policy with Gson will ensure that the field name is
+   * unchanged.
+   */
+  IDENTITY() {
+    @Override public String translateName(Field f) {
+      return f.getName();
+    }
+  },
+
+  /**
+   * Using this naming policy with Gson will ensure that the first "letter" of the Java
+   * field name is capitalized when serialized to its JSON form.
+   *
+   * <p>Here are a few examples of the form "Java Field Name" ---&gt; "JSON Field Name":</p>
+   * <ul>
+   *   <li>someFieldName ---&gt; SomeFieldName</li>
+   *   <li>_someFieldName ---&gt; _SomeFieldName</li>
+   * </ul>
+   */
+  UPPER_CAMEL_CASE() {
+    @Override public String translateName(Field f) {
+      return upperCaseFirstLetter(f.getName());
+    }
+  },
+
+  /**
+   * Using this naming policy with Gson will ensure that the first "letter" of the Java
+   * field name is capitalized when serialized to its JSON form and the words will be
+   * separated by a space.
+   *
+   * <p>Here are a few examples of the form "Java Field Name" ---&gt; "JSON Field Name":</p>
+   * <ul>
+   *   <li>someFieldName ---&gt; Some Field Name</li>
+   *   <li>_someFieldName ---&gt; _Some Field Name</li>
+   * </ul>
+   *
+   * @since 1.4
+   */
+  UPPER_CAMEL_CASE_WITH_SPACES() {
+    @Override public String translateName(Field f) {
+      return upperCaseFirstLetter(separateCamelCase(f.getName(), ' '));
+    }
+  },
+
+  /**
+   * Using this naming policy with Gson will modify the Java Field name from its camel cased
+   * form to an upper case field name where each word is separated by an underscore (_).
+   *
+   * <p>Here are a few examples of the form "Java Field Name" ---&gt; "JSON Field Name":</p>
+   * <ul>
+   *   <li>someFieldName ---&gt; SOME_FIELD_NAME</li>
+   *   <li>_someFieldName ---&gt; _SOME_FIELD_NAME</li>
+   *   <li>aStringField ---&gt; A_STRING_FIELD</li>
+   *   <li>aURL ---&gt; A_U_R_L</li>
+   * </ul>
+   */
+  UPPER_CASE_WITH_UNDERSCORES() {
+    @Override public String translateName(Field f) {
+      return separateCamelCase(f.getName(), '_').toUpperCase(Locale.ENGLISH);
+    }
+  },
+
+  /**
+   * Using this naming policy with Gson will modify the Java Field name from its camel cased
+   * form to a lower case field name where each word is separated by an underscore (_).
+   *
+   * <p>Here are a few examples of the form "Java Field Name" ---&gt; "JSON Field Name":</p>
+   * <ul>
+   *   <li>someFieldName ---&gt; some_field_name</li>
+   *   <li>_someFieldName ---&gt; _some_field_name</li>
+   *   <li>aStringField ---&gt; a_string_field</li>
+   *   <li>aURL ---&gt; a_u_r_l</li>
+   * </ul>
+   */
+  LOWER_CASE_WITH_UNDERSCORES() {
+    @Override public String translateName(Field f) {
+      return separateCamelCase(f.getName(), '_').toLowerCase(Locale.ENGLISH);
+    }
+  },
+
+  /**
+   * Using this naming policy with Gson will modify the Java Field name from its camel cased
+   * form to a lower case field name where each word is separated by a dash (-).
+   *
+   * <p>Here are a few examples of the form "Java Field Name" ---&gt; "JSON Field Name":</p>
+   * <ul>
+   *   <li>someFieldName ---&gt; some-field-name</li>
+   *   <li>_someFieldName ---&gt; _some-field-name</li>
+   *   <li>aStringField ---&gt; a-string-field</li>
+   *   <li>aURL ---&gt; a-u-r-l</li>
+   * </ul>
+   * Using dashes in JavaScript is not recommended since dash is also used for a minus sign in
+   * expressions. This requires that a field named with dashes is always accessed as a quoted
+   * property like {@code myobject['my-field']}. Accessing it as an object field
+   * {@code myobject.my-field} will result in an unintended javascript expression.
+   * @since 1.4
+   */
+  LOWER_CASE_WITH_DASHES() {
+    @Override public String translateName(Field f) {
+      return separateCamelCase(f.getName(), '-').toLowerCase(Locale.ENGLISH);
+    }
+  },
+
+  /**
+   * Using this naming policy with Gson will modify the Java Field name from its camel cased
+   * form to a lower case field name where each word is separated by a dot (.).
+   *
+   * <p>Here are a few examples of the form "Java Field Name" ---&gt; "JSON Field Name":</p>
+   * <ul>
+   *   <li>someFieldName ---&gt; some.field.name</li>
+   *   <li>_someFieldName ---&gt; _some.field.name</li>
+   *   <li>aStringField ---&gt; a.string.field</li>
+   *   <li>aURL ---&gt; a.u.r.l</li>
+   * </ul>
+   * Using dots in JavaScript is not recommended since dot is also used for a member sign in
+   * expressions. This requires that a field named with dots is always accessed as a quoted
+   * property like {@code myobject['my.field']}. Accessing it as an object field
+   * {@code myobject.my.field} will result in an unintended javascript expression.
+   * @since 2.8
+   */
+  LOWER_CASE_WITH_DOTS() {
+    @Override public String translateName(Field f) {
+      return separateCamelCase(f.getName(), '.').toLowerCase(Locale.ENGLISH);
+    }
+  };
+
+  /**
+   * Converts the field name that uses camel-case define word separation into
+   * separate words that are separated by the provided {@code separator}.
+   */
+  static String separateCamelCase(String name, char separator) {
+    StringBuilder translation = new StringBuilder();
+    for (int i = 0, length = name.length(); i < length; i++) {
+      char character = name.charAt(i);
+      if (Character.isUpperCase(character) && translation.length() != 0) {
+        translation.append(separator);
+      }
+      translation.append(character);
+    }
+    return translation.toString();
+  }
+
+  /**
+   * Ensures the JSON field names begins with an upper case letter.
+   */
+  static String upperCaseFirstLetter(String s) {
+    int length = s.length();
+    for (int i = 0; i < length; i++) {
+      char c = s.charAt(i);
+      if (Character.isLetter(c)) {
+        if (Character.isUpperCase(c)) {
+          return s;
+        }
+
+        char uppercased = Character.toUpperCase(c);
+        // For leading letter only need one substring
+        if (i == 0) {
+          return uppercased + s.substring(1);
+        } else {
+          return s.substring(0, i) + uppercased + s.substring(i + 1);
+        }
+      }
+    }
+
+    return s;
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/FieldNamingStrategy.java b/gson/src/main/java/com/google/gson/FieldNamingStrategy.java
new file mode 100644
index 0000000..f2f7c48
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/FieldNamingStrategy.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import java.lang.reflect.Field;
+
+/**
+ * A mechanism for providing custom field naming in Gson. This allows the client code to translate
+ * field names into a particular convention that is not supported as a normal Java field
+ * declaration rules. For example, Java does not support "-" characters in a field name.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ * @since 1.3
+ */
+public interface FieldNamingStrategy {
+
+  /**
+   * Translates the field name into its JSON field name representation.
+   *
+   * @param f the field object that we are translating
+   * @return the translated field name.
+   * @since 1.3
+   */
+  public String translateName(Field f);
+}
diff --git a/gson/src/main/java/com/google/gson/Gson.java b/gson/src/main/java/com/google/gson/Gson.java
new file mode 100644
index 0000000..666e5f8
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/Gson.java
@@ -0,0 +1,1166 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import com.google.gson.internal.ConstructorConstructor;
+import com.google.gson.internal.Excluder;
+import com.google.gson.internal.GsonBuildConfig;
+import com.google.gson.internal.LazilyParsedNumber;
+import com.google.gson.internal.Primitives;
+import com.google.gson.internal.Streams;
+import com.google.gson.internal.bind.ArrayTypeAdapter;
+import com.google.gson.internal.bind.CollectionTypeAdapterFactory;
+import com.google.gson.internal.bind.DateTypeAdapter;
+import com.google.gson.internal.bind.JsonAdapterAnnotationTypeAdapterFactory;
+import com.google.gson.internal.bind.JsonTreeReader;
+import com.google.gson.internal.bind.JsonTreeWriter;
+import com.google.gson.internal.bind.MapTypeAdapterFactory;
+import com.google.gson.internal.bind.NumberTypeAdapter;
+import com.google.gson.internal.bind.ObjectTypeAdapter;
+import com.google.gson.internal.bind.ReflectiveTypeAdapterFactory;
+import com.google.gson.internal.bind.TypeAdapters;
+import com.google.gson.internal.sql.SqlTypesSupport;
+import com.google.gson.reflect.TypeToken;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonToken;
+import com.google.gson.stream.JsonWriter;
+import com.google.gson.stream.MalformedJsonException;
+import java.io.EOFException;
+import java.io.IOException;
+import java.io.Reader;
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.io.Writer;
+import java.lang.reflect.Type;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.text.DateFormat;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicLongArray;
+
+/**
+ * This is the main class for using Gson. Gson is typically used by first constructing a
+ * Gson instance and then invoking {@link #toJson(Object)} or {@link #fromJson(String, Class)}
+ * methods on it. Gson instances are Thread-safe so you can reuse them freely across multiple
+ * threads.
+ *
+ * <p>You can create a Gson instance by invoking {@code new Gson()} if the default configuration
+ * is all you need. You can also use {@link GsonBuilder} to build a Gson instance with various
+ * configuration options such as versioning support, pretty printing, custom
+ * {@link JsonSerializer}s, {@link JsonDeserializer}s, and {@link InstanceCreator}s.</p>
+ *
+ * <p>Here is an example of how Gson is used for a simple Class:
+ *
+ * <pre>
+ * Gson gson = new Gson(); // Or use new GsonBuilder().create();
+ * MyType target = new MyType();
+ * String json = gson.toJson(target); // serializes target to Json
+ * MyType target2 = gson.fromJson(json, MyType.class); // deserializes json into target2
+ * </pre>
+ *
+ * <p>If the object that your are serializing/deserializing is a {@code ParameterizedType}
+ * (i.e. contains at least one type parameter and may be an array) then you must use the
+ * {@link #toJson(Object, Type)} or {@link #fromJson(String, Type)} method. Here is an
+ * example for serializing and deserializing a {@code ParameterizedType}:
+ *
+ * <pre>
+ * Type listType = new TypeToken&lt;List&lt;String&gt;&gt;() {}.getType();
+ * List&lt;String&gt; target = new LinkedList&lt;String&gt;();
+ * target.add("blah");
+ *
+ * Gson gson = new Gson();
+ * String json = gson.toJson(target, listType);
+ * List&lt;String&gt; target2 = gson.fromJson(json, listType);
+ * </pre>
+ *
+ * <p>See the <a href="https://sites.google.com/site/gson/gson-user-guide">Gson User Guide</a>
+ * for a more complete set of examples.</p>
+ *
+ * <h2>Lenient JSON handling</h2>
+ * For legacy reasons most of the {@code Gson} methods allow JSON data which does not
+ * comply with the JSON specification, regardless of whether {@link GsonBuilder#setLenient()}
+ * is used or not. If this behavior is not desired, the following workarounds can be used:
+ *
+ * <h3>Serialization</h3>
+ * <ol>
+ *   <li>Use {@link #getAdapter(Class)} to obtain the adapter for the type to be serialized
+ *   <li>When using an existing {@code JsonWriter}, manually apply the writer settings of this
+ *       {@code Gson} instance listed by {@link #newJsonWriter(Writer)}.<br>
+ *       Otherwise, when not using an existing {@code JsonWriter}, use {@link #newJsonWriter(Writer)}
+ *       to construct one.
+ *   <li>Call {@link TypeAdapter#write(JsonWriter, Object)}
+ * </ol>
+ *
+ * <h3>Deserialization</h3>
+ * <ol>
+ *   <li>Use {@link #getAdapter(Class)} to obtain the adapter for the type to be deserialized
+ *   <li>When using an existing {@code JsonReader}, manually apply the reader settings of this
+ *       {@code Gson} instance listed by {@link #newJsonReader(Reader)}.<br>
+ *       Otherwise, when not using an existing {@code JsonReader}, use {@link #newJsonReader(Reader)}
+ *       to construct one.
+ *   <li>Call {@link TypeAdapter#read(JsonReader)}
+ *   <li>Call {@link JsonReader#peek()} and verify that the result is {@link JsonToken#END_DOCUMENT}
+ *       to make sure there is no trailing data
+ * </ol>
+ *
+ * @see com.google.gson.reflect.TypeToken
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ * @author Jesse Wilson
+ */
+public final class Gson {
+  static final boolean DEFAULT_JSON_NON_EXECUTABLE = false;
+  static final boolean DEFAULT_LENIENT = false;
+  static final boolean DEFAULT_PRETTY_PRINT = false;
+  static final boolean DEFAULT_ESCAPE_HTML = true;
+  static final boolean DEFAULT_SERIALIZE_NULLS = false;
+  static final boolean DEFAULT_COMPLEX_MAP_KEYS = false;
+  static final boolean DEFAULT_SPECIALIZE_FLOAT_VALUES = false;
+  static final boolean DEFAULT_USE_JDK_UNSAFE = true;
+  static final String DEFAULT_DATE_PATTERN = null;
+  static final FieldNamingStrategy DEFAULT_FIELD_NAMING_STRATEGY = FieldNamingPolicy.IDENTITY;
+  static final ToNumberStrategy DEFAULT_OBJECT_TO_NUMBER_STRATEGY = ToNumberPolicy.DOUBLE;
+  static final ToNumberStrategy DEFAULT_NUMBER_TO_NUMBER_STRATEGY = ToNumberPolicy.LAZILY_PARSED_NUMBER;
+
+  private static final TypeToken<?> NULL_KEY_SURROGATE = TypeToken.get(Object.class);
+  private static final String JSON_NON_EXECUTABLE_PREFIX = ")]}'\n";
+
+  /**
+   * This thread local guards against reentrant calls to getAdapter(). In
+   * certain object graphs, creating an adapter for a type may recursively
+   * require an adapter for the same type! Without intervention, the recursive
+   * lookup would stack overflow. We cheat by returning a proxy type adapter.
+   * The proxy is wired up once the initial adapter has been created.
+   */
+  private final ThreadLocal<Map<TypeToken<?>, FutureTypeAdapter<?>>> calls
+      = new ThreadLocal<>();
+
+  private final Map<TypeToken<?>, TypeAdapter<?>> typeTokenCache = new ConcurrentHashMap<>();
+
+  private final ConstructorConstructor constructorConstructor;
+  private final JsonAdapterAnnotationTypeAdapterFactory jsonAdapterFactory;
+
+  final List<TypeAdapterFactory> factories;
+
+  final Excluder excluder;
+  final FieldNamingStrategy fieldNamingStrategy;
+  final Map<Type, InstanceCreator<?>> instanceCreators;
+  final boolean serializeNulls;
+  final boolean complexMapKeySerialization;
+  final boolean generateNonExecutableJson;
+  final boolean htmlSafe;
+  final boolean prettyPrinting;
+  final boolean lenient;
+  final boolean serializeSpecialFloatingPointValues;
+  final boolean useJdkUnsafe;
+  final String datePattern;
+  final int dateStyle;
+  final int timeStyle;
+  final LongSerializationPolicy longSerializationPolicy;
+  final List<TypeAdapterFactory> builderFactories;
+  final List<TypeAdapterFactory> builderHierarchyFactories;
+  final ToNumberStrategy objectToNumberStrategy;
+  final ToNumberStrategy numberToNumberStrategy;
+  final List<ReflectionAccessFilter> reflectionFilters;
+
+  /**
+   * Constructs a Gson object with default configuration. The default configuration has the
+   * following settings:
+   * <ul>
+   *   <li>The JSON generated by <code>toJson</code> methods is in compact representation. This
+   *   means that all the unneeded white-space is removed. You can change this behavior with
+   *   {@link GsonBuilder#setPrettyPrinting()}. </li>
+   *   <li>The generated JSON omits all the fields that are null. Note that nulls in arrays are
+   *   kept as is since an array is an ordered list. Moreover, if a field is not null, but its
+   *   generated JSON is empty, the field is kept. You can configure Gson to serialize null values
+   *   by setting {@link GsonBuilder#serializeNulls()}.</li>
+   *   <li>Gson provides default serialization and deserialization for Enums, {@link Map},
+   *   {@link java.net.URL}, {@link java.net.URI}, {@link java.util.Locale}, {@link java.util.Date},
+   *   {@link java.math.BigDecimal}, and {@link java.math.BigInteger} classes. If you would prefer
+   *   to change the default representation, you can do so by registering a type adapter through
+   *   {@link GsonBuilder#registerTypeAdapter(Type, Object)}. </li>
+   *   <li>The default Date format is same as {@link java.text.DateFormat#DEFAULT}. This format
+   *   ignores the millisecond portion of the date during serialization. You can change
+   *   this by invoking {@link GsonBuilder#setDateFormat(int)} or
+   *   {@link GsonBuilder#setDateFormat(String)}. </li>
+   *   <li>By default, Gson ignores the {@link com.google.gson.annotations.Expose} annotation.
+   *   You can enable Gson to serialize/deserialize only those fields marked with this annotation
+   *   through {@link GsonBuilder#excludeFieldsWithoutExposeAnnotation()}. </li>
+   *   <li>By default, Gson ignores the {@link com.google.gson.annotations.Since} annotation. You
+   *   can enable Gson to use this annotation through {@link GsonBuilder#setVersion(double)}.</li>
+   *   <li>The default field naming policy for the output Json is same as in Java. So, a Java class
+   *   field <code>versionNumber</code> will be output as <code>&quot;versionNumber&quot;</code> in
+   *   Json. The same rules are applied for mapping incoming Json to the Java classes. You can
+   *   change this policy through {@link GsonBuilder#setFieldNamingPolicy(FieldNamingPolicy)}.</li>
+   *   <li>By default, Gson excludes <code>transient</code> or <code>static</code> fields from
+   *   consideration for serialization and deserialization. You can change this behavior through
+   *   {@link GsonBuilder#excludeFieldsWithModifiers(int...)}.</li>
+   * </ul>
+   */
+  public Gson() {
+    this(Excluder.DEFAULT, DEFAULT_FIELD_NAMING_STRATEGY,
+        Collections.<Type, InstanceCreator<?>>emptyMap(), DEFAULT_SERIALIZE_NULLS,
+        DEFAULT_COMPLEX_MAP_KEYS, DEFAULT_JSON_NON_EXECUTABLE, DEFAULT_ESCAPE_HTML,
+        DEFAULT_PRETTY_PRINT, DEFAULT_LENIENT, DEFAULT_SPECIALIZE_FLOAT_VALUES,
+        DEFAULT_USE_JDK_UNSAFE,
+        LongSerializationPolicy.DEFAULT, DEFAULT_DATE_PATTERN, DateFormat.DEFAULT, DateFormat.DEFAULT,
+        Collections.<TypeAdapterFactory>emptyList(), Collections.<TypeAdapterFactory>emptyList(),
+        Collections.<TypeAdapterFactory>emptyList(), DEFAULT_OBJECT_TO_NUMBER_STRATEGY, DEFAULT_NUMBER_TO_NUMBER_STRATEGY,
+        Collections.<ReflectionAccessFilter>emptyList());
+  }
+
+  Gson(Excluder excluder, FieldNamingStrategy fieldNamingStrategy,
+      Map<Type, InstanceCreator<?>> instanceCreators, boolean serializeNulls,
+      boolean complexMapKeySerialization, boolean generateNonExecutableGson, boolean htmlSafe,
+      boolean prettyPrinting, boolean lenient, boolean serializeSpecialFloatingPointValues,
+      boolean useJdkUnsafe,
+      LongSerializationPolicy longSerializationPolicy, String datePattern, int dateStyle,
+      int timeStyle, List<TypeAdapterFactory> builderFactories,
+      List<TypeAdapterFactory> builderHierarchyFactories,
+      List<TypeAdapterFactory> factoriesToBeAdded,
+      ToNumberStrategy objectToNumberStrategy, ToNumberStrategy numberToNumberStrategy,
+      List<ReflectionAccessFilter> reflectionFilters) {
+    this.excluder = excluder;
+    this.fieldNamingStrategy = fieldNamingStrategy;
+    this.instanceCreators = instanceCreators;
+    this.constructorConstructor = new ConstructorConstructor(instanceCreators, useJdkUnsafe, reflectionFilters);
+    this.serializeNulls = serializeNulls;
+    this.complexMapKeySerialization = complexMapKeySerialization;
+    this.generateNonExecutableJson = generateNonExecutableGson;
+    this.htmlSafe = htmlSafe;
+    this.prettyPrinting = prettyPrinting;
+    this.lenient = lenient;
+    this.serializeSpecialFloatingPointValues = serializeSpecialFloatingPointValues;
+    this.useJdkUnsafe = useJdkUnsafe;
+    this.longSerializationPolicy = longSerializationPolicy;
+    this.datePattern = datePattern;
+    this.dateStyle = dateStyle;
+    this.timeStyle = timeStyle;
+    this.builderFactories = builderFactories;
+    this.builderHierarchyFactories = builderHierarchyFactories;
+    this.objectToNumberStrategy = objectToNumberStrategy;
+    this.numberToNumberStrategy = numberToNumberStrategy;
+    this.reflectionFilters = reflectionFilters;
+
+    List<TypeAdapterFactory> factories = new ArrayList<>();
+
+    // built-in type adapters that cannot be overridden
+    factories.add(TypeAdapters.JSON_ELEMENT_FACTORY);
+    factories.add(ObjectTypeAdapter.getFactory(objectToNumberStrategy));
+
+    // the excluder must precede all adapters that handle user-defined types
+    factories.add(excluder);
+
+    // users' type adapters
+    factories.addAll(factoriesToBeAdded);
+
+    // type adapters for basic platform types
+    factories.add(TypeAdapters.STRING_FACTORY);
+    factories.add(TypeAdapters.INTEGER_FACTORY);
+    factories.add(TypeAdapters.BOOLEAN_FACTORY);
+    factories.add(TypeAdapters.BYTE_FACTORY);
+    factories.add(TypeAdapters.SHORT_FACTORY);
+    TypeAdapter<Number> longAdapter = longAdapter(longSerializationPolicy);
+    factories.add(TypeAdapters.newFactory(long.class, Long.class, longAdapter));
+    factories.add(TypeAdapters.newFactory(double.class, Double.class,
+            doubleAdapter(serializeSpecialFloatingPointValues)));
+    factories.add(TypeAdapters.newFactory(float.class, Float.class,
+            floatAdapter(serializeSpecialFloatingPointValues)));
+    factories.add(NumberTypeAdapter.getFactory(numberToNumberStrategy));
+    factories.add(TypeAdapters.ATOMIC_INTEGER_FACTORY);
+    factories.add(TypeAdapters.ATOMIC_BOOLEAN_FACTORY);
+    factories.add(TypeAdapters.newFactory(AtomicLong.class, atomicLongAdapter(longAdapter)));
+    factories.add(TypeAdapters.newFactory(AtomicLongArray.class, atomicLongArrayAdapter(longAdapter)));
+    factories.add(TypeAdapters.ATOMIC_INTEGER_ARRAY_FACTORY);
+    factories.add(TypeAdapters.CHARACTER_FACTORY);
+    factories.add(TypeAdapters.STRING_BUILDER_FACTORY);
+    factories.add(TypeAdapters.STRING_BUFFER_FACTORY);
+    factories.add(TypeAdapters.newFactory(BigDecimal.class, TypeAdapters.BIG_DECIMAL));
+    factories.add(TypeAdapters.newFactory(BigInteger.class, TypeAdapters.BIG_INTEGER));
+    // Add adapter for LazilyParsedNumber because user can obtain it from Gson and then try to serialize it again
+    factories.add(TypeAdapters.newFactory(LazilyParsedNumber.class, TypeAdapters.LAZILY_PARSED_NUMBER));
+    factories.add(TypeAdapters.URL_FACTORY);
+    factories.add(TypeAdapters.URI_FACTORY);
+    factories.add(TypeAdapters.UUID_FACTORY);
+    factories.add(TypeAdapters.CURRENCY_FACTORY);
+    factories.add(TypeAdapters.LOCALE_FACTORY);
+    factories.add(TypeAdapters.INET_ADDRESS_FACTORY);
+    factories.add(TypeAdapters.BIT_SET_FACTORY);
+    factories.add(DateTypeAdapter.FACTORY);
+    factories.add(TypeAdapters.CALENDAR_FACTORY);
+
+    if (SqlTypesSupport.SUPPORTS_SQL_TYPES) {
+      factories.add(SqlTypesSupport.TIME_FACTORY);
+      factories.add(SqlTypesSupport.DATE_FACTORY);
+      factories.add(SqlTypesSupport.TIMESTAMP_FACTORY);
+    }
+
+    factories.add(ArrayTypeAdapter.FACTORY);
+    factories.add(TypeAdapters.CLASS_FACTORY);
+
+    // type adapters for composite and user-defined types
+    factories.add(new CollectionTypeAdapterFactory(constructorConstructor));
+    factories.add(new MapTypeAdapterFactory(constructorConstructor, complexMapKeySerialization));
+    this.jsonAdapterFactory = new JsonAdapterAnnotationTypeAdapterFactory(constructorConstructor);
+    factories.add(jsonAdapterFactory);
+    factories.add(TypeAdapters.ENUM_FACTORY);
+    factories.add(new ReflectiveTypeAdapterFactory(
+        constructorConstructor, fieldNamingStrategy, excluder, jsonAdapterFactory, reflectionFilters));
+
+    this.factories = Collections.unmodifiableList(factories);
+  }
+
+  /**
+   * Returns a new GsonBuilder containing all custom factories and configuration used by the current
+   * instance.
+   *
+   * @return a GsonBuilder instance.
+   */
+  public GsonBuilder newBuilder() {
+    return new GsonBuilder(this);
+  }
+
+  /**
+   * @deprecated This method by accident exposes an internal Gson class; it might be removed in a
+   * future version.
+   */
+  @Deprecated
+  public Excluder excluder() {
+    return excluder;
+  }
+
+  /**
+   * Returns the field naming strategy used by this Gson instance.
+   *
+   * @see GsonBuilder#setFieldNamingStrategy(FieldNamingStrategy)
+   */
+  public FieldNamingStrategy fieldNamingStrategy() {
+    return fieldNamingStrategy;
+  }
+
+  /**
+   * Returns whether this Gson instance is serializing JSON object properties with
+   * {@code null} values, or just omits them.
+   *
+   * @see GsonBuilder#serializeNulls()
+   */
+  public boolean serializeNulls() {
+    return serializeNulls;
+  }
+
+  /**
+   * Returns whether this Gson instance produces JSON output which is
+   * HTML-safe, that means all HTML characters are escaped.
+   *
+   * @see GsonBuilder#disableHtmlEscaping()
+   */
+  public boolean htmlSafe() {
+    return htmlSafe;
+  }
+
+  private TypeAdapter<Number> doubleAdapter(boolean serializeSpecialFloatingPointValues) {
+    if (serializeSpecialFloatingPointValues) {
+      return TypeAdapters.DOUBLE;
+    }
+    return new TypeAdapter<Number>() {
+      @Override public Double read(JsonReader in) throws IOException {
+        if (in.peek() == JsonToken.NULL) {
+          in.nextNull();
+          return null;
+        }
+        return in.nextDouble();
+      }
+      @Override public void write(JsonWriter out, Number value) throws IOException {
+        if (value == null) {
+          out.nullValue();
+          return;
+        }
+        double doubleValue = value.doubleValue();
+        checkValidFloatingPoint(doubleValue);
+        out.value(value);
+      }
+    };
+  }
+
+  private TypeAdapter<Number> floatAdapter(boolean serializeSpecialFloatingPointValues) {
+    if (serializeSpecialFloatingPointValues) {
+      return TypeAdapters.FLOAT;
+    }
+    return new TypeAdapter<Number>() {
+      @Override public Float read(JsonReader in) throws IOException {
+        if (in.peek() == JsonToken.NULL) {
+          in.nextNull();
+          return null;
+        }
+        return (float) in.nextDouble();
+      }
+      @Override public void write(JsonWriter out, Number value) throws IOException {
+        if (value == null) {
+          out.nullValue();
+          return;
+        }
+        float floatValue = value.floatValue();
+        checkValidFloatingPoint(floatValue);
+        out.value(value);
+      }
+    };
+  }
+
+  static void checkValidFloatingPoint(double value) {
+    if (Double.isNaN(value) || Double.isInfinite(value)) {
+      throw new IllegalArgumentException(value
+          + " is not a valid double value as per JSON specification. To override this"
+          + " behavior, use GsonBuilder.serializeSpecialFloatingPointValues() method.");
+    }
+  }
+
+  private static TypeAdapter<Number> longAdapter(LongSerializationPolicy longSerializationPolicy) {
+    if (longSerializationPolicy == LongSerializationPolicy.DEFAULT) {
+      return TypeAdapters.LONG;
+    }
+    return new TypeAdapter<Number>() {
+      @Override public Number read(JsonReader in) throws IOException {
+        if (in.peek() == JsonToken.NULL) {
+          in.nextNull();
+          return null;
+        }
+        return in.nextLong();
+      }
+      @Override public void write(JsonWriter out, Number value) throws IOException {
+        if (value == null) {
+          out.nullValue();
+          return;
+        }
+        out.value(value.toString());
+      }
+    };
+  }
+
+  private static TypeAdapter<AtomicLong> atomicLongAdapter(final TypeAdapter<Number> longAdapter) {
+    return new TypeAdapter<AtomicLong>() {
+      @Override public void write(JsonWriter out, AtomicLong value) throws IOException {
+        longAdapter.write(out, value.get());
+      }
+      @Override public AtomicLong read(JsonReader in) throws IOException {
+        Number value = longAdapter.read(in);
+        return new AtomicLong(value.longValue());
+      }
+    }.nullSafe();
+  }
+
+  private static TypeAdapter<AtomicLongArray> atomicLongArrayAdapter(final TypeAdapter<Number> longAdapter) {
+    return new TypeAdapter<AtomicLongArray>() {
+      @Override public void write(JsonWriter out, AtomicLongArray value) throws IOException {
+        out.beginArray();
+        for (int i = 0, length = value.length(); i < length; i++) {
+          longAdapter.write(out, value.get(i));
+        }
+        out.endArray();
+      }
+      @Override public AtomicLongArray read(JsonReader in) throws IOException {
+        List<Long> list = new ArrayList<>();
+        in.beginArray();
+        while (in.hasNext()) {
+            long value = longAdapter.read(in).longValue();
+            list.add(value);
+        }
+        in.endArray();
+        int length = list.size();
+        AtomicLongArray array = new AtomicLongArray(length);
+        for (int i = 0; i < length; ++i) {
+          array.set(i, list.get(i));
+        }
+        return array;
+      }
+    }.nullSafe();
+  }
+
+  /**
+   * Returns the type adapter for {@code} type.
+   *
+   * @throws IllegalArgumentException if this GSON cannot serialize and
+   *     deserialize {@code type}.
+   */
+  @SuppressWarnings("unchecked")
+  public <T> TypeAdapter<T> getAdapter(TypeToken<T> type) {
+    TypeAdapter<?> cached = typeTokenCache.get(type == null ? NULL_KEY_SURROGATE : type);
+    if (cached != null) {
+      return (TypeAdapter<T>) cached;
+    }
+
+    Map<TypeToken<?>, FutureTypeAdapter<?>> threadCalls = calls.get();
+    boolean requiresThreadLocalCleanup = false;
+    if (threadCalls == null) {
+      threadCalls = new HashMap<>();
+      calls.set(threadCalls);
+      requiresThreadLocalCleanup = true;
+    }
+
+    // the key and value type parameters always agree
+    FutureTypeAdapter<T> ongoingCall = (FutureTypeAdapter<T>) threadCalls.get(type);
+    if (ongoingCall != null) {
+      return ongoingCall;
+    }
+
+    try {
+      FutureTypeAdapter<T> call = new FutureTypeAdapter<>();
+      threadCalls.put(type, call);
+
+      for (TypeAdapterFactory factory : factories) {
+        TypeAdapter<T> candidate = factory.create(this, type);
+        if (candidate != null) {
+          call.setDelegate(candidate);
+          typeTokenCache.put(type, candidate);
+          return candidate;
+        }
+      }
+      throw new IllegalArgumentException("GSON (" + GsonBuildConfig.VERSION + ") cannot handle " + type);
+    } finally {
+      threadCalls.remove(type);
+
+      if (requiresThreadLocalCleanup) {
+        calls.remove();
+      }
+    }
+  }
+
+  /**
+   * This method is used to get an alternate type adapter for the specified type. This is used
+   * to access a type adapter that is overridden by a {@link TypeAdapterFactory} that you
+   * may have registered. This features is typically used when you want to register a type
+   * adapter that does a little bit of work but then delegates further processing to the Gson
+   * default type adapter. Here is an example:
+   * <p>Let's say we want to write a type adapter that counts the number of objects being read
+   *  from or written to JSON. We can achieve this by writing a type adapter factory that uses
+   *  the <code>getDelegateAdapter</code> method:
+   *  <pre> {@code
+   *  class StatsTypeAdapterFactory implements TypeAdapterFactory {
+   *    public int numReads = 0;
+   *    public int numWrites = 0;
+   *    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
+   *      final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
+   *      return new TypeAdapter<T>() {
+   *        public void write(JsonWriter out, T value) throws IOException {
+   *          ++numWrites;
+   *          delegate.write(out, value);
+   *        }
+   *        public T read(JsonReader in) throws IOException {
+   *          ++numReads;
+   *          return delegate.read(in);
+   *        }
+   *      };
+   *    }
+   *  }
+   *  } </pre>
+   *  This factory can now be used like this:
+   *  <pre> {@code
+   *  StatsTypeAdapterFactory stats = new StatsTypeAdapterFactory();
+   *  Gson gson = new GsonBuilder().registerTypeAdapterFactory(stats).create();
+   *  // Call gson.toJson() and fromJson methods on objects
+   *  System.out.println("Num JSON reads" + stats.numReads);
+   *  System.out.println("Num JSON writes" + stats.numWrites);
+   *  }</pre>
+   *  Note that this call will skip all factories registered before {@code skipPast}. In case of
+   *  multiple TypeAdapterFactories registered it is up to the caller of this function to insure
+   *  that the order of registration does not prevent this method from reaching a factory they
+   *  would expect to reply from this call.
+   *  Note that since you can not override type adapter factories for String and Java primitive
+   *  types, our stats factory will not count the number of String or primitives that will be
+   *  read or written.
+   * @param skipPast The type adapter factory that needs to be skipped while searching for
+   *   a matching type adapter. In most cases, you should just pass <i>this</i> (the type adapter
+   *   factory from where {@code getDelegateAdapter} method is being invoked).
+   * @param type Type for which the delegate adapter is being searched for.
+   *
+   * @since 2.2
+   */
+  public <T> TypeAdapter<T> getDelegateAdapter(TypeAdapterFactory skipPast, TypeToken<T> type) {
+    // Hack. If the skipPast factory isn't registered, assume the factory is being requested via
+    // our @JsonAdapter annotation.
+    if (!factories.contains(skipPast)) {
+      skipPast = jsonAdapterFactory;
+    }
+
+    boolean skipPastFound = false;
+    for (TypeAdapterFactory factory : factories) {
+      if (!skipPastFound) {
+        if (factory == skipPast) {
+          skipPastFound = true;
+        }
+        continue;
+      }
+
+      TypeAdapter<T> candidate = factory.create(this, type);
+      if (candidate != null) {
+        return candidate;
+      }
+    }
+    throw new IllegalArgumentException("GSON cannot serialize " + type);
+  }
+
+  /**
+   * Returns the type adapter for {@code} type.
+   *
+   * @throws IllegalArgumentException if this GSON cannot serialize and
+   *     deserialize {@code type}.
+   */
+  public <T> TypeAdapter<T> getAdapter(Class<T> type) {
+    return getAdapter(TypeToken.get(type));
+  }
+
+  /**
+   * This method serializes the specified object into its equivalent representation as a tree of
+   * {@link JsonElement}s. This method should be used when the specified object is not a generic
+   * type. This method uses {@link Class#getClass()} to get the type for the specified object, but
+   * the {@code getClass()} loses the generic type information because of the Type Erasure feature
+   * of Java. Note that this method works fine if the any of the object fields are of generic type,
+   * just the object itself should not be of a generic type. If the object is of generic type, use
+   * {@link #toJsonTree(Object, Type)} instead.
+   *
+   * @param src the object for which Json representation is to be created setting for Gson
+   * @return Json representation of {@code src}.
+   * @since 1.4
+   */
+  public JsonElement toJsonTree(Object src) {
+    if (src == null) {
+      return JsonNull.INSTANCE;
+    }
+    return toJsonTree(src, src.getClass());
+  }
+
+  /**
+   * This method serializes the specified object, including those of generic types, into its
+   * equivalent representation as a tree of {@link JsonElement}s. This method must be used if the
+   * specified object is a generic type. For non-generic objects, use {@link #toJsonTree(Object)}
+   * instead.
+   *
+   * @param src the object for which JSON representation is to be created
+   * @param typeOfSrc The specific genericized type of src. You can obtain
+   * this type by using the {@link com.google.gson.reflect.TypeToken} class. For example,
+   * to get the type for {@code Collection<Foo>}, you should use:
+   * <pre>
+   * Type typeOfSrc = new TypeToken&lt;Collection&lt;Foo&gt;&gt;(){}.getType();
+   * </pre>
+   * @return Json representation of {@code src}
+   * @since 1.4
+   */
+  public JsonElement toJsonTree(Object src, Type typeOfSrc) {
+    JsonTreeWriter writer = new JsonTreeWriter();
+    toJson(src, typeOfSrc, writer);
+    return writer.get();
+  }
+
+  /**
+   * This method serializes the specified object into its equivalent Json representation.
+   * This method should be used when the specified object is not a generic type. This method uses
+   * {@link Class#getClass()} to get the type for the specified object, but the
+   * {@code getClass()} loses the generic type information because of the Type Erasure feature
+   * of Java. Note that this method works fine if the any of the object fields are of generic type,
+   * just the object itself should not be of a generic type. If the object is of generic type, use
+   * {@link #toJson(Object, Type)} instead. If you want to write out the object to a
+   * {@link Writer}, use {@link #toJson(Object, Appendable)} instead.
+   *
+   * @param src the object for which Json representation is to be created setting for Gson
+   * @return Json representation of {@code src}.
+   */
+  public String toJson(Object src) {
+    if (src == null) {
+      return toJson(JsonNull.INSTANCE);
+    }
+    return toJson(src, src.getClass());
+  }
+
+  /**
+   * This method serializes the specified object, including those of generic types, into its
+   * equivalent Json representation. This method must be used if the specified object is a generic
+   * type. For non-generic objects, use {@link #toJson(Object)} instead. If you want to write out
+   * the object to a {@link Appendable}, use {@link #toJson(Object, Type, Appendable)} instead.
+   *
+   * @param src the object for which JSON representation is to be created
+   * @param typeOfSrc The specific genericized type of src. You can obtain
+   * this type by using the {@link com.google.gson.reflect.TypeToken} class. For example,
+   * to get the type for {@code Collection<Foo>}, you should use:
+   * <pre>
+   * Type typeOfSrc = new TypeToken&lt;Collection&lt;Foo&gt;&gt;(){}.getType();
+   * </pre>
+   * @return Json representation of {@code src}
+   */
+  public String toJson(Object src, Type typeOfSrc) {
+    StringWriter writer = new StringWriter();
+    toJson(src, typeOfSrc, writer);
+    return writer.toString();
+  }
+
+  /**
+   * This method serializes the specified object into its equivalent Json representation.
+   * This method should be used when the specified object is not a generic type. This method uses
+   * {@link Class#getClass()} to get the type for the specified object, but the
+   * {@code getClass()} loses the generic type information because of the Type Erasure feature
+   * of Java. Note that this method works fine if the any of the object fields are of generic type,
+   * just the object itself should not be of a generic type. If the object is of generic type, use
+   * {@link #toJson(Object, Type, Appendable)} instead.
+   *
+   * @param src the object for which Json representation is to be created setting for Gson
+   * @param writer Writer to which the Json representation needs to be written
+   * @throws JsonIOException if there was a problem writing to the writer
+   * @since 1.2
+   */
+  public void toJson(Object src, Appendable writer) throws JsonIOException {
+    if (src != null) {
+      toJson(src, src.getClass(), writer);
+    } else {
+      toJson(JsonNull.INSTANCE, writer);
+    }
+  }
+
+  /**
+   * This method serializes the specified object, including those of generic types, into its
+   * equivalent Json representation. This method must be used if the specified object is a generic
+   * type. For non-generic objects, use {@link #toJson(Object, Appendable)} instead.
+   *
+   * @param src the object for which JSON representation is to be created
+   * @param typeOfSrc The specific genericized type of src. You can obtain
+   * this type by using the {@link com.google.gson.reflect.TypeToken} class. For example,
+   * to get the type for {@code Collection<Foo>}, you should use:
+   * <pre>
+   * Type typeOfSrc = new TypeToken&lt;Collection&lt;Foo&gt;&gt;(){}.getType();
+   * </pre>
+   * @param writer Writer to which the Json representation of src needs to be written.
+   * @throws JsonIOException if there was a problem writing to the writer
+   * @since 1.2
+   */
+  public void toJson(Object src, Type typeOfSrc, Appendable writer) throws JsonIOException {
+    try {
+      JsonWriter jsonWriter = newJsonWriter(Streams.writerForAppendable(writer));
+      toJson(src, typeOfSrc, jsonWriter);
+    } catch (IOException e) {
+      throw new JsonIOException(e);
+    }
+  }
+
+  /**
+   * Writes the JSON representation of {@code src} of type {@code typeOfSrc} to
+   * {@code writer}.
+   *
+   * <p>The JSON data is written in {@linkplain JsonWriter#setLenient(boolean) lenient mode},
+   * regardless of the lenient mode setting of the provided writer. The lenient mode setting
+   * of the writer is restored once this method returns.
+   *
+   * <p>The 'HTML-safe' and 'serialize {@code null}' settings of this {@code Gson} instance
+   * (configured by the {@link GsonBuilder}) are applied, and the original settings of the
+   * writer are restored once this method returns.
+   *
+   * @throws JsonIOException if there was a problem writing to the writer
+   */
+  @SuppressWarnings("unchecked")
+  public void toJson(Object src, Type typeOfSrc, JsonWriter writer) throws JsonIOException {
+    TypeAdapter<?> adapter = getAdapter(TypeToken.get(typeOfSrc));
+    boolean oldLenient = writer.isLenient();
+    writer.setLenient(true);
+    boolean oldHtmlSafe = writer.isHtmlSafe();
+    writer.setHtmlSafe(htmlSafe);
+    boolean oldSerializeNulls = writer.getSerializeNulls();
+    writer.setSerializeNulls(serializeNulls);
+    try {
+      ((TypeAdapter<Object>) adapter).write(writer, src);
+    } catch (IOException e) {
+      throw new JsonIOException(e);
+    } catch (AssertionError e) {
+      AssertionError error = new AssertionError("AssertionError (GSON " + GsonBuildConfig.VERSION + "): " + e.getMessage());
+      error.initCause(e);
+      throw error;
+    } finally {
+      writer.setLenient(oldLenient);
+      writer.setHtmlSafe(oldHtmlSafe);
+      writer.setSerializeNulls(oldSerializeNulls);
+    }
+  }
+
+  /**
+   * Converts a tree of {@link JsonElement}s into its equivalent JSON representation.
+   *
+   * @param jsonElement root of a tree of {@link JsonElement}s
+   * @return JSON String representation of the tree
+   * @since 1.4
+   */
+  public String toJson(JsonElement jsonElement) {
+    StringWriter writer = new StringWriter();
+    toJson(jsonElement, writer);
+    return writer.toString();
+  }
+
+  /**
+   * Writes out the equivalent JSON for a tree of {@link JsonElement}s.
+   *
+   * @param jsonElement root of a tree of {@link JsonElement}s
+   * @param writer Writer to which the Json representation needs to be written
+   * @throws JsonIOException if there was a problem writing to the writer
+   * @since 1.4
+   */
+  public void toJson(JsonElement jsonElement, Appendable writer) throws JsonIOException {
+    try {
+      JsonWriter jsonWriter = newJsonWriter(Streams.writerForAppendable(writer));
+      toJson(jsonElement, jsonWriter);
+    } catch (IOException e) {
+      throw new JsonIOException(e);
+    }
+  }
+
+  /**
+   * Returns a new JSON writer configured for the settings on this Gson instance.
+   *
+   * <p>The following settings are considered:
+   * <ul>
+   *   <li>{@link GsonBuilder#disableHtmlEscaping()}</li>
+   *   <li>{@link GsonBuilder#generateNonExecutableJson()}</li>
+   *   <li>{@link GsonBuilder#serializeNulls()}</li>
+   *   <li>{@link GsonBuilder#setLenient()}</li>
+   *   <li>{@link GsonBuilder#setPrettyPrinting()}</li>
+   * </ul>
+   */
+  public JsonWriter newJsonWriter(Writer writer) throws IOException {
+    if (generateNonExecutableJson) {
+      writer.write(JSON_NON_EXECUTABLE_PREFIX);
+    }
+    JsonWriter jsonWriter = new JsonWriter(writer);
+    if (prettyPrinting) {
+      jsonWriter.setIndent("  ");
+    }
+    jsonWriter.setHtmlSafe(htmlSafe);
+    jsonWriter.setLenient(lenient);
+    jsonWriter.setSerializeNulls(serializeNulls);
+    return jsonWriter;
+  }
+
+  /**
+   * Returns a new JSON reader configured for the settings on this Gson instance.
+   *
+   * <p>The following settings are considered:
+   * <ul>
+   *   <li>{@link GsonBuilder#setLenient()}</li>
+   * </ul>
+   */
+  public JsonReader newJsonReader(Reader reader) {
+    JsonReader jsonReader = new JsonReader(reader);
+    jsonReader.setLenient(lenient);
+    return jsonReader;
+  }
+
+  /**
+   * Writes the JSON for {@code jsonElement} to {@code writer}.
+   *
+   * <p>The JSON data is written in {@linkplain JsonWriter#setLenient(boolean) lenient mode},
+   * regardless of the lenient mode setting of the provided writer. The lenient mode setting
+   * of the writer is restored once this method returns.
+   *
+   * <p>The 'HTML-safe' and 'serialize {@code null}' settings of this {@code Gson} instance
+   * (configured by the {@link GsonBuilder}) are applied, and the original settings of the
+   * writer are restored once this method returns.
+   *
+   * @throws JsonIOException if there was a problem writing to the writer
+   */
+  public void toJson(JsonElement jsonElement, JsonWriter writer) throws JsonIOException {
+    boolean oldLenient = writer.isLenient();
+    writer.setLenient(true);
+    boolean oldHtmlSafe = writer.isHtmlSafe();
+    writer.setHtmlSafe(htmlSafe);
+    boolean oldSerializeNulls = writer.getSerializeNulls();
+    writer.setSerializeNulls(serializeNulls);
+    try {
+      Streams.write(jsonElement, writer);
+    } catch (IOException e) {
+      throw new JsonIOException(e);
+    } catch (AssertionError e) {
+      AssertionError error = new AssertionError("AssertionError (GSON " + GsonBuildConfig.VERSION + "): " + e.getMessage());
+      error.initCause(e);
+      throw error;
+    } finally {
+      writer.setLenient(oldLenient);
+      writer.setHtmlSafe(oldHtmlSafe);
+      writer.setSerializeNulls(oldSerializeNulls);
+    }
+  }
+
+  /**
+   * This method deserializes the specified Json into an object of the specified class. It is not
+   * suitable to use if the specified class is a generic type since it will not have the generic
+   * type information because of the Type Erasure feature of Java. Therefore, this method should not
+   * be used if the desired type is a generic type. Note that this method works fine if the any of
+   * the fields of the specified object are generics, just the object itself should not be a
+   * generic type. For the cases when the object is of generic type, invoke
+   * {@link #fromJson(String, Type)}. If you have the Json in a {@link Reader} instead of
+   * a String, use {@link #fromJson(Reader, Class)} instead.
+   *
+   * <p>An exception is thrown if the JSON string has multiple top-level JSON elements,
+   * or if there is trailing data.
+   *
+   * @param <T> the type of the desired object
+   * @param json the string from which the object is to be deserialized
+   * @param classOfT the class of T
+   * @return an object of type T from the string. Returns {@code null} if {@code json} is {@code null}
+   * or if {@code json} is empty.
+   * @throws JsonSyntaxException if json is not a valid representation for an object of type
+   * classOfT
+   */
+  public <T> T fromJson(String json, Class<T> classOfT) throws JsonSyntaxException {
+    Object object = fromJson(json, (Type) classOfT);
+    return Primitives.wrap(classOfT).cast(object);
+  }
+
+  /**
+   * This method deserializes the specified Json into an object of the specified type. This method
+   * is useful if the specified object is a generic type. For non-generic objects, use
+   * {@link #fromJson(String, Class)} instead. If you have the Json in a {@link Reader} instead of
+   * a String, use {@link #fromJson(Reader, Type)} instead.
+   *
+   * <p>An exception is thrown if the JSON string has multiple top-level JSON elements,
+   * or if there is trailing data.
+   *
+   * @param <T> the type of the desired object
+   * @param json the string from which the object is to be deserialized
+   * @param typeOfT The specific genericized type of src. You can obtain this type by using the
+   * {@link com.google.gson.reflect.TypeToken} class. For example, to get the type for
+   * {@code Collection<Foo>}, you should use:
+   * <pre>
+   * Type typeOfT = new TypeToken&lt;Collection&lt;Foo&gt;&gt;(){}.getType();
+   * </pre>
+   * @return an object of type T from the string. Returns {@code null} if {@code json} is {@code null}
+   * or if {@code json} is empty.
+   * @throws JsonParseException if json is not a valid representation for an object of type typeOfT
+   * @throws JsonSyntaxException if json is not a valid representation for an object of type
+   */
+  @SuppressWarnings("unchecked")
+  public <T> T fromJson(String json, Type typeOfT) throws JsonSyntaxException {
+    if (json == null) {
+      return null;
+    }
+    StringReader reader = new StringReader(json);
+    T target = (T) fromJson(reader, typeOfT);
+    return target;
+  }
+
+  /**
+   * This method deserializes the Json read from the specified reader into an object of the
+   * specified class. It is not suitable to use if the specified class is a generic type since it
+   * will not have the generic type information because of the Type Erasure feature of Java.
+   * Therefore, this method should not be used if the desired type is a generic type. Note that
+   * this method works fine if the any of the fields of the specified object are generics, just the
+   * object itself should not be a generic type. For the cases when the object is of generic type,
+   * invoke {@link #fromJson(Reader, Type)}. If you have the Json in a String form instead of a
+   * {@link Reader}, use {@link #fromJson(String, Class)} instead.
+   *
+   * <p>An exception is thrown if the JSON data has multiple top-level JSON elements,
+   * or if there is trailing data.
+   *
+   * @param <T> the type of the desired object
+   * @param json the reader producing the Json from which the object is to be deserialized.
+   * @param classOfT the class of T
+   * @return an object of type T from the string. Returns {@code null} if {@code json} is at EOF.
+   * @throws JsonIOException if there was a problem reading from the Reader
+   * @throws JsonSyntaxException if json is not a valid representation for an object of type
+   * @since 1.2
+   */
+  public <T> T fromJson(Reader json, Class<T> classOfT) throws JsonSyntaxException, JsonIOException {
+    JsonReader jsonReader = newJsonReader(json);
+    Object object = fromJson(jsonReader, classOfT);
+    assertFullConsumption(object, jsonReader);
+    return Primitives.wrap(classOfT).cast(object);
+  }
+
+  /**
+   * This method deserializes the Json read from the specified reader into an object of the
+   * specified type. This method is useful if the specified object is a generic type. For
+   * non-generic objects, use {@link #fromJson(Reader, Class)} instead. If you have the Json in a
+   * String form instead of a {@link Reader}, use {@link #fromJson(String, Type)} instead.
+   *
+   * <p>An exception is thrown if the JSON data has multiple top-level JSON elements,
+   * or if there is trailing data.
+   *
+   * @param <T> the type of the desired object
+   * @param json the reader producing Json from which the object is to be deserialized
+   * @param typeOfT The specific genericized type of src. You can obtain this type by using the
+   * {@link com.google.gson.reflect.TypeToken} class. For example, to get the type for
+   * {@code Collection<Foo>}, you should use:
+   * <pre>
+   * Type typeOfT = new TypeToken&lt;Collection&lt;Foo&gt;&gt;(){}.getType();
+   * </pre>
+   * @return an object of type T from the json. Returns {@code null} if {@code json} is at EOF.
+   * @throws JsonIOException if there was a problem reading from the Reader
+   * @throws JsonSyntaxException if json is not a valid representation for an object of type
+   * @since 1.2
+   */
+  @SuppressWarnings("unchecked")
+  public <T> T fromJson(Reader json, Type typeOfT) throws JsonIOException, JsonSyntaxException {
+    JsonReader jsonReader = newJsonReader(json);
+    T object = (T) fromJson(jsonReader, typeOfT);
+    assertFullConsumption(object, jsonReader);
+    return object;
+  }
+
+  private static void assertFullConsumption(Object obj, JsonReader reader) {
+    try {
+      if (obj != null && reader.peek() != JsonToken.END_DOCUMENT) {
+        throw new JsonSyntaxException("JSON document was not fully consumed.");
+      }
+    } catch (MalformedJsonException e) {
+      throw new JsonSyntaxException(e);
+    } catch (IOException e) {
+      throw new JsonIOException(e);
+    }
+  }
+
+  /**
+   * Reads the next JSON value from {@code reader} and convert it to an object
+   * of type {@code typeOfT}. Returns {@code null}, if the {@code reader} is at EOF.
+   * Since Type is not parameterized by T, this method is type unsafe and should be used carefully.
+   *
+   * <p>Unlike the other {@code fromJson} methods, no exception is thrown if the JSON data has
+   * multiple top-level JSON elements, or if there is trailing data.
+   *
+   * <p>The JSON data is parsed in {@linkplain JsonReader#setLenient(boolean) lenient mode},
+   * regardless of the lenient mode setting of the provided reader. The lenient mode setting
+   * of the reader is restored once this method returns.
+   *
+   * @throws JsonIOException if there was a problem writing to the Reader
+   * @throws JsonSyntaxException if json is not a valid representation for an object of type
+   */
+  @SuppressWarnings("unchecked")
+  public <T> T fromJson(JsonReader reader, Type typeOfT) throws JsonIOException, JsonSyntaxException {
+    boolean isEmpty = true;
+    boolean oldLenient = reader.isLenient();
+    reader.setLenient(true);
+    try {
+      reader.peek();
+      isEmpty = false;
+      TypeToken<T> typeToken = (TypeToken<T>) TypeToken.get(typeOfT);
+      TypeAdapter<T> typeAdapter = getAdapter(typeToken);
+      T object = typeAdapter.read(reader);
+      return object;
+    } catch (EOFException e) {
+      /*
+       * For compatibility with JSON 1.5 and earlier, we return null for empty
+       * documents instead of throwing.
+       */
+      if (isEmpty) {
+        return null;
+      }
+      throw new JsonSyntaxException(e);
+    } catch (IllegalStateException e) {
+      throw new JsonSyntaxException(e);
+    } catch (IOException e) {
+      // TODO(inder): Figure out whether it is indeed right to rethrow this as JsonSyntaxException
+      throw new JsonSyntaxException(e);
+    } catch (AssertionError e) {
+      AssertionError error = new AssertionError("AssertionError (GSON " + GsonBuildConfig.VERSION + "): " + e.getMessage());
+      error.initCause(e);
+      throw error;
+    } finally {
+      reader.setLenient(oldLenient);
+    }
+  }
+
+  /**
+   * This method deserializes the Json read from the specified parse tree into an object of the
+   * specified type. It is not suitable to use if the specified class is a generic type since it
+   * will not have the generic type information because of the Type Erasure feature of Java.
+   * Therefore, this method should not be used if the desired type is a generic type. Note that
+   * this method works fine if the any of the fields of the specified object are generics, just the
+   * object itself should not be a generic type. For the cases when the object is of generic type,
+   * invoke {@link #fromJson(JsonElement, Type)}.
+   * @param <T> the type of the desired object
+   * @param json the root of the parse tree of {@link JsonElement}s from which the object is to
+   * be deserialized
+   * @param classOfT The class of T
+   * @return an object of type T from the json. Returns {@code null} if {@code json} is {@code null}
+   * or if {@code json} is empty.
+   * @throws JsonSyntaxException if json is not a valid representation for an object of type typeOfT
+   * @since 1.3
+   */
+  public <T> T fromJson(JsonElement json, Class<T> classOfT) throws JsonSyntaxException {
+    Object object = fromJson(json, (Type) classOfT);
+    return Primitives.wrap(classOfT).cast(object);
+  }
+
+  /**
+   * This method deserializes the Json read from the specified parse tree into an object of the
+   * specified type. This method is useful if the specified object is a generic type. For
+   * non-generic objects, use {@link #fromJson(JsonElement, Class)} instead.
+   *
+   * @param <T> the type of the desired object
+   * @param json the root of the parse tree of {@link JsonElement}s from which the object is to
+   * be deserialized
+   * @param typeOfT The specific genericized type of src. You can obtain this type by using the
+   * {@link com.google.gson.reflect.TypeToken} class. For example, to get the type for
+   * {@code Collection<Foo>}, you should use:
+   * <pre>
+   * Type typeOfT = new TypeToken&lt;Collection&lt;Foo&gt;&gt;(){}.getType();
+   * </pre>
+   * @return an object of type T from the json. Returns {@code null} if {@code json} is {@code null}
+   * or if {@code json} is empty.
+   * @throws JsonSyntaxException if json is not a valid representation for an object of type typeOfT
+   * @since 1.3
+   */
+  @SuppressWarnings("unchecked")
+  public <T> T fromJson(JsonElement json, Type typeOfT) throws JsonSyntaxException {
+    if (json == null) {
+      return null;
+    }
+    return (T) fromJson(new JsonTreeReader(json), typeOfT);
+  }
+
+  static class FutureTypeAdapter<T> extends TypeAdapter<T> {
+    private TypeAdapter<T> delegate;
+
+    public void setDelegate(TypeAdapter<T> typeAdapter) {
+      if (delegate != null) {
+        throw new AssertionError();
+      }
+      delegate = typeAdapter;
+    }
+
+    @Override public T read(JsonReader in) throws IOException {
+      if (delegate == null) {
+        throw new IllegalStateException();
+      }
+      return delegate.read(in);
+    }
+
+    @Override public void write(JsonWriter out, T value) throws IOException {
+      if (delegate == null) {
+        throw new IllegalStateException();
+      }
+      delegate.write(out, value);
+    }
+  }
+
+  @Override
+  public String toString() {
+    return new StringBuilder("{serializeNulls:")
+        .append(serializeNulls)
+        .append(",factories:").append(factories)
+        .append(",instanceCreators:").append(constructorConstructor)
+        .append("}")
+        .toString();
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/GsonBuilder.java b/gson/src/main/java/com/google/gson/GsonBuilder.java
new file mode 100644
index 0000000..4c540ac
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/GsonBuilder.java
@@ -0,0 +1,719 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import java.lang.reflect.Type;
+import java.text.DateFormat;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+import com.google.gson.internal.$Gson$Preconditions;
+import com.google.gson.internal.Excluder;
+import com.google.gson.internal.bind.DefaultDateTypeAdapter;
+import com.google.gson.internal.bind.TreeTypeAdapter;
+import com.google.gson.internal.bind.TypeAdapters;
+import com.google.gson.internal.sql.SqlTypesSupport;
+import com.google.gson.reflect.TypeToken;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonWriter;
+
+import static com.google.gson.Gson.DEFAULT_COMPLEX_MAP_KEYS;
+import static com.google.gson.Gson.DEFAULT_DATE_PATTERN;
+import static com.google.gson.Gson.DEFAULT_ESCAPE_HTML;
+import static com.google.gson.Gson.DEFAULT_JSON_NON_EXECUTABLE;
+import static com.google.gson.Gson.DEFAULT_LENIENT;
+import static com.google.gson.Gson.DEFAULT_NUMBER_TO_NUMBER_STRATEGY;
+import static com.google.gson.Gson.DEFAULT_OBJECT_TO_NUMBER_STRATEGY;
+import static com.google.gson.Gson.DEFAULT_PRETTY_PRINT;
+import static com.google.gson.Gson.DEFAULT_SERIALIZE_NULLS;
+import static com.google.gson.Gson.DEFAULT_SPECIALIZE_FLOAT_VALUES;
+import static com.google.gson.Gson.DEFAULT_USE_JDK_UNSAFE;
+
+/**
+ * <p>Use this builder to construct a {@link Gson} instance when you need to set configuration
+ * options other than the default. For {@link Gson} with default configuration, it is simpler to
+ * use {@code new Gson()}. {@code GsonBuilder} is best used by creating it, and then invoking its
+ * various configuration methods, and finally calling create.</p>
+ *
+ * <p>The following is an example shows how to use the {@code GsonBuilder} to construct a Gson
+ * instance:
+ *
+ * <pre>
+ * Gson gson = new GsonBuilder()
+ *     .registerTypeAdapter(Id.class, new IdTypeAdapter())
+ *     .enableComplexMapKeySerialization()
+ *     .serializeNulls()
+ *     .setDateFormat(DateFormat.LONG)
+ *     .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
+ *     .setPrettyPrinting()
+ *     .setVersion(1.0)
+ *     .create();
+ * </pre>
+ *
+ * <p>NOTES:
+ * <ul>
+ * <li> the order of invocation of configuration methods does not matter.</li>
+ * <li> The default serialization of {@link Date} and its subclasses in Gson does
+ *  not contain time-zone information. So, if you are using date/time instances,
+ *  use {@code GsonBuilder} and its {@code setDateFormat} methods.</li>
+ * </ul>
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ * @author Jesse Wilson
+ */
+public final class GsonBuilder {
+  private Excluder excluder = Excluder.DEFAULT;
+  private LongSerializationPolicy longSerializationPolicy = LongSerializationPolicy.DEFAULT;
+  private FieldNamingStrategy fieldNamingPolicy = FieldNamingPolicy.IDENTITY;
+  private final Map<Type, InstanceCreator<?>> instanceCreators = new HashMap<>();
+  private final List<TypeAdapterFactory> factories = new ArrayList<>();
+  /** tree-style hierarchy factories. These come after factories for backwards compatibility. */
+  private final List<TypeAdapterFactory> hierarchyFactories = new ArrayList<>();
+  private boolean serializeNulls = DEFAULT_SERIALIZE_NULLS;
+  private String datePattern = DEFAULT_DATE_PATTERN;
+  private int dateStyle = DateFormat.DEFAULT;
+  private int timeStyle = DateFormat.DEFAULT;
+  private boolean complexMapKeySerialization = DEFAULT_COMPLEX_MAP_KEYS;
+  private boolean serializeSpecialFloatingPointValues = DEFAULT_SPECIALIZE_FLOAT_VALUES;
+  private boolean escapeHtmlChars = DEFAULT_ESCAPE_HTML;
+  private boolean prettyPrinting = DEFAULT_PRETTY_PRINT;
+  private boolean generateNonExecutableJson = DEFAULT_JSON_NON_EXECUTABLE;
+  private boolean lenient = DEFAULT_LENIENT;
+  private boolean useJdkUnsafe = DEFAULT_USE_JDK_UNSAFE;
+  private ToNumberStrategy objectToNumberStrategy = DEFAULT_OBJECT_TO_NUMBER_STRATEGY;
+  private ToNumberStrategy numberToNumberStrategy = DEFAULT_NUMBER_TO_NUMBER_STRATEGY;
+  private final LinkedList<ReflectionAccessFilter> reflectionFilters = new LinkedList<>();
+
+  /**
+   * Creates a GsonBuilder instance that can be used to build Gson with various configuration
+   * settings. GsonBuilder follows the builder pattern, and it is typically used by first
+   * invoking various configuration methods to set desired options, and finally calling
+   * {@link #create()}.
+   */
+  public GsonBuilder() {
+  }
+
+  /**
+   * Constructs a GsonBuilder instance from a Gson instance. The newly constructed GsonBuilder
+   * has the same configuration as the previously built Gson instance.
+   *
+   * @param gson the gson instance whose configuration should by applied to a new GsonBuilder.
+   */
+  GsonBuilder(Gson gson) {
+    this.excluder = gson.excluder;
+    this.fieldNamingPolicy = gson.fieldNamingStrategy;
+    this.instanceCreators.putAll(gson.instanceCreators);
+    this.serializeNulls = gson.serializeNulls;
+    this.complexMapKeySerialization = gson.complexMapKeySerialization;
+    this.generateNonExecutableJson = gson.generateNonExecutableJson;
+    this.escapeHtmlChars = gson.htmlSafe;
+    this.prettyPrinting = gson.prettyPrinting;
+    this.lenient = gson.lenient;
+    this.serializeSpecialFloatingPointValues = gson.serializeSpecialFloatingPointValues;
+    this.longSerializationPolicy = gson.longSerializationPolicy;
+    this.datePattern = gson.datePattern;
+    this.dateStyle = gson.dateStyle;
+    this.timeStyle = gson.timeStyle;
+    this.factories.addAll(gson.builderFactories);
+    this.hierarchyFactories.addAll(gson.builderHierarchyFactories);
+    this.useJdkUnsafe = gson.useJdkUnsafe;
+    this.objectToNumberStrategy = gson.objectToNumberStrategy;
+    this.numberToNumberStrategy = gson.numberToNumberStrategy;
+    this.reflectionFilters.addAll(gson.reflectionFilters);
+  }
+
+  /**
+   * Configures Gson to enable versioning support.
+   *
+   * @param ignoreVersionsAfter any field or type marked with a version higher than this value
+   * are ignored during serialization or deserialization.
+   * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
+   */
+  public GsonBuilder setVersion(double ignoreVersionsAfter) {
+    excluder = excluder.withVersion(ignoreVersionsAfter);
+    return this;
+  }
+
+  /**
+   * Configures Gson to excludes all class fields that have the specified modifiers. By default,
+   * Gson will exclude all fields marked transient or static. This method will override that
+   * behavior.
+   *
+   * @param modifiers the field modifiers. You must use the modifiers specified in the
+   * {@link java.lang.reflect.Modifier} class. For example,
+   * {@link java.lang.reflect.Modifier#TRANSIENT},
+   * {@link java.lang.reflect.Modifier#STATIC}.
+   * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
+   */
+  public GsonBuilder excludeFieldsWithModifiers(int... modifiers) {
+    excluder = excluder.withModifiers(modifiers);
+    return this;
+  }
+
+  /**
+   * Makes the output JSON non-executable in Javascript by prefixing the generated JSON with some
+   * special text. This prevents attacks from third-party sites through script sourcing. See
+   * <a href="http://code.google.com/p/google-gson/issues/detail?id=42">Gson Issue 42</a>
+   * for details.
+   *
+   * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
+   * @since 1.3
+   */
+  public GsonBuilder generateNonExecutableJson() {
+    this.generateNonExecutableJson = true;
+    return this;
+  }
+
+  /**
+   * Configures Gson to exclude all fields from consideration for serialization or deserialization
+   * that do not have the {@link com.google.gson.annotations.Expose} annotation.
+   *
+   * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
+   */
+  public GsonBuilder excludeFieldsWithoutExposeAnnotation() {
+    excluder = excluder.excludeFieldsWithoutExposeAnnotation();
+    return this;
+  }
+
+  /**
+   * Configure Gson to serialize null fields. By default, Gson omits all fields that are null
+   * during serialization.
+   *
+   * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
+   * @since 1.2
+   */
+  public GsonBuilder serializeNulls() {
+    this.serializeNulls = true;
+    return this;
+  }
+
+  /**
+   * Enabling this feature will only change the serialized form if the map key is
+   * a complex type (i.e. non-primitive) in its <strong>serialized</strong> JSON
+   * form. The default implementation of map serialization uses {@code toString()}
+   * on the key; however, when this is called then one of the following cases
+   * apply:
+   *
+   * <h3>Maps as JSON objects</h3>
+   * For this case, assume that a type adapter is registered to serialize and
+   * deserialize some {@code Point} class, which contains an x and y coordinate,
+   * to/from the JSON Primitive string value {@code "(x,y)"}. The Java map would
+   * then be serialized as a {@link JsonObject}.
+   *
+   * <p>Below is an example:
+   * <pre>  {@code
+   *   Gson gson = new GsonBuilder()
+   *       .register(Point.class, new MyPointTypeAdapter())
+   *       .enableComplexMapKeySerialization()
+   *       .create();
+   *
+   *   Map<Point, String> original = new LinkedHashMap<>();
+   *   original.put(new Point(5, 6), "a");
+   *   original.put(new Point(8, 8), "b");
+   *   System.out.println(gson.toJson(original, type));
+   * }</pre>
+   * The above code prints this JSON object:<pre>  {@code
+   *   {
+   *     "(5,6)": "a",
+   *     "(8,8)": "b"
+   *   }
+   * }</pre>
+   *
+   * <h3>Maps as JSON arrays</h3>
+   * For this case, assume that a type adapter was NOT registered for some
+   * {@code Point} class, but rather the default Gson serialization is applied.
+   * In this case, some {@code new Point(2,3)} would serialize as {@code
+   * {"x":2,"y":5}}.
+   *
+   * <p>Given the assumption above, a {@code Map<Point, String>} will be
+   * serialize as an array of arrays (can be viewed as an entry set of pairs).
+   *
+   * <p>Below is an example of serializing complex types as JSON arrays:
+   * <pre> {@code
+   *   Gson gson = new GsonBuilder()
+   *       .enableComplexMapKeySerialization()
+   *       .create();
+   *
+   *   Map<Point, String> original = new LinkedHashMap<>();
+   *   original.put(new Point(5, 6), "a");
+   *   original.put(new Point(8, 8), "b");
+   *   System.out.println(gson.toJson(original, type));
+   * }
+   * </pre>
+   *
+   * The JSON output would look as follows:
+   * <pre>   {@code
+   *   [
+   *     [
+   *       {
+   *         "x": 5,
+   *         "y": 6
+   *       },
+   *       "a"
+   *     ],
+   *     [
+   *       {
+   *         "x": 8,
+   *         "y": 8
+   *       },
+   *       "b"
+   *     ]
+   *   ]
+   * }</pre>
+   *
+   * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
+   * @since 1.7
+   */
+  public GsonBuilder enableComplexMapKeySerialization() {
+    complexMapKeySerialization = true;
+    return this;
+  }
+
+  /**
+   * Configures Gson to exclude inner classes during serialization.
+   *
+   * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
+   * @since 1.3
+   */
+  public GsonBuilder disableInnerClassSerialization() {
+    excluder = excluder.disableInnerClassSerialization();
+    return this;
+  }
+
+  /**
+   * Configures Gson to apply a specific serialization policy for {@code Long} and {@code long}
+   * objects.
+   *
+   * @param serializationPolicy the particular policy to use for serializing longs.
+   * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
+   * @since 1.3
+   */
+  public GsonBuilder setLongSerializationPolicy(LongSerializationPolicy serializationPolicy) {
+    this.longSerializationPolicy = serializationPolicy;
+    return this;
+  }
+
+  /**
+   * Configures Gson to apply a specific naming policy to an object's field during serialization
+   * and deserialization.
+   *
+   * @param namingConvention the JSON field naming convention to use for serialization and
+   * deserialization.
+   * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
+   */
+  public GsonBuilder setFieldNamingPolicy(FieldNamingPolicy namingConvention) {
+    this.fieldNamingPolicy = namingConvention;
+    return this;
+  }
+
+  /**
+   * Configures Gson to apply a specific naming policy strategy to an object's field during
+   * serialization and deserialization.
+   *
+   * @param fieldNamingStrategy the actual naming strategy to apply to the fields
+   * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
+   * @since 1.3
+   */
+  public GsonBuilder setFieldNamingStrategy(FieldNamingStrategy fieldNamingStrategy) {
+    this.fieldNamingPolicy = fieldNamingStrategy;
+    return this;
+  }
+
+  /**
+   * Configures Gson to apply a specific number strategy during deserialization of {@link Object}.
+   *
+   * @param objectToNumberStrategy the actual object-to-number strategy
+   * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
+   * @see ToNumberPolicy#DOUBLE The default object-to-number strategy
+   */
+  public GsonBuilder setObjectToNumberStrategy(ToNumberStrategy objectToNumberStrategy) {
+    this.objectToNumberStrategy = objectToNumberStrategy;
+    return this;
+  }
+
+  /**
+   * Configures Gson to apply a specific number strategy during deserialization of {@link Number}.
+   *
+   * @param numberToNumberStrategy the actual number-to-number strategy
+   * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
+   * @see ToNumberPolicy#LAZILY_PARSED_NUMBER The default number-to-number strategy
+   */
+  public GsonBuilder setNumberToNumberStrategy(ToNumberStrategy numberToNumberStrategy) {
+    this.numberToNumberStrategy = numberToNumberStrategy;
+    return this;
+  }
+
+  /**
+   * Configures Gson to apply a set of exclusion strategies during both serialization and
+   * deserialization. Each of the {@code strategies} will be applied as a disjunction rule.
+   * This means that if one of the {@code strategies} suggests that a field (or class) should be
+   * skipped then that field (or object) is skipped during serialization/deserialization.
+   *
+   * @param strategies the set of strategy object to apply during object (de)serialization.
+   * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
+   * @since 1.4
+   */
+  public GsonBuilder setExclusionStrategies(ExclusionStrategy... strategies) {
+    for (ExclusionStrategy strategy : strategies) {
+      excluder = excluder.withExclusionStrategy(strategy, true, true);
+    }
+    return this;
+  }
+
+  /**
+   * Configures Gson to apply the passed in exclusion strategy during serialization.
+   * If this method is invoked numerous times with different exclusion strategy objects
+   * then the exclusion strategies that were added will be applied as a disjunction rule.
+   * This means that if one of the added exclusion strategies suggests that a field (or
+   * class) should be skipped then that field (or object) is skipped during its
+   * serialization.
+   *
+   * @param strategy an exclusion strategy to apply during serialization.
+   * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
+   * @since 1.7
+   */
+  public GsonBuilder addSerializationExclusionStrategy(ExclusionStrategy strategy) {
+    excluder = excluder.withExclusionStrategy(strategy, true, false);
+    return this;
+  }
+
+  /**
+   * Configures Gson to apply the passed in exclusion strategy during deserialization.
+   * If this method is invoked numerous times with different exclusion strategy objects
+   * then the exclusion strategies that were added will be applied as a disjunction rule.
+   * This means that if one of the added exclusion strategies suggests that a field (or
+   * class) should be skipped then that field (or object) is skipped during its
+   * deserialization.
+   *
+   * @param strategy an exclusion strategy to apply during deserialization.
+   * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
+   * @since 1.7
+   */
+  public GsonBuilder addDeserializationExclusionStrategy(ExclusionStrategy strategy) {
+    excluder = excluder.withExclusionStrategy(strategy, false, true);
+    return this;
+  }
+
+  /**
+   * Configures Gson to output Json that fits in a page for pretty printing. This option only
+   * affects Json serialization.
+   *
+   * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
+   */
+  public GsonBuilder setPrettyPrinting() {
+    prettyPrinting = true;
+    return this;
+  }
+
+  /**
+   * Configures Gson to allow JSON data which does not strictly comply with the JSON specification.
+   *
+   * <p>Note: Due to legacy reasons most methods of Gson are always lenient, regardless of
+   * whether this builder method is used.
+   *
+   * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
+   * @see JsonReader#setLenient(boolean)
+   * @see JsonWriter#setLenient(boolean)
+   */
+  public GsonBuilder setLenient() {
+    lenient = true;
+    return this;
+  }
+
+  /**
+   * By default, Gson escapes HTML characters such as &lt; &gt; etc. Use this option to configure
+   * Gson to pass-through HTML characters as is.
+   *
+   * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
+   * @since 1.3
+   */
+  public GsonBuilder disableHtmlEscaping() {
+    this.escapeHtmlChars = false;
+    return this;
+  }
+
+  /**
+   * Configures Gson to serialize {@code Date} objects according to the pattern provided. You can
+   * call this method or {@link #setDateFormat(int)} multiple times, but only the last invocation
+   * will be used to decide the serialization format.
+   *
+   * <p>The date format will be used to serialize and deserialize {@link java.util.Date} and in case
+   * the {@code java.sql} module is present, also {@link java.sql.Timestamp} and {@link java.sql.Date}.
+   *
+   * <p>Note that this pattern must abide by the convention provided by {@code SimpleDateFormat}
+   * class. See the documentation in {@link java.text.SimpleDateFormat} for more information on
+   * valid date and time patterns.</p>
+   *
+   * @param pattern the pattern that dates will be serialized/deserialized to/from
+   * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
+   * @since 1.2
+   */
+  public GsonBuilder setDateFormat(String pattern) {
+    // TODO(Joel): Make this fail fast if it is an invalid date format
+    this.datePattern = pattern;
+    return this;
+  }
+
+  /**
+   * Configures Gson to to serialize {@code Date} objects according to the style value provided.
+   * You can call this method or {@link #setDateFormat(String)} multiple times, but only the last
+   * invocation will be used to decide the serialization format.
+   *
+   * <p>Note that this style value should be one of the predefined constants in the
+   * {@code DateFormat} class. See the documentation in {@link java.text.DateFormat} for more
+   * information on the valid style constants.</p>
+   *
+   * @param style the predefined date style that date objects will be serialized/deserialized
+   * to/from
+   * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
+   * @since 1.2
+   */
+  public GsonBuilder setDateFormat(int style) {
+    this.dateStyle = style;
+    this.datePattern = null;
+    return this;
+  }
+
+  /**
+   * Configures Gson to to serialize {@code Date} objects according to the style value provided.
+   * You can call this method or {@link #setDateFormat(String)} multiple times, but only the last
+   * invocation will be used to decide the serialization format.
+   *
+   * <p>Note that this style value should be one of the predefined constants in the
+   * {@code DateFormat} class. See the documentation in {@link java.text.DateFormat} for more
+   * information on the valid style constants.</p>
+   *
+   * @param dateStyle the predefined date style that date objects will be serialized/deserialized
+   * to/from
+   * @param timeStyle the predefined style for the time portion of the date objects
+   * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
+   * @since 1.2
+   */
+  public GsonBuilder setDateFormat(int dateStyle, int timeStyle) {
+    this.dateStyle = dateStyle;
+    this.timeStyle = timeStyle;
+    this.datePattern = null;
+    return this;
+  }
+
+  /**
+   * Configures Gson for custom serialization or deserialization. This method combines the
+   * registration of an {@link TypeAdapter}, {@link InstanceCreator}, {@link JsonSerializer}, and a
+   * {@link JsonDeserializer}. It is best used when a single object {@code typeAdapter} implements
+   * all the required interfaces for custom serialization with Gson. If a type adapter was
+   * previously registered for the specified {@code type}, it is overwritten.
+   *
+   * <p>This registers the type specified and no other types: you must manually register related
+   * types! For example, applications registering {@code boolean.class} should also register {@code
+   * Boolean.class}.
+   *
+   * @param type the type definition for the type adapter being registered
+   * @param typeAdapter This object must implement at least one of the {@link TypeAdapter},
+   * {@link InstanceCreator}, {@link JsonSerializer}, and a {@link JsonDeserializer} interfaces.
+   * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
+   */
+  @SuppressWarnings({"unchecked", "rawtypes"})
+  public GsonBuilder registerTypeAdapter(Type type, Object typeAdapter) {
+    $Gson$Preconditions.checkArgument(typeAdapter instanceof JsonSerializer<?>
+        || typeAdapter instanceof JsonDeserializer<?>
+        || typeAdapter instanceof InstanceCreator<?>
+        || typeAdapter instanceof TypeAdapter<?>);
+    if (typeAdapter instanceof InstanceCreator<?>) {
+      instanceCreators.put(type, (InstanceCreator) typeAdapter);
+    }
+    if (typeAdapter instanceof JsonSerializer<?> || typeAdapter instanceof JsonDeserializer<?>) {
+      TypeToken<?> typeToken = TypeToken.get(type);
+      factories.add(TreeTypeAdapter.newFactoryWithMatchRawType(typeToken, typeAdapter));
+    }
+    if (typeAdapter instanceof TypeAdapter<?>) {
+      factories.add(TypeAdapters.newFactory(TypeToken.get(type), (TypeAdapter)typeAdapter));
+    }
+    return this;
+  }
+
+  /**
+   * Register a factory for type adapters. Registering a factory is useful when the type
+   * adapter needs to be configured based on the type of the field being processed. Gson
+   * is designed to handle a large number of factories, so you should consider registering
+   * them to be at par with registering an individual type adapter.
+   *
+   * @since 2.1
+   */
+  public GsonBuilder registerTypeAdapterFactory(TypeAdapterFactory factory) {
+    factories.add(factory);
+    return this;
+  }
+
+  /**
+   * Configures Gson for custom serialization or deserialization for an inheritance type hierarchy.
+   * This method combines the registration of a {@link TypeAdapter}, {@link JsonSerializer} and
+   * a {@link JsonDeserializer}. If a type adapter was previously registered for the specified
+   * type hierarchy, it is overridden. If a type adapter is registered for a specific type in
+   * the type hierarchy, it will be invoked instead of the one registered for the type hierarchy.
+   *
+   * @param baseType the class definition for the type adapter being registered for the base class
+   *        or interface
+   * @param typeAdapter This object must implement at least one of {@link TypeAdapter},
+   *        {@link JsonSerializer} or {@link JsonDeserializer} interfaces.
+   * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
+   * @since 1.7
+   */
+  @SuppressWarnings({"unchecked", "rawtypes"})
+  public GsonBuilder registerTypeHierarchyAdapter(Class<?> baseType, Object typeAdapter) {
+    $Gson$Preconditions.checkArgument(typeAdapter instanceof JsonSerializer<?>
+        || typeAdapter instanceof JsonDeserializer<?>
+        || typeAdapter instanceof TypeAdapter<?>);
+    if (typeAdapter instanceof JsonDeserializer || typeAdapter instanceof JsonSerializer) {
+      hierarchyFactories.add(TreeTypeAdapter.newTypeHierarchyFactory(baseType, typeAdapter));
+    }
+    if (typeAdapter instanceof TypeAdapter<?>) {
+      factories.add(TypeAdapters.newTypeHierarchyFactory(baseType, (TypeAdapter)typeAdapter));
+    }
+    return this;
+  }
+
+  /**
+   * Section 2.4 of <a href="http://www.ietf.org/rfc/rfc4627.txt">JSON specification</a> disallows
+   * special double values (NaN, Infinity, -Infinity). However,
+   * <a href="http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf">Javascript
+   * specification</a> (see section 4.3.20, 4.3.22, 4.3.23) allows these values as valid Javascript
+   * values. Moreover, most JavaScript engines will accept these special values in JSON without
+   * problem. So, at a practical level, it makes sense to accept these values as valid JSON even
+   * though JSON specification disallows them.
+   *
+   * <p>Gson always accepts these special values during deserialization. However, it outputs
+   * strictly compliant JSON. Hence, if it encounters a float value {@link Float#NaN},
+   * {@link Float#POSITIVE_INFINITY}, {@link Float#NEGATIVE_INFINITY}, or a double value
+   * {@link Double#NaN}, {@link Double#POSITIVE_INFINITY}, {@link Double#NEGATIVE_INFINITY}, it
+   * will throw an {@link IllegalArgumentException}. This method provides a way to override the
+   * default behavior when you know that the JSON receiver will be able to handle these special
+   * values.
+   *
+   * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
+   * @since 1.3
+   */
+  public GsonBuilder serializeSpecialFloatingPointValues() {
+    this.serializeSpecialFloatingPointValues = true;
+    return this;
+  }
+
+  /**
+   * Disables usage of JDK's {@code sun.misc.Unsafe}.
+   *
+   * <p>By default Gson uses {@code Unsafe} to create instances of classes which don't have
+   * a no-args constructor. However, {@code Unsafe} might not be available for all Java
+   * runtimes. For example Android does not provide {@code Unsafe}, or only with limited
+   * functionality. Additionally {@code Unsafe} creates instances without executing any
+   * constructor or initializer block, or performing initialization of field values. This can
+   * lead to surprising and difficult to debug errors.
+   * Therefore, to get reliable behavior regardless of which runtime is used, and to detect
+   * classes which cannot be deserialized in an early stage of development, this method allows
+   * disabling usage of {@code Unsafe}.
+   *
+   * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
+   */
+  public GsonBuilder disableJdkUnsafe() {
+    this.useJdkUnsafe = false;
+    return this;
+  }
+
+  /**
+   * Adds a reflection access filter. A reflection access filter prevents Gson from using
+   * reflection for the serialization and deserialization of certain classes. The logic in
+   * the filter specifies which classes those are.
+   *
+   * <p>Filters will be invoked in reverse registration order, that is, the most recently
+   * added filter will be invoked first.
+   *
+   * <p>By default Gson has no filters configured and will try to use reflection for
+   * all classes for which no {@link TypeAdapter} has been registered, and for which no
+   * built-in Gson {@code TypeAdapter} exists.
+   *
+   * @param filter filter to add
+   * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
+   */
+  public GsonBuilder addReflectionAccessFilter(ReflectionAccessFilter filter) {
+    if (filter == null) throw new NullPointerException();
+
+    reflectionFilters.addFirst(filter);
+    return this;
+  }
+
+  /**
+   * Creates a {@link Gson} instance based on the current configuration. This method is free of
+   * side-effects to this {@code GsonBuilder} instance and hence can be called multiple times.
+   *
+   * @return an instance of Gson configured with the options currently set in this builder
+   */
+  public Gson create() {
+    List<TypeAdapterFactory> factories = new ArrayList<>(this.factories.size() + this.hierarchyFactories.size() + 3);
+    factories.addAll(this.factories);
+    Collections.reverse(factories);
+
+    List<TypeAdapterFactory> hierarchyFactories = new ArrayList<>(this.hierarchyFactories);
+    Collections.reverse(hierarchyFactories);
+    factories.addAll(hierarchyFactories);
+
+    addTypeAdaptersForDate(datePattern, dateStyle, timeStyle, factories);
+
+    return new Gson(excluder, fieldNamingPolicy, new HashMap<>(instanceCreators),
+        serializeNulls, complexMapKeySerialization,
+        generateNonExecutableJson, escapeHtmlChars, prettyPrinting, lenient,
+        serializeSpecialFloatingPointValues, useJdkUnsafe, longSerializationPolicy,
+        datePattern, dateStyle, timeStyle, new ArrayList<>(this.factories),
+        new ArrayList<>(this.hierarchyFactories), factories,
+        objectToNumberStrategy, numberToNumberStrategy, new ArrayList<>(reflectionFilters));
+  }
+
+  private void addTypeAdaptersForDate(String datePattern, int dateStyle, int timeStyle,
+      List<TypeAdapterFactory> factories) {
+    TypeAdapterFactory dateAdapterFactory;
+    boolean sqlTypesSupported = SqlTypesSupport.SUPPORTS_SQL_TYPES;
+    TypeAdapterFactory sqlTimestampAdapterFactory = null;
+    TypeAdapterFactory sqlDateAdapterFactory = null;
+
+    if (datePattern != null && !datePattern.trim().isEmpty()) {
+      dateAdapterFactory = DefaultDateTypeAdapter.DateType.DATE.createAdapterFactory(datePattern);
+
+      if (sqlTypesSupported) {
+        sqlTimestampAdapterFactory = SqlTypesSupport.TIMESTAMP_DATE_TYPE.createAdapterFactory(datePattern);
+        sqlDateAdapterFactory = SqlTypesSupport.DATE_DATE_TYPE.createAdapterFactory(datePattern);
+      }
+    } else if (dateStyle != DateFormat.DEFAULT && timeStyle != DateFormat.DEFAULT) {
+      dateAdapterFactory = DefaultDateTypeAdapter.DateType.DATE.createAdapterFactory(dateStyle, timeStyle);
+
+      if (sqlTypesSupported) {
+        sqlTimestampAdapterFactory = SqlTypesSupport.TIMESTAMP_DATE_TYPE.createAdapterFactory(dateStyle, timeStyle);
+        sqlDateAdapterFactory = SqlTypesSupport.DATE_DATE_TYPE.createAdapterFactory(dateStyle, timeStyle);
+      }
+    } else {
+      return;
+    }
+
+    factories.add(dateAdapterFactory);
+    if (sqlTypesSupported) {
+      factories.add(sqlTimestampAdapterFactory);
+      factories.add(sqlDateAdapterFactory);
+    }
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/InstanceCreator.java b/gson/src/main/java/com/google/gson/InstanceCreator.java
new file mode 100644
index 0000000..d5096a0
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/InstanceCreator.java
@@ -0,0 +1,92 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import java.lang.reflect.Type;
+
+/**
+ * This interface is implemented to create instances of a class that does not define a no-args
+ * constructor. If you can modify the class, you should instead add a private, or public
+ * no-args constructor. However, that is not possible for library classes, such as JDK classes, or
+ * a third-party library that you do not have source-code of. In such cases, you should define an
+ * instance creator for the class. Implementations of this interface should be registered with
+ * {@link GsonBuilder#registerTypeAdapter(Type, Object)} method before Gson will be able to use
+ * them.
+ * <p>Let us look at an example where defining an InstanceCreator might be useful. The
+ * {@code Id} class defined below does not have a default no-args constructor.</p>
+ *
+ * <pre>
+ * public class Id&lt;T&gt; {
+ *   private final Class&lt;T&gt; clazz;
+ *   private final long value;
+ *   public Id(Class&lt;T&gt; clazz, long value) {
+ *     this.clazz = clazz;
+ *     this.value = value;
+ *   }
+ * }
+ * </pre>
+ *
+ * <p>If Gson encounters an object of type {@code Id} during deserialization, it will throw an
+ * exception. The easiest way to solve this problem will be to add a (public or private) no-args
+ * constructor as follows:</p>
+ *
+ * <pre>
+ * private Id() {
+ *   this(Object.class, 0L);
+ * }
+ * </pre>
+ *
+ * <p>However, let us assume that the developer does not have access to the source-code of the
+ * {@code Id} class, or does not want to define a no-args constructor for it. The developer
+ * can solve this problem by defining an {@code InstanceCreator} for {@code Id}:</p>
+ *
+ * <pre>
+ * class IdInstanceCreator implements InstanceCreator&lt;Id&gt; {
+ *   public Id createInstance(Type type) {
+ *     return new Id(Object.class, 0L);
+ *   }
+ * }
+ * </pre>
+ *
+ * <p>Note that it does not matter what the fields of the created instance contain since Gson will
+ * overwrite them with the deserialized values specified in Json. You should also ensure that a
+ * <i>new</i> object is returned, not a common object since its fields will be overwritten.
+ * The developer will need to register {@code IdInstanceCreator} with Gson as follows:</p>
+ *
+ * <pre>
+ * Gson gson = new GsonBuilder().registerTypeAdapter(Id.class, new IdInstanceCreator()).create();
+ * </pre>
+ *
+ * @param <T> the type of object that will be created by this implementation.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public interface InstanceCreator<T> {
+
+  /**
+   * Gson invokes this call-back method during deserialization to create an instance of the
+   * specified type. The fields of the returned instance are overwritten with the data present
+   * in the Json. Since the prior contents of the object are destroyed and overwritten, do not
+   * return an instance that is useful elsewhere. In particular, do not return a common instance,
+   * always use {@code new} to create a new instance.
+   *
+   * @param type the parameterized T represented as a {@link Type}.
+   * @return a default object instance of type T.
+   */
+  public T createInstance(Type type);
+}
diff --git a/gson/src/main/java/com/google/gson/JsonArray.java b/gson/src/main/java/com/google/gson/JsonArray.java
new file mode 100644
index 0000000..fe8b686
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/JsonArray.java
@@ -0,0 +1,396 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+/**
+ * A class representing an array type in Json. An array is a list of {@link JsonElement}s each of
+ * which can be of a different type. This is an ordered list, meaning that the order in which
+ * elements are added is preserved.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public final class JsonArray extends JsonElement implements Iterable<JsonElement> {
+  private final List<JsonElement> elements;
+
+  /**
+   * Creates an empty JsonArray.
+   */
+  public JsonArray() {
+    elements = new ArrayList<>();
+  }
+  
+  public JsonArray(int capacity) {
+    elements = new ArrayList<>(capacity);
+  }
+
+  /**
+   * Creates a deep copy of this element and all its children
+   * @since 2.8.2
+   */
+  @Override
+  public JsonArray deepCopy() {
+    if (!elements.isEmpty()) {
+      JsonArray result = new JsonArray(elements.size());
+      for (JsonElement element : elements) {
+        result.add(element.deepCopy());
+      }
+      return result;
+    }
+    return new JsonArray();
+  }
+
+  /**
+   * Adds the specified boolean to self.
+   *
+   * @param bool the boolean that needs to be added to the array.
+   */
+  public void add(Boolean bool) {
+    elements.add(bool == null ? JsonNull.INSTANCE : new JsonPrimitive(bool));
+  }
+
+  /**
+   * Adds the specified character to self.
+   *
+   * @param character the character that needs to be added to the array.
+   */
+  public void add(Character character) {
+    elements.add(character == null ? JsonNull.INSTANCE : new JsonPrimitive(character));
+  }
+
+  /**
+   * Adds the specified number to self.
+   *
+   * @param number the number that needs to be added to the array.
+   */
+  public void add(Number number) {
+    elements.add(number == null ? JsonNull.INSTANCE : new JsonPrimitive(number));
+  }
+
+  /**
+   * Adds the specified string to self.
+   *
+   * @param string the string that needs to be added to the array.
+   */
+  public void add(String string) {
+    elements.add(string == null ? JsonNull.INSTANCE : new JsonPrimitive(string));
+  }
+
+  /**
+   * Adds the specified element to self.
+   *
+   * @param element the element that needs to be added to the array.
+   */
+  public void add(JsonElement element) {
+    if (element == null) {
+      element = JsonNull.INSTANCE;
+    }
+    elements.add(element);
+  }
+
+  /**
+   * Adds all the elements of the specified array to self.
+   *
+   * @param array the array whose elements need to be added to the array.
+   */
+  public void addAll(JsonArray array) {
+    elements.addAll(array.elements);
+  }
+
+  /**
+   * Replaces the element at the specified position in this array with the specified element.
+   *   Element can be null.
+   * @param index index of the element to replace
+   * @param element element to be stored at the specified position
+   * @return the element previously at the specified position
+   * @throws IndexOutOfBoundsException if the specified index is outside the array bounds
+   */
+  public JsonElement set(int index, JsonElement element) {
+    return elements.set(index, element);
+  }
+
+  /**
+   * Removes the first occurrence of the specified element from this array, if it is present.
+   * If the array does not contain the element, it is unchanged.
+   * @param element element to be removed from this array, if present
+   * @return true if this array contained the specified element, false otherwise
+   * @since 2.3
+   */
+  public boolean remove(JsonElement element) {
+    return elements.remove(element);
+  }
+
+  /**
+   * Removes the element at the specified position in this array. Shifts any subsequent elements
+   * to the left (subtracts one from their indices). Returns the element that was removed from
+   * the array.
+   * @param index index the index of the element to be removed
+   * @return the element previously at the specified position
+   * @throws IndexOutOfBoundsException if the specified index is outside the array bounds
+   * @since 2.3
+   */
+  public JsonElement remove(int index) {
+    return elements.remove(index);
+  }
+
+  /**
+   * Returns true if this array contains the specified element.
+   * @return true if this array contains the specified element.
+   * @param element whose presence in this array is to be tested
+   * @since 2.3
+   */
+  public boolean contains(JsonElement element) {
+    return elements.contains(element);
+  }
+
+  /**
+   * Returns the number of elements in the array.
+   *
+   * @return the number of elements in the array.
+   */
+  public int size() {
+    return elements.size();
+  }
+  
+  /**
+   * Returns true if the array is empty
+   *
+   * @return true if the array is empty
+   */
+  public boolean isEmpty() {
+    return elements.isEmpty();
+  }
+
+  /**
+   * Returns an iterator to navigate the elements of the array. Since the array is an ordered list,
+   * the iterator navigates the elements in the order they were inserted.
+   *
+   * @return an iterator to navigate the elements of the array.
+   */
+  @Override
+  public Iterator<JsonElement> iterator() {
+    return elements.iterator();
+  }
+
+  /**
+   * Returns the ith element of the array.
+   *
+   * @param i the index of the element that is being sought.
+   * @return the element present at the ith index.
+   * @throws IndexOutOfBoundsException if i is negative or greater than or equal to the
+   * {@link #size()} of the array.
+   */
+  public JsonElement get(int i) {
+    return elements.get(i);
+  }
+
+  /**
+   * convenience method to get this array as a {@link Number} if it contains a single element.
+   *
+   * @return get this element as a number if it is single element array.
+   * @throws ClassCastException if the element in the array is of not a {@link JsonPrimitive} and
+   * is not a valid Number.
+   * @throws IllegalStateException if the array has more than one element.
+   */
+  @Override
+  public Number getAsNumber() {
+    if (elements.size() == 1) {
+      return elements.get(0).getAsNumber();
+    }
+    throw new IllegalStateException();
+  }
+
+  /**
+   * convenience method to get this array as a {@link String} if it contains a single element.
+   *
+   * @return get this element as a String if it is single element array.
+   * @throws ClassCastException if the element in the array is of not a {@link JsonPrimitive} and
+   * is not a valid String.
+   * @throws IllegalStateException if the array has more than one element.
+   */
+  @Override
+  public String getAsString() {
+    if (elements.size() == 1) {
+      return elements.get(0).getAsString();
+    }
+    throw new IllegalStateException();
+  }
+
+  /**
+   * convenience method to get this array as a double if it contains a single element.
+   *
+   * @return get this element as a double if it is single element array.
+   * @throws ClassCastException if the element in the array is of not a {@link JsonPrimitive} and
+   * is not a valid double.
+   * @throws IllegalStateException if the array has more than one element.
+   */
+  @Override
+  public double getAsDouble() {
+    if (elements.size() == 1) {
+      return elements.get(0).getAsDouble();
+    }
+    throw new IllegalStateException();
+  }
+
+  /**
+   * convenience method to get this array as a {@link BigDecimal} if it contains a single element.
+   *
+   * @return get this element as a {@link BigDecimal} if it is single element array.
+   * @throws ClassCastException if the element in the array is of not a {@link JsonPrimitive}.
+   * @throws NumberFormatException if the element at index 0 is not a valid {@link BigDecimal}.
+   * @throws IllegalStateException if the array has more than one element.
+   * @since 1.2
+   */
+  @Override
+  public BigDecimal getAsBigDecimal() {
+    if (elements.size() == 1) {
+      return elements.get(0).getAsBigDecimal();
+    }
+    throw new IllegalStateException();
+  }
+
+  /**
+   * convenience method to get this array as a {@link BigInteger} if it contains a single element.
+   *
+   * @return get this element as a {@link BigInteger} if it is single element array.
+   * @throws ClassCastException if the element in the array is of not a {@link JsonPrimitive}.
+   * @throws NumberFormatException if the element at index 0 is not a valid {@link BigInteger}.
+   * @throws IllegalStateException if the array has more than one element.
+   * @since 1.2
+   */
+  @Override
+  public BigInteger getAsBigInteger() {
+    if (elements.size() == 1) {
+      return elements.get(0).getAsBigInteger();
+    }
+    throw new IllegalStateException();
+  }
+
+  /**
+   * convenience method to get this array as a float if it contains a single element.
+   *
+   * @return get this element as a float if it is single element array.
+   * @throws ClassCastException if the element in the array is of not a {@link JsonPrimitive} and
+   * is not a valid float.
+   * @throws IllegalStateException if the array has more than one element.
+   */
+  @Override
+  public float getAsFloat() {
+    if (elements.size() == 1) {
+      return elements.get(0).getAsFloat();
+    }
+    throw new IllegalStateException();
+  }
+
+  /**
+   * convenience method to get this array as a long if it contains a single element.
+   *
+   * @return get this element as a long if it is single element array.
+   * @throws ClassCastException if the element in the array is of not a {@link JsonPrimitive} and
+   * is not a valid long.
+   * @throws IllegalStateException if the array has more than one element.
+   */
+  @Override
+  public long getAsLong() {
+    if (elements.size() == 1) {
+      return elements.get(0).getAsLong();
+    }
+    throw new IllegalStateException();
+  }
+
+  /**
+   * convenience method to get this array as an integer if it contains a single element.
+   *
+   * @return get this element as an integer if it is single element array.
+   * @throws ClassCastException if the element in the array is of not a {@link JsonPrimitive} and
+   * is not a valid integer.
+   * @throws IllegalStateException if the array has more than one element.
+   */
+  @Override
+  public int getAsInt() {
+    if (elements.size() == 1) {
+      return elements.get(0).getAsInt();
+    }
+    throw new IllegalStateException();
+  }
+
+  @Override
+  public byte getAsByte() {
+    if (elements.size() == 1) {
+      return elements.get(0).getAsByte();
+    }
+    throw new IllegalStateException();
+  }
+
+  @Deprecated
+  @Override
+  public char getAsCharacter() {
+    if (elements.size() == 1) {
+      JsonElement element = elements.get(0);
+      return element.getAsCharacter();
+    }
+    throw new IllegalStateException();
+  }
+
+  /**
+   * convenience method to get this array as a primitive short if it contains a single element.
+   *
+   * @return get this element as a primitive short if it is single element array.
+   * @throws ClassCastException if the element in the array is of not a {@link JsonPrimitive} and
+   * is not a valid short.
+   * @throws IllegalStateException if the array has more than one element.
+   */
+  @Override
+  public short getAsShort() {
+    if (elements.size() == 1) {
+      return elements.get(0).getAsShort();
+    }
+    throw new IllegalStateException();
+  }
+
+  /**
+   * convenience method to get this array as a boolean if it contains a single element.
+   *
+   * @return get this element as a boolean if it is single element array.
+   * @throws ClassCastException if the element in the array is of not a {@link JsonPrimitive} and
+   * is not a valid boolean.
+   * @throws IllegalStateException if the array has more than one element.
+   */
+  @Override
+  public boolean getAsBoolean() {
+    if (elements.size() == 1) {
+      return elements.get(0).getAsBoolean();
+    }
+    throw new IllegalStateException();
+  }
+
+  @Override
+  public boolean equals(Object o) {
+    return (o == this) || (o instanceof JsonArray && ((JsonArray) o).elements.equals(elements));
+  }
+
+  @Override
+  public int hashCode() {
+    return elements.hashCode();
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/JsonDeserializationContext.java b/gson/src/main/java/com/google/gson/JsonDeserializationContext.java
new file mode 100644
index 0000000..00c7505
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/JsonDeserializationContext.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import java.lang.reflect.Type;
+
+/**
+ * Context for deserialization that is passed to a custom deserializer during invocation of its
+ * {@link JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext)}
+ * method.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public interface JsonDeserializationContext {
+
+  /**
+   * Invokes default deserialization on the specified object. It should never be invoked on
+   * the element received as a parameter of the
+   * {@link JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext)} method. Doing
+   * so will result in an infinite loop since Gson will in-turn call the custom deserializer again.
+   *
+   * @param json the parse tree.
+   * @param typeOfT type of the expected return value.
+   * @param <T> The type of the deserialized object.
+   * @return An object of type typeOfT.
+   * @throws JsonParseException if the parse tree does not contain expected data.
+   */
+  public <T> T deserialize(JsonElement json, Type typeOfT) throws JsonParseException;
+}
\ No newline at end of file
diff --git a/gson/src/main/java/com/google/gson/JsonDeserializer.java b/gson/src/main/java/com/google/gson/JsonDeserializer.java
new file mode 100644
index 0000000..0589eb2
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/JsonDeserializer.java
@@ -0,0 +1,91 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import java.lang.reflect.Type;
+
+/**
+ * <p>Interface representing a custom deserializer for Json. You should write a custom
+ * deserializer, if you are not happy with the default deserialization done by Gson. You will
+ * also need to register this deserializer through
+ * {@link GsonBuilder#registerTypeAdapter(Type, Object)}.</p>
+ *
+ * <p>Let us look at example where defining a deserializer will be useful. The {@code Id} class
+ * defined below has two fields: {@code clazz} and {@code value}.</p>
+ *
+ * <pre>
+ * public class Id&lt;T&gt; {
+ *   private final Class&lt;T&gt; clazz;
+ *   private final long value;
+ *   public Id(Class&lt;T&gt; clazz, long value) {
+ *     this.clazz = clazz;
+ *     this.value = value;
+ *   }
+ *   public long getValue() {
+ *     return value;
+ *   }
+ * }
+ * </pre>
+ *
+ * <p>The default deserialization of {@code Id(com.foo.MyObject.class, 20L)} will require the
+ * Json string to be <code>{"clazz":com.foo.MyObject,"value":20}</code>. Suppose, you already know
+ * the type of the field that the {@code Id} will be deserialized into, and hence just want to
+ * deserialize it from a Json string {@code 20}. You can achieve that by writing a custom
+ * deserializer:</p>
+ *
+ * <pre>
+ * class IdDeserializer implements JsonDeserializer&lt;Id&gt;() {
+ *   public Id deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
+ *       throws JsonParseException {
+ *     return new Id((Class)typeOfT, id.getValue());
+ *   }
+ * </pre>
+ *
+ * <p>You will also need to register {@code IdDeserializer} with Gson as follows:</p>
+ *
+ * <pre>
+ * Gson gson = new GsonBuilder().registerTypeAdapter(Id.class, new IdDeserializer()).create();
+ * </pre>
+ *
+ * <p>New applications should prefer {@link TypeAdapter}, whose streaming API
+ * is more efficient than this interface's tree API.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ *
+ * @param <T> type for which the deserializer is being registered. It is possible that a
+ * deserializer may be asked to deserialize a specific generic type of the T.
+ */
+public interface JsonDeserializer<T> {
+
+  /**
+   * Gson invokes this call-back method during deserialization when it encounters a field of the
+   * specified type.
+   * <p>In the implementation of this call-back method, you should consider invoking
+   * {@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
+   * the same type passing {@code json} since that will cause an infinite loop (Gson will call your
+   * call-back method again).
+   *
+   * @param json The Json data being deserialized
+   * @param typeOfT The type of the Object to deserialize to
+   * @return a deserialized object of the specified type typeOfT which is a subclass of {@code T}
+   * @throws JsonParseException if json is not in the expected format of {@code typeofT}
+   */
+  public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
+      throws JsonParseException;
+}
diff --git a/gson/src/main/java/com/google/gson/JsonElement.java b/gson/src/main/java/com/google/gson/JsonElement.java
new file mode 100644
index 0000000..fb6a5f1
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/JsonElement.java
@@ -0,0 +1,322 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import com.google.gson.internal.Streams;
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
+import java.io.StringWriter;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+
+/**
+ * A class representing an element of Json. It could either be a {@link JsonObject}, a
+ * {@link JsonArray}, a {@link JsonPrimitive} or a {@link JsonNull}.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public abstract class JsonElement {
+  /**
+   * Returns a deep copy of this element. Immutable elements like primitives
+   * and nulls are not copied.
+   * @since 2.8.2
+   */
+  public abstract JsonElement deepCopy();
+
+  /**
+   * provides check for verifying if this element is an array or not.
+   *
+   * @return true if this element is of type {@link JsonArray}, false otherwise.
+   */
+  public boolean isJsonArray() {
+    return this instanceof JsonArray;
+  }
+
+  /**
+   * provides check for verifying if this element is a Json object or not.
+   *
+   * @return true if this element is of type {@link JsonObject}, false otherwise.
+   */
+  public boolean isJsonObject() {
+    return this instanceof JsonObject;
+  }
+
+  /**
+   * provides check for verifying if this element is a primitive or not.
+   *
+   * @return true if this element is of type {@link JsonPrimitive}, false otherwise.
+   */
+  public boolean isJsonPrimitive() {
+    return this instanceof JsonPrimitive;
+  }
+
+  /**
+   * provides check for verifying if this element represents a null value or not.
+   *
+   * @return true if this element is of type {@link JsonNull}, false otherwise.
+   * @since 1.2
+   */
+  public boolean isJsonNull() {
+    return this instanceof JsonNull;
+  }
+
+  /**
+   * convenience method to get this element as a {@link JsonObject}. If the element is of some
+   * other type, a {@link IllegalStateException} will result. Hence it is best to use this method
+   * after ensuring that this element is of the desired type by calling {@link #isJsonObject()}
+   * first.
+   *
+   * @return get this element as a {@link JsonObject}.
+   * @throws IllegalStateException if the element is of another type.
+   */
+  public JsonObject getAsJsonObject() {
+    if (isJsonObject()) {
+      return (JsonObject) this;
+    }
+    throw new IllegalStateException("Not a JSON Object: " + this);
+  }
+
+  /**
+   * convenience method to get this element as a {@link JsonArray}. If the element is of some
+   * other type, a {@link IllegalStateException} will result. Hence it is best to use this method
+   * after ensuring that this element is of the desired type by calling {@link #isJsonArray()}
+   * first.
+   *
+   * @return get this element as a {@link JsonArray}.
+   * @throws IllegalStateException if the element is of another type.
+   */
+  public JsonArray getAsJsonArray() {
+    if (isJsonArray()) {
+      return (JsonArray) this;
+    }
+    throw new IllegalStateException("Not a JSON Array: " + this);
+  }
+
+  /**
+   * convenience method to get this element as a {@link JsonPrimitive}. If the element is of some
+   * other type, a {@link IllegalStateException} will result. Hence it is best to use this method
+   * after ensuring that this element is of the desired type by calling {@link #isJsonPrimitive()}
+   * first.
+   *
+   * @return get this element as a {@link JsonPrimitive}.
+   * @throws IllegalStateException if the element is of another type.
+   */
+  public JsonPrimitive getAsJsonPrimitive() {
+    if (isJsonPrimitive()) {
+      return (JsonPrimitive) this;
+    }
+    throw new IllegalStateException("Not a JSON Primitive: " + this);
+  }
+
+  /**
+   * convenience method to get this element as a {@link JsonNull}. If the element is of some
+   * other type, a {@link IllegalStateException} will result. Hence it is best to use this method
+   * after ensuring that this element is of the desired type by calling {@link #isJsonNull()}
+   * first.
+   *
+   * @return get this element as a {@link JsonNull}.
+   * @throws IllegalStateException if the element is of another type.
+   * @since 1.2
+   */
+  public JsonNull getAsJsonNull() {
+    if (isJsonNull()) {
+      return (JsonNull) this;
+    }
+    throw new IllegalStateException("Not a JSON Null: " + this);
+  }
+
+  /**
+   * convenience method to get this element as a boolean value.
+   *
+   * @return get this element as a primitive boolean value.
+   * @throws ClassCastException if the element is of not a {@link JsonPrimitive} and is not a valid
+   * boolean value.
+   * @throws IllegalStateException if the element is of the type {@link JsonArray} but contains
+   * more than a single element.
+   */
+  public boolean getAsBoolean() {
+    throw new UnsupportedOperationException(getClass().getSimpleName());
+  }
+
+  /**
+   * convenience method to get this element as a {@link Number}.
+   *
+   * @return get this element as a {@link Number}.
+   * @throws ClassCastException if the element is of not a {@link JsonPrimitive} and is not a valid
+   * number.
+   * @throws IllegalStateException if the element is of the type {@link JsonArray} but contains
+   * more than a single element.
+   */
+  public Number getAsNumber() {
+    throw new UnsupportedOperationException(getClass().getSimpleName());
+  }
+
+  /**
+   * convenience method to get this element as a string value.
+   *
+   * @return get this element as a string value.
+   * @throws ClassCastException if the element is of not a {@link JsonPrimitive} and is not a valid
+   * string value.
+   * @throws IllegalStateException if the element is of the type {@link JsonArray} but contains
+   * more than a single element.
+   */
+  public String getAsString() {
+    throw new UnsupportedOperationException(getClass().getSimpleName());
+  }
+
+  /**
+   * convenience method to get this element as a primitive double value.
+   *
+   * @return get this element as a primitive double value.
+   * @throws ClassCastException if the element is of not a {@link JsonPrimitive} and is not a valid
+   * double value.
+   * @throws IllegalStateException if the element is of the type {@link JsonArray} but contains
+   * more than a single element.
+   */
+  public double getAsDouble() {
+    throw new UnsupportedOperationException(getClass().getSimpleName());
+  }
+
+  /**
+   * convenience method to get this element as a primitive float value.
+   *
+   * @return get this element as a primitive float value.
+   * @throws ClassCastException if the element is of not a {@link JsonPrimitive} and is not a valid
+   * float value.
+   * @throws IllegalStateException if the element is of the type {@link JsonArray} but contains
+   * more than a single element.
+   */
+  public float getAsFloat() {
+    throw new UnsupportedOperationException(getClass().getSimpleName());
+  }
+
+  /**
+   * convenience method to get this element as a primitive long value.
+   *
+   * @return get this element as a primitive long value.
+   * @throws ClassCastException if the element is of not a {@link JsonPrimitive} and is not a valid
+   * long value.
+   * @throws IllegalStateException if the element is of the type {@link JsonArray} but contains
+   * more than a single element.
+   */
+  public long getAsLong() {
+    throw new UnsupportedOperationException(getClass().getSimpleName());
+  }
+
+  /**
+   * convenience method to get this element as a primitive integer value.
+   *
+   * @return get this element as a primitive integer value.
+   * @throws ClassCastException if the element is of not a {@link JsonPrimitive} and is not a valid
+   * integer value.
+   * @throws IllegalStateException if the element is of the type {@link JsonArray} but contains
+   * more than a single element.
+   */
+  public int getAsInt() {
+    throw new UnsupportedOperationException(getClass().getSimpleName());
+  }
+
+  /**
+   * convenience method to get this element as a primitive byte value.
+   *
+   * @return get this element as a primitive byte value.
+   * @throws ClassCastException if the element is of not a {@link JsonPrimitive} and is not a valid
+   * byte value.
+   * @throws IllegalStateException if the element is of the type {@link JsonArray} but contains
+   * more than a single element.
+   * @since 1.3
+   */
+  public byte getAsByte() {
+    throw new UnsupportedOperationException(getClass().getSimpleName());
+  }
+
+  /**
+   * convenience method to get the first character of this element as a string or the first
+   * character of this array's first element as a string.
+   *
+   * @return the first character of the string.
+   * @throws ClassCastException if the element is of not a {@link JsonPrimitive} and is not a valid
+   * string value.
+   * @throws IllegalStateException if the element is of the type {@link JsonArray} but contains
+   * more than a single element.
+   * @since 1.3
+   * @deprecated This method is misleading, as it does not get this element as a char but rather as
+   * a string's first character.
+   */
+  @Deprecated
+  public char getAsCharacter() {
+    throw new UnsupportedOperationException(getClass().getSimpleName());
+  }
+
+  /**
+   * convenience method to get this element as a {@link BigDecimal}.
+   *
+   * @return get this element as a {@link BigDecimal}.
+   * @throws ClassCastException if the element is of not a {@link JsonPrimitive}.
+   * @throws NumberFormatException if the element is not a valid {@link BigDecimal}.
+   * @throws IllegalStateException if the element is of the type {@link JsonArray} but contains
+   * more than a single element.
+   * @since 1.2
+   */
+  public BigDecimal getAsBigDecimal() {
+    throw new UnsupportedOperationException(getClass().getSimpleName());
+  }
+
+  /**
+   * convenience method to get this element as a {@link BigInteger}.
+   *
+   * @return get this element as a {@link BigInteger}.
+   * @throws ClassCastException if the element is of not a {@link JsonPrimitive}.
+   * @throws NumberFormatException if the element is not a valid {@link BigInteger}.
+   * @throws IllegalStateException if the element is of the type {@link JsonArray} but contains
+   * more than a single element.
+   * @since 1.2
+   */
+  public BigInteger getAsBigInteger() {
+    throw new UnsupportedOperationException(getClass().getSimpleName());
+  }
+
+  /**
+   * convenience method to get this element as a primitive short value.
+   *
+   * @return get this element as a primitive short value.
+   * @throws ClassCastException if the element is of not a {@link JsonPrimitive} and is not a valid
+   * short value.
+   * @throws IllegalStateException if the element is of the type {@link JsonArray} but contains
+   * more than a single element.
+   */
+  public short getAsShort() {
+    throw new UnsupportedOperationException(getClass().getSimpleName());
+  }
+
+  /**
+   * Returns a String representation of this element.
+   */
+  @Override
+  public String toString() {
+    try {
+      StringWriter stringWriter = new StringWriter();
+      JsonWriter jsonWriter = new JsonWriter(stringWriter);
+      jsonWriter.setLenient(true);
+      Streams.write(this, jsonWriter);
+      return stringWriter.toString();
+    } catch (IOException e) {
+      throw new AssertionError(e);
+    }
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/JsonIOException.java b/gson/src/main/java/com/google/gson/JsonIOException.java
new file mode 100644
index 0000000..dfeccd8
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/JsonIOException.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson;
+
+/**
+ * This exception is raised when Gson was unable to read an input stream
+ * or write to one.
+ * 
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public final class JsonIOException extends JsonParseException {
+  private static final long serialVersionUID = 1L;
+
+  public JsonIOException(String msg) {
+    super(msg);
+  }
+
+  public JsonIOException(String msg, Throwable cause) {
+    super(msg, cause);
+  }
+
+  /**
+   * Creates exception with the specified cause. Consider using
+   * {@link #JsonIOException(String, Throwable)} instead if you can describe what happened.
+   *
+   * @param cause root exception that caused this exception to be thrown.
+   */
+  public JsonIOException(Throwable cause) {
+    super(cause);
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/JsonNull.java b/gson/src/main/java/com/google/gson/JsonNull.java
new file mode 100644
index 0000000..67cb932
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/JsonNull.java
@@ -0,0 +1,67 @@
+/*

+ * Copyright (C) 2008 Google Inc.

+ *

+ * Licensed under the Apache License, Version 2.0 (the "License");

+ * you may not use this file except in compliance with the License.

+ * You may obtain a copy of the License at

+ *

+ * http://www.apache.org/licenses/LICENSE-2.0

+ *

+ * Unless required by applicable law or agreed to in writing, software

+ * distributed under the License is distributed on an "AS IS" BASIS,

+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

+ * See the License for the specific language governing permissions and

+ * limitations under the License.

+ */

+

+package com.google.gson;

+

+/**

+ * A class representing a Json {@code null} value.

+ *

+ * @author Inderjeet Singh

+ * @author Joel Leitch

+ * @since 1.2

+ */

+public final class JsonNull extends JsonElement {

+  /**

+   * singleton for JsonNull

+   *

+   * @since 1.8

+   */

+  public static final JsonNull INSTANCE = new JsonNull();

+

+  /**

+   * Creates a new JsonNull object.

+   * Deprecated since Gson version 1.8. Use {@link #INSTANCE} instead

+   */

+  @Deprecated

+  public JsonNull() {

+    // Do nothing

+  }

+

+  /**

+   * Returns the same instance since it is an immutable value

+   * @since 2.8.2

+   */

+  @Override

+  public JsonNull deepCopy() {

+    return INSTANCE;

+  }

+

+  /**

+   * All instances of JsonNull have the same hash code since they are indistinguishable

+   */

+  @Override

+  public int hashCode() {

+    return JsonNull.class.hashCode();

+  }

+

+  /**

+   * All instances of JsonNull are the same

+   */

+  @Override

+  public boolean equals(Object other) {

+    return this == other || other instanceof JsonNull;

+  }

+}

diff --git a/gson/src/main/java/com/google/gson/JsonObject.java b/gson/src/main/java/com/google/gson/JsonObject.java
new file mode 100644
index 0000000..285a842
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/JsonObject.java
@@ -0,0 +1,204 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import com.google.gson.internal.LinkedTreeMap;
+
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * A class representing an object type in Json. An object consists of name-value pairs where names
+ * are strings, and values are any other type of {@link JsonElement}. This allows for a creating a
+ * tree of JsonElements. The member elements of this object are maintained in order they were added.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public final class JsonObject extends JsonElement {
+  private final LinkedTreeMap<String, JsonElement> members = new LinkedTreeMap<>();
+
+  /**
+   * Creates a deep copy of this element and all its children
+   * @since 2.8.2
+   */
+  @Override
+  public JsonObject deepCopy() {
+    JsonObject result = new JsonObject();
+    for (Map.Entry<String, JsonElement> entry : members.entrySet()) {
+      result.add(entry.getKey(), entry.getValue().deepCopy());
+    }
+    return result;
+  }
+
+  /**
+   * Adds a member, which is a name-value pair, to self. The name must be a String, but the value
+   * can be an arbitrary JsonElement, thereby allowing you to build a full tree of JsonElements
+   * rooted at this node.
+   *
+   * @param property name of the member.
+   * @param value the member object.
+   */
+  public void add(String property, JsonElement value) {
+    members.put(property, value == null ? JsonNull.INSTANCE : value);
+  }
+
+  /**
+   * Removes the {@code property} from this {@link JsonObject}.
+   *
+   * @param property name of the member that should be removed.
+   * @return the {@link JsonElement} object that is being removed.
+   * @since 1.3
+   */
+  public JsonElement remove(String property) {
+    return members.remove(property);
+  }
+
+  /**
+   * Convenience method to add a primitive member. The specified value is converted to a
+   * JsonPrimitive of String.
+   *
+   * @param property name of the member.
+   * @param value the string value associated with the member.
+   */
+  public void addProperty(String property, String value) {
+    add(property, value == null ? JsonNull.INSTANCE : new JsonPrimitive(value));
+  }
+
+  /**
+   * Convenience method to add a primitive member. The specified value is converted to a
+   * JsonPrimitive of Number.
+   *
+   * @param property name of the member.
+   * @param value the number value associated with the member.
+   */
+  public void addProperty(String property, Number value) {
+    add(property, value == null ? JsonNull.INSTANCE : new JsonPrimitive(value));
+  }
+
+  /**
+   * Convenience method to add a boolean member. The specified value is converted to a
+   * JsonPrimitive of Boolean.
+   *
+   * @param property name of the member.
+   * @param value the number value associated with the member.
+   */
+  public void addProperty(String property, Boolean value) {
+    add(property, value == null ? JsonNull.INSTANCE : new JsonPrimitive(value));
+  }
+
+  /**
+   * Convenience method to add a char member. The specified value is converted to a
+   * JsonPrimitive of Character.
+   *
+   * @param property name of the member.
+   * @param value the number value associated with the member.
+   */
+  public void addProperty(String property, Character value) {
+    add(property, value == null ? JsonNull.INSTANCE : new JsonPrimitive(value));
+  }
+
+  /**
+   * Returns a set of members of this object. The set is ordered, and the order is in which the
+   * elements were added.
+   *
+   * @return a set of members of this object.
+   */
+  public Set<Map.Entry<String, JsonElement>> entrySet() {
+    return members.entrySet();
+  }
+
+  /**
+   * Returns a set of members key values.
+   *
+   * @return a set of member keys as Strings
+   * @since 2.8.1
+   */
+  public Set<String> keySet() {
+    return members.keySet();
+  }
+
+  /**
+   * Returns the number of key/value pairs in the object.
+   *
+   * @return the number of key/value pairs in the object.
+   */
+  public int size() {
+    return members.size();
+  }
+
+  /**
+   * Convenience method to check if a member with the specified name is present in this object.
+   *
+   * @param memberName name of the member that is being checked for presence.
+   * @return true if there is a member with the specified name, false otherwise.
+   */
+  public boolean has(String memberName) {
+    return members.containsKey(memberName);
+  }
+
+  /**
+   * Returns the member with the specified name.
+   *
+   * @param memberName name of the member that is being requested.
+   * @return the member matching the name. Null if no such member exists.
+   */
+  public JsonElement get(String memberName) {
+    return members.get(memberName);
+  }
+
+  /**
+   * Convenience method to get the specified member as a JsonPrimitive element.
+   *
+   * @param memberName name of the member being requested.
+   * @return the JsonPrimitive corresponding to the specified member.
+   */
+  public JsonPrimitive getAsJsonPrimitive(String memberName) {
+    return (JsonPrimitive) members.get(memberName);
+  }
+
+  /**
+   * Convenience method to get the specified member as a JsonArray.
+   *
+   * @param memberName name of the member being requested.
+   * @return the JsonArray corresponding to the specified member.
+   */
+  public JsonArray getAsJsonArray(String memberName) {
+    return (JsonArray) members.get(memberName);
+  }
+
+  /**
+   * Convenience method to get the specified member as a JsonObject.
+   *
+   * @param memberName name of the member being requested.
+   * @return the JsonObject corresponding to the specified member.
+   */
+  public JsonObject getAsJsonObject(String memberName) {
+    return (JsonObject) members.get(memberName);
+  }
+
+  @Override
+  public boolean equals(Object o) {
+    return (o == this) || (o instanceof JsonObject
+        && ((JsonObject) o).members.equals(members));
+  }
+
+  @Override
+  public int hashCode() {
+    return members.hashCode();
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/JsonParseException.java b/gson/src/main/java/com/google/gson/JsonParseException.java
new file mode 100644
index 0000000..c1f264d
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/JsonParseException.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+/**
+ * This exception is raised if there is a serious issue that occurs during parsing of a Json
+ * string. One of the main usages for this class is for the Gson infrastructure. If the incoming
+ * Json is bad/malicious, an instance of this exception is raised.
+ *
+ * <p>This exception is a {@link RuntimeException} because it is exposed to the client. Using a
+ * {@link RuntimeException} avoids bad coding practices on the client side where they catch the
+ * exception and do nothing. It is often the case that you want to blow up if there is a parsing
+ * error (i.e. often clients do not know how to recover from a {@link JsonParseException}.</p>
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public class JsonParseException extends RuntimeException {
+  static final long serialVersionUID = -4086729973971783390L;
+
+  /**
+   * Creates exception with the specified message. If you are wrapping another exception, consider
+   * using {@link #JsonParseException(String, Throwable)} instead.
+   *
+   * @param msg error message describing a possible cause of this exception.
+   */
+  public JsonParseException(String msg) {
+    super(msg);
+  }
+
+  /**
+   * Creates exception with the specified message and cause.
+   *
+   * @param msg error message describing what happened.
+   * @param cause root exception that caused this exception to be thrown.
+   */
+  public JsonParseException(String msg, Throwable cause) {
+    super(msg, cause);
+  }
+
+  /**
+   * Creates exception with the specified cause. Consider using
+   * {@link #JsonParseException(String, Throwable)} instead if you can describe what happened.
+   *
+   * @param cause root exception that caused this exception to be thrown.
+   */
+  public JsonParseException(Throwable cause) {
+    super(cause);
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/JsonParser.java b/gson/src/main/java/com/google/gson/JsonParser.java
new file mode 100644
index 0000000..d3508c1
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/JsonParser.java
@@ -0,0 +1,126 @@
+/*

+ * Copyright (C) 2009 Google Inc.

+ *

+ * Licensed under the Apache License, Version 2.0 (the "License");

+ * you may not use this file except in compliance with the License.

+ * You may obtain a copy of the License at

+ *

+ * http://www.apache.org/licenses/LICENSE-2.0

+ *

+ * Unless required by applicable law or agreed to in writing, software

+ * distributed under the License is distributed on an "AS IS" BASIS,

+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

+ * See the License for the specific language governing permissions and

+ * limitations under the License.

+ */

+package com.google.gson;

+

+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.Reader;

+import java.io.StringReader;

+

+/**

+ * A parser to parse JSON into a parse tree of {@link JsonElement}s.

+ *

+ * @author Inderjeet Singh

+ * @author Joel Leitch

+ * @since 1.3

+ */

+public final class JsonParser {

+  /** @deprecated No need to instantiate this class, use the static methods instead. */

+  @Deprecated

+  public JsonParser() {}

+

+  /**

+   * Parses the specified JSON string into a parse tree.

+   * An exception is thrown if the JSON string has multiple top-level JSON elements,

+   * or if there is trailing data.

+   *

+   * <p>The JSON string is parsed in {@linkplain JsonReader#setLenient(boolean) lenient mode}.

+   *

+   * @param json JSON text

+   * @return a parse tree of {@link JsonElement}s corresponding to the specified JSON

+   * @throws JsonParseException if the specified text is not valid JSON

+   */

+  public static JsonElement parseString(String json) throws JsonSyntaxException {

+    return parseReader(new StringReader(json));

+  }

+

+  /**

+   * Parses the complete JSON string provided by the reader into a parse tree.

+   * An exception is thrown if the JSON string has multiple top-level JSON elements,

+   * or if there is trailing data.

+   *

+   * <p>The JSON data is parsed in {@linkplain JsonReader#setLenient(boolean) lenient mode}.

+   *

+   * @param reader JSON text

+   * @return a parse tree of {@link JsonElement}s corresponding to the specified JSON

+   * @throws JsonParseException if there is an IOException or if the specified

+   *     text is not valid JSON

+   */

+  public static JsonElement parseReader(Reader reader) throws JsonIOException, JsonSyntaxException {

+    try {

+      JsonReader jsonReader = new JsonReader(reader);

+      JsonElement element = parseReader(jsonReader);

+      if (!element.isJsonNull() && jsonReader.peek() != JsonToken.END_DOCUMENT) {

+        throw new JsonSyntaxException("Did not consume the entire document.");

+      }

+      return element;

+    } catch (MalformedJsonException e) {

+      throw new JsonSyntaxException(e);

+    } catch (IOException e) {

+      throw new JsonIOException(e);

+    } catch (NumberFormatException e) {

+      throw new JsonSyntaxException(e);

+    }

+  }

+

+  /**

+   * Returns the next value from the JSON stream as a parse tree.

+   * Unlike the other {@code parse} methods, no exception is thrown if the JSON data has

+   * multiple top-level JSON elements, or if there is trailing data.

+   *

+   * <p>The JSON data is parsed in {@linkplain JsonReader#setLenient(boolean) lenient mode},

+   * regardless of the lenient mode setting of the provided reader. The lenient mode setting

+   * of the reader is restored once this method returns.

+   *

+   * @throws JsonParseException if there is an IOException or if the specified

+   *     text is not valid JSON

+   */

+  public static JsonElement parseReader(JsonReader reader)

+      throws JsonIOException, JsonSyntaxException {

+    boolean lenient = reader.isLenient();

+    reader.setLenient(true);

+    try {

+      return Streams.parse(reader);

+    } catch (StackOverflowError e) {

+      throw new JsonParseException("Failed parsing JSON source: " + reader + " to Json", e);

+    } catch (OutOfMemoryError e) {

+      throw new JsonParseException("Failed parsing JSON source: " + reader + " to Json", e);

+    } finally {

+      reader.setLenient(lenient);

+    }

+  }

+

+  /** @deprecated Use {@link JsonParser#parseString} */

+  @Deprecated

+  public JsonElement parse(String json) throws JsonSyntaxException {

+    return parseString(json);

+  }

+

+  /** @deprecated Use {@link JsonParser#parseReader(Reader)} */

+  @Deprecated

+  public JsonElement parse(Reader json) throws JsonIOException, JsonSyntaxException {

+    return parseReader(json);

+  }

+

+  /** @deprecated Use {@link JsonParser#parseReader(JsonReader)} */

+  @Deprecated

+  public JsonElement parse(JsonReader json) throws JsonIOException, JsonSyntaxException {

+    return parseReader(json);

+  }

+}

diff --git a/gson/src/main/java/com/google/gson/JsonPrimitive.java b/gson/src/main/java/com/google/gson/JsonPrimitive.java
new file mode 100644
index 0000000..5e95d5a
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/JsonPrimitive.java
@@ -0,0 +1,295 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import com.google.gson.internal.$Gson$Preconditions;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+
+import com.google.gson.internal.LazilyParsedNumber;
+
+/**
+ * A class representing a Json primitive value. A primitive value
+ * is either a String, a Java primitive, or a Java primitive
+ * wrapper type.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public final class JsonPrimitive extends JsonElement {
+
+  private final Object value;
+
+  /**
+   * Create a primitive containing a boolean value.
+   *
+   * @param bool the value to create the primitive with.
+   */
+  public JsonPrimitive(Boolean bool) {
+    value = $Gson$Preconditions.checkNotNull(bool);
+  }
+
+  /**
+   * Create a primitive containing a {@link Number}.
+   *
+   * @param number the value to create the primitive with.
+   */
+  public JsonPrimitive(Number number) {
+    value = $Gson$Preconditions.checkNotNull(number);
+  }
+
+  /**
+   * Create a primitive containing a String value.
+   *
+   * @param string the value to create the primitive with.
+   */
+  public JsonPrimitive(String string) {
+    value = $Gson$Preconditions.checkNotNull(string);
+  }
+
+  /**
+   * Create a primitive containing a character. The character is turned into a one character String
+   * since Json only supports String.
+   *
+   * @param c the value to create the primitive with.
+   */
+  public JsonPrimitive(Character c) {
+    // convert characters to strings since in JSON, characters are represented as a single
+    // character string
+    value = $Gson$Preconditions.checkNotNull(c).toString();
+  }
+
+  /**
+   * Returns the same value as primitives are immutable.
+   * @since 2.8.2
+   */
+  @Override
+  public JsonPrimitive deepCopy() {
+    return this;
+  }
+
+  /**
+   * Check whether this primitive contains a boolean value.
+   *
+   * @return true if this primitive contains a boolean value, false otherwise.
+   */
+  public boolean isBoolean() {
+    return value instanceof Boolean;
+  }
+
+  /**
+   * convenience method to get this element as a boolean value.
+   *
+   * @return get this element as a primitive boolean value.
+   */
+  @Override
+  public boolean getAsBoolean() {
+    if (isBoolean()) {
+      return ((Boolean) value).booleanValue();
+    }
+	// Check to see if the value as a String is "true" in any case.
+    return Boolean.parseBoolean(getAsString());
+  }
+
+  /**
+   * Check whether this primitive contains a Number.
+   *
+   * @return true if this primitive contains a Number, false otherwise.
+   */
+  public boolean isNumber() {
+    return value instanceof Number;
+  }
+
+  /**
+   * convenience method to get this element as a Number.
+   *
+   * @return get this element as a Number.
+   * @throws NumberFormatException if the value contained is not a valid Number.
+   */
+  @Override
+  public Number getAsNumber() {
+    return value instanceof String ? new LazilyParsedNumber((String) value) : (Number) value;
+  }
+
+  /**
+   * Check whether this primitive contains a String value.
+   *
+   * @return true if this primitive contains a String value, false otherwise.
+   */
+  public boolean isString() {
+    return value instanceof String;
+  }
+
+  /**
+   * convenience method to get this element as a String.
+   *
+   * @return get this element as a String.
+   */
+  @Override
+  public String getAsString() {
+    if (isNumber()) {
+      return getAsNumber().toString();
+    } else if (isBoolean()) {
+      return ((Boolean) value).toString();
+    } else {
+      return (String) value;
+    }
+  }
+
+  /**
+   * convenience method to get this element as a primitive double.
+   *
+   * @return get this element as a primitive double.
+   * @throws NumberFormatException if the value contained is not a valid double.
+   */
+  @Override
+  public double getAsDouble() {
+    return isNumber() ? getAsNumber().doubleValue() : Double.parseDouble(getAsString());
+  }
+
+  /**
+   * convenience method to get this element as a {@link BigDecimal}.
+   *
+   * @return get this element as a {@link BigDecimal}.
+   * @throws NumberFormatException if the value contained is not a valid {@link BigDecimal}.
+   */
+  @Override
+  public BigDecimal getAsBigDecimal() {
+    return value instanceof BigDecimal ? (BigDecimal) value : new BigDecimal(value.toString());
+  }
+
+  /**
+   * convenience method to get this element as a {@link BigInteger}.
+   *
+   * @return get this element as a {@link BigInteger}.
+   * @throws NumberFormatException if the value contained is not a valid {@link BigInteger}.
+   */
+  @Override
+  public BigInteger getAsBigInteger() {
+    return value instanceof BigInteger ?
+        (BigInteger) value : new BigInteger(value.toString());
+  }
+
+  /**
+   * convenience method to get this element as a float.
+   *
+   * @return get this element as a float.
+   * @throws NumberFormatException if the value contained is not a valid float.
+   */
+  @Override
+  public float getAsFloat() {
+    return isNumber() ? getAsNumber().floatValue() : Float.parseFloat(getAsString());
+  }
+
+  /**
+   * convenience method to get this element as a primitive long.
+   *
+   * @return get this element as a primitive long.
+   * @throws NumberFormatException if the value contained is not a valid long.
+   */
+  @Override
+  public long getAsLong() {
+    return isNumber() ? getAsNumber().longValue() : Long.parseLong(getAsString());
+  }
+
+  /**
+   * convenience method to get this element as a primitive short.
+   *
+   * @return get this element as a primitive short.
+   * @throws NumberFormatException if the value contained is not a valid short value.
+   */
+  @Override
+  public short getAsShort() {
+    return isNumber() ? getAsNumber().shortValue() : Short.parseShort(getAsString());
+  }
+
+ /**
+  * convenience method to get this element as a primitive integer.
+  *
+  * @return get this element as a primitive integer.
+  * @throws NumberFormatException if the value contained is not a valid integer.
+  */
+  @Override
+  public int getAsInt() {
+    return isNumber() ? getAsNumber().intValue() : Integer.parseInt(getAsString());
+  }
+
+  @Override
+  public byte getAsByte() {
+    return isNumber() ? getAsNumber().byteValue() : Byte.parseByte(getAsString());
+  }
+
+  @Override
+  public char getAsCharacter() {
+    return getAsString().charAt(0);
+  }
+
+  @Override
+  public int hashCode() {
+    if (value == null) {
+      return 31;
+    }
+    // Using recommended hashing algorithm from Effective Java for longs and doubles
+    if (isIntegral(this)) {
+      long value = getAsNumber().longValue();
+      return (int) (value ^ (value >>> 32));
+    }
+    if (value instanceof Number) {
+      long value = Double.doubleToLongBits(getAsNumber().doubleValue());
+      return (int) (value ^ (value >>> 32));
+    }
+    return value.hashCode();
+  }
+
+  @Override
+  public boolean equals(Object obj) {
+    if (this == obj) {
+      return true;
+    }
+    if (obj == null || getClass() != obj.getClass()) {
+      return false;
+    }
+    JsonPrimitive other = (JsonPrimitive)obj;
+    if (value == null) {
+      return other.value == null;
+    }
+    if (isIntegral(this) && isIntegral(other)) {
+      return getAsNumber().longValue() == other.getAsNumber().longValue();
+    }
+    if (value instanceof Number && other.value instanceof Number) {
+      double a = getAsNumber().doubleValue();
+      // Java standard types other than double return true for two NaN. So, need
+      // special handling for double.
+      double b = other.getAsNumber().doubleValue();
+      return a == b || (Double.isNaN(a) && Double.isNaN(b));
+    }
+    return value.equals(other.value);
+  }
+
+  /**
+   * Returns true if the specified number is an integral type
+   * (Long, Integer, Short, Byte, BigInteger)
+   */
+  private static boolean isIntegral(JsonPrimitive primitive) {
+    if (primitive.value instanceof Number) {
+      Number number = (Number) primitive.value;
+      return number instanceof BigInteger || number instanceof Long || number instanceof Integer
+          || number instanceof Short || number instanceof Byte;
+    }
+    return false;
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/JsonSerializationContext.java b/gson/src/main/java/com/google/gson/JsonSerializationContext.java
new file mode 100644
index 0000000..ca3ec4f
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/JsonSerializationContext.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import java.lang.reflect.Type;
+
+/**
+ * Context for serialization that is passed to a custom serializer during invocation of its
+ * {@link JsonSerializer#serialize(Object, Type, JsonSerializationContext)} method.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public interface JsonSerializationContext {
+
+  /**
+   * Invokes default serialization on the specified object.
+   *
+   * @param src the object that needs to be serialized.
+   * @return a tree of {@link JsonElement}s corresponding to the serialized form of {@code src}.
+   */
+  public JsonElement serialize(Object src);
+
+  /**
+   * Invokes default serialization on the specified object passing the specific type information.
+   * It should never be invoked on the element received as a parameter of the
+   * {@link JsonSerializer#serialize(Object, Type, JsonSerializationContext)} method. Doing
+   * so will result in an infinite loop since Gson will in-turn call the custom serializer again.
+   *
+   * @param src the object that needs to be serialized.
+   * @param typeOfSrc the actual genericized type of src object.
+   * @return a tree of {@link JsonElement}s corresponding to the serialized form of {@code src}.
+   */
+  public JsonElement serialize(Object src, Type typeOfSrc);
+}
diff --git a/gson/src/main/java/com/google/gson/JsonSerializer.java b/gson/src/main/java/com/google/gson/JsonSerializer.java
new file mode 100644
index 0000000..19eaf17
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/JsonSerializer.java
@@ -0,0 +1,89 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import java.lang.reflect.Type;
+
+/**
+ * Interface representing a custom serializer for Json. You should write a custom serializer, if
+ * you are not happy with the default serialization done by Gson. You will also need to register
+ * this serializer through {@link com.google.gson.GsonBuilder#registerTypeAdapter(Type, Object)}.
+ *
+ * <p>Let us look at example where defining a serializer will be useful. The {@code Id} class
+ * defined below has two fields: {@code clazz} and {@code value}.</p>
+ *
+ * <pre>
+ * public class Id&lt;T&gt; {
+ *   private final Class&lt;T&gt; clazz;
+ *   private final long value;
+ *
+ *   public Id(Class&lt;T&gt; clazz, long value) {
+ *     this.clazz = clazz;
+ *     this.value = value;
+ *   }
+ *
+ *   public long getValue() {
+ *     return value;
+ *   }
+ * }
+ * </pre>
+ *
+ * <p>The default serialization of {@code Id(com.foo.MyObject.class, 20L)} will be
+ * <code>{"clazz":com.foo.MyObject,"value":20}</code>. Suppose, you just want the output to be
+ * the value instead, which is {@code 20} in this case. You can achieve that by writing a custom
+ * serializer:</p>
+ *
+ * <pre>
+ * class IdSerializer implements JsonSerializer&lt;Id&gt;() {
+ *   public JsonElement serialize(Id id, Type typeOfId, JsonSerializationContext context) {
+ *     return new JsonPrimitive(id.getValue());
+ *   }
+ * }
+ * </pre>
+ *
+ * <p>You will also need to register {@code IdSerializer} with Gson as follows:</p>
+ * <pre>
+ * Gson gson = new GsonBuilder().registerTypeAdapter(Id.class, new IdSerializer()).create();
+ * </pre>
+ *
+ * <p>New applications should prefer {@link TypeAdapter}, whose streaming API
+ * is more efficient than this interface's tree API.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ *
+ * @param <T> type for which the serializer is being registered. It is possible that a serializer
+ *        may be asked to serialize a specific generic type of the T.
+ */
+public interface JsonSerializer<T> {
+
+  /**
+   * Gson invokes this call-back method during serialization when it encounters a field of the
+   * specified type.
+   *
+   * <p>In the implementation of this call-back method, you should consider invoking
+   * {@link JsonSerializationContext#serialize(Object, Type)} method to create JsonElements for any
+   * non-trivial field of the {@code src} object. However, you should never invoke it on the
+   * {@code src} object itself since that will cause an infinite loop (Gson will call your
+   * call-back method again).</p>
+   *
+   * @param src the object that needs to be converted to Json.
+   * @param typeOfSrc the actual type (fully genericized version) of the source object.
+   * @return a JsonElement corresponding to the specified object.
+   */
+  public JsonElement serialize(T src, Type typeOfSrc, JsonSerializationContext context);
+}
diff --git a/gson/src/main/java/com/google/gson/JsonStreamParser.java b/gson/src/main/java/com/google/gson/JsonStreamParser.java
new file mode 100644
index 0000000..27597da
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/JsonStreamParser.java
@@ -0,0 +1,129 @@
+/*
+ * Copyright (C) 2009 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.io.Reader;
+import java.io.StringReader;
+import java.util.Iterator;
+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
+ * asynchronously. The JSON data is parsed in lenient mode, see also
+ * {@link JsonReader#setLenient(boolean)}.
+ *
+ * <p>This class is conditionally thread-safe (see Item 70, Effective Java second edition). To
+ * properly use this class across multiple threads, you will need to add some external
+ * synchronization. For example:
+ * 
+ * <pre>
+ * JsonStreamParser parser = new JsonStreamParser("['first'] {'second':10} 'third'");
+ * JsonElement element;
+ * synchronized (parser) {  // synchronize on an object shared by threads
+ *   if (parser.hasNext()) {
+ *     element = parser.next();
+ *   }
+ * }
+ * </pre>
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ * @since 1.4
+ */
+public final class JsonStreamParser implements Iterator<JsonElement> {
+  private final JsonReader parser;
+  private final Object lock;
+
+  /**
+   * @param json The string containing JSON elements concatenated to each other.
+   * @since 1.4
+   */
+  public JsonStreamParser(String json) {
+    this(new StringReader(json));
+  }
+  
+  /**
+   * @param reader The data stream containing JSON elements concatenated to each other.
+   * @since 1.4
+   */
+  public JsonStreamParser(Reader reader) {
+    parser = new JsonReader(reader);
+    parser.setLenient(true);
+    lock = new Object();
+  }
+  
+  /**
+   * Returns the next available {@link JsonElement} on the reader. Throws a
+   * {@link NoSuchElementException} if no element is available.
+   *
+   * @return the next available {@code JsonElement} on the reader.
+   * @throws JsonSyntaxException if the incoming stream is malformed JSON.
+   * @throws NoSuchElementException if no {@code JsonElement} is available.
+   * @since 1.4
+   */
+  @Override
+  public JsonElement next() throws JsonParseException {
+    if (!hasNext()) {
+      throw new NoSuchElementException();
+    }
+    
+    try {
+      return Streams.parse(parser);
+    } catch (StackOverflowError e) {
+      throw new JsonParseException("Failed parsing JSON source to Json", e);
+    } catch (OutOfMemoryError 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
+   * @return true if a {@link JsonElement} is available on the input, false otherwise
+   * @throws JsonSyntaxException if the incoming stream is malformed JSON.
+   * @since 1.4
+   */
+  @Override
+  public boolean hasNext() {
+    synchronized (lock) {
+      try {
+        return parser.peek() != JsonToken.END_DOCUMENT;
+      } catch (MalformedJsonException e) {
+        throw new JsonSyntaxException(e);
+      } catch (IOException e) {
+        throw new JsonIOException(e);
+      }
+    }
+  }
+
+  /**
+   * This optional {@link Iterator} method is not relevant for stream parsing and hence is not
+   * implemented.
+   * @since 1.4
+   */
+  @Override
+  public void remove() {
+    throw new UnsupportedOperationException();
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/JsonSyntaxException.java b/gson/src/main/java/com/google/gson/JsonSyntaxException.java
new file mode 100644
index 0000000..17c1d3d
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/JsonSyntaxException.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) 2010 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson;
+
+/**
+ * This exception is raised when Gson attempts to read (or write) a malformed
+ * JSON element.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public final class JsonSyntaxException extends JsonParseException {
+
+  private static final long serialVersionUID = 1L;
+
+  public JsonSyntaxException(String msg) {
+    super(msg);
+  }
+
+  public JsonSyntaxException(String msg, Throwable cause) {
+    super(msg, cause);
+  }
+
+  /**
+   * Creates exception with the specified cause. Consider using
+   * {@link #JsonSyntaxException(String, Throwable)} instead if you can
+   * describe what actually happened.
+   *
+   * @param cause root exception that caused this exception to be thrown.
+   */
+  public JsonSyntaxException(Throwable cause) {
+    super(cause);
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/LongSerializationPolicy.java b/gson/src/main/java/com/google/gson/LongSerializationPolicy.java
new file mode 100644
index 0000000..3cc9c72
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/LongSerializationPolicy.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2009 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+/**
+ * Defines the expected format for a {@code long} or {@code Long} type when it is serialized.
+ *
+ * @since 1.3
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public enum LongSerializationPolicy {
+  /**
+   * This is the "default" serialization policy that will output a {@code Long} object as a JSON
+   * number. For example, assume an object has a long field named "f" then the serialized output
+   * would be:
+   * {@code {"f":123}}
+   *
+   * <p>A {@code null} value is serialized as {@link JsonNull}.
+   */
+  DEFAULT() {
+    @Override public JsonElement serialize(Long value) {
+      if (value == null) {
+        return JsonNull.INSTANCE;
+      }
+      return new JsonPrimitive(value);
+    }
+  },
+  
+  /**
+   * Serializes a long value as a quoted string. For example, assume an object has a long field 
+   * named "f" then the serialized output would be:
+   * {@code {"f":"123"}}
+   *
+   * <p>A {@code null} value is serialized as {@link JsonNull}.
+   */
+  STRING() {
+    @Override public JsonElement serialize(Long value) {
+      if (value == null) {
+        return JsonNull.INSTANCE;
+      }
+      return new JsonPrimitive(value.toString());
+    }
+  };
+  
+  /**
+   * Serialize this {@code value} using this serialization policy.
+   *
+   * @param value the long value to be serialized into a {@link JsonElement}
+   * @return the serialized version of {@code value}
+   */
+  public abstract JsonElement serialize(Long value);
+}
diff --git a/gson/src/main/java/com/google/gson/ReflectionAccessFilter.java b/gson/src/main/java/com/google/gson/ReflectionAccessFilter.java
new file mode 100644
index 0000000..b787ae8
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/ReflectionAccessFilter.java
@@ -0,0 +1,194 @@
+package com.google.gson;
+
+import java.lang.reflect.AccessibleObject;
+
+import com.google.gson.internal.ReflectionAccessFilterHelper;
+
+/**
+ * Filter for determining whether reflection based serialization and
+ * deserialization is allowed for a class.
+ *
+ * <p>A filter can be useful in multiple scenarios, for example when
+ * upgrading to newer Java versions which use the Java Platform Module
+ * System (JPMS). A filter then allows to {@linkplain FilterResult#BLOCK_INACCESSIBLE
+ * prevent making inaccessible members accessible}, even if the used
+ * Java version might still allow illegal access (but logs a warning),
+ * or if {@code java} command line arguments are used to open the inaccessible
+ * packages to other parts of the application. This interface defines some
+ * convenience filters for this task, such as {@link #BLOCK_INACCESSIBLE_JAVA}.
+ *
+ * <p>A filter can also be useful to prevent mixing model classes of a
+ * project with other non-model classes; the filter could
+ * {@linkplain FilterResult#BLOCK_ALL block all reflective access} to
+ * non-model classes.
+ *
+ * <p>A reflection access filter is similar to an {@link ExclusionStrategy}
+ * with the major difference that a filter will cause an exception to be
+ * thrown when access is disallowed while an exclusion strategy just skips
+ * fields and classes.
+ *
+ * @see GsonBuilder#addReflectionAccessFilter(ReflectionAccessFilter)
+ */
+public interface ReflectionAccessFilter {
+  /**
+   * Result of a filter check.
+   */
+  enum FilterResult {
+    /**
+     * Reflection access for the class is allowed.
+     *
+     * <p>Note that this does not affect the Java access checks in any way,
+     * it only permits Gson to try using reflection for a class. The Java
+     * runtime might still deny such access.
+     */
+    ALLOW,
+    /**
+     * The filter is indecisive whether reflection access should be allowed.
+     * The next registered filter will be consulted to get the result. If
+     * there is no next filter, this result acts like {@link #ALLOW}.
+     */
+    INDECISIVE,
+    /**
+     * Blocks reflection access if a member of the class is not accessible
+     * by default and would have to be made accessible. This is unaffected
+     * by any {@code java} command line arguments being used to make packages
+     * accessible, or by module declaration directives which <i>open</i> the
+     * complete module or certain packages for reflection and will consider
+     * such packages inaccessible.
+     *
+     * <p>Note that this <b>only works for Java 9 and higher</b>, for older
+     * Java versions its functionality will be limited and it might behave like
+     * {@link #ALLOW}. Access checks are only performed as defined by the Java
+     * Language Specification (<a href="https://docs.oracle.com/javase/specs/jls/se11/html/jls-6.html#jls-6.6">JLS 11 &sect;6.6</a>),
+     * restrictions imposed by a {@link SecurityManager} are not considered.
+     *
+     * <p>This result type is mainly intended to help enforce the access checks of
+     * the Java Platform Module System. It allows detecting illegal access, even if
+     * the used Java version would only log a warning, or is configured to open
+     * packages for reflection using command line arguments.
+     *
+     * @see AccessibleObject#canAccess(Object)
+     */
+    BLOCK_INACCESSIBLE,
+    /**
+     * Blocks all reflection access for the class. Other means for serializing
+     * and deserializing the class, such as a {@link TypeAdapter}, have to
+     * be used.
+     */
+    BLOCK_ALL
+  }
+
+  /**
+   * Blocks all reflection access to members of standard Java classes which are
+   * not accessible by default. However, reflection access is still allowed for
+   * classes for which all fields are accessible and which have an accessible
+   * no-args constructor (or for which an {@link InstanceCreator} has been registered).
+   *
+   * <p>If this filter encounters a class other than a standard Java class it
+   * returns {@link FilterResult#INDECISIVE}.
+   *
+   * <p>This filter is mainly intended to help enforcing the access checks of
+   * Java Platform Module System. It allows detecting illegal access, even if
+   * the used Java version would only log a warning, or is configured to open
+   * packages for reflection. However, this filter <b>only works for Java 9 and
+   * higher</b>, when using an older Java version its functionality will be
+   * limited.
+   *
+   * <p>Note that this filter might not cover all standard Java classes. Currently
+   * only classes in a {@code java.*} or {@code javax.*} package are considered. The
+   * set of detected classes might be expanded in the future without prior notice.
+   *
+   * @see FilterResult#BLOCK_INACCESSIBLE
+   */
+  ReflectionAccessFilter BLOCK_INACCESSIBLE_JAVA = new ReflectionAccessFilter() {
+    @Override public FilterResult check(Class<?> rawClass) {
+      return ReflectionAccessFilterHelper.isJavaType(rawClass)
+        ? FilterResult.BLOCK_INACCESSIBLE
+        : FilterResult.INDECISIVE;
+    }
+  };
+
+  /**
+   * Blocks all reflection access to members of standard Java classes.
+   *
+   * <p>If this filter encounters a class other than a standard Java class it
+   * returns {@link FilterResult#INDECISIVE}.
+   *
+   * <p>This filter is mainly intended to prevent depending on implementation
+   * details of the Java platform and to help applications prepare for upgrading
+   * to the Java Platform Module System.
+   *
+   * <p>Note that this filter might not cover all standard Java classes. Currently
+   * only classes in a {@code java.*} or {@code javax.*} package are considered. The
+   * set of detected classes might be expanded in the future without prior notice.
+   *
+   * @see #BLOCK_INACCESSIBLE_JAVA
+   * @see FilterResult#BLOCK_ALL
+   */
+  ReflectionAccessFilter BLOCK_ALL_JAVA = new ReflectionAccessFilter() {
+    @Override public FilterResult check(Class<?> rawClass) {
+      return ReflectionAccessFilterHelper.isJavaType(rawClass)
+        ? FilterResult.BLOCK_ALL
+        : FilterResult.INDECISIVE;
+    }
+  };
+
+  /**
+   * Blocks all reflection access to members of standard Android classes.
+   *
+   * <p>If this filter encounters a class other than a standard Android class it
+   * returns {@link FilterResult#INDECISIVE}.
+   *
+   * <p>This filter is mainly intended to prevent depending on implementation
+   * details of the Android platform.
+   *
+   * <p>Note that this filter might not cover all standard Android classes. Currently
+   * only classes in an {@code android.*} or {@code androidx.*} package, and standard
+   * Java classes in a {@code java.*} or {@code javax.*} package are considered. The
+   * set of detected classes might be expanded in the future without prior notice.
+   *
+   * @see FilterResult#BLOCK_ALL
+   */
+  ReflectionAccessFilter BLOCK_ALL_ANDROID = new ReflectionAccessFilter() {
+    @Override public FilterResult check(Class<?> rawClass) {
+      return ReflectionAccessFilterHelper.isAndroidType(rawClass)
+        ? FilterResult.BLOCK_ALL
+        : FilterResult.INDECISIVE;
+    }
+  };
+
+  /**
+   * Blocks all reflection access to members of classes belonging to programming
+   * language platforms, such as Java, Android, Kotlin or Scala.
+   *
+   * <p>If this filter encounters a class other than a standard platform class it
+   * returns {@link FilterResult#INDECISIVE}.
+   *
+   * <p>This filter is mainly intended to prevent depending on implementation
+   * details of the platform classes.
+   *
+   * <p>Note that this filter might not cover all platform classes. Currently it
+   * combines the filters {@link #BLOCK_ALL_JAVA} and {@link #BLOCK_ALL_ANDROID},
+   * and checks for other language-specific platform classes like {@code kotlin.*}.
+   * The set of detected classes might be expanded in the future without prior notice.
+   *
+   * @see FilterResult#BLOCK_ALL
+   */
+  ReflectionAccessFilter BLOCK_ALL_PLATFORM = new ReflectionAccessFilter() {
+    @Override public FilterResult check(Class<?> rawClass) {
+      return ReflectionAccessFilterHelper.isAnyPlatformType(rawClass)
+        ? FilterResult.BLOCK_ALL
+        : FilterResult.INDECISIVE;
+    }
+  };
+
+  /**
+   * Checks if reflection access should be allowed for a class.
+   *
+   * @param rawClass
+   *    Class to check
+   * @return
+   *    Result indicating whether reflection access is allowed
+   */
+  FilterResult check(Class<?> rawClass);
+}
diff --git a/gson/src/main/java/com/google/gson/ToNumberPolicy.java b/gson/src/main/java/com/google/gson/ToNumberPolicy.java
new file mode 100644
index 0000000..bd70213
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/ToNumberPolicy.java
@@ -0,0 +1,99 @@
+/*
+ * Copyright (C) 2021 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import java.io.IOException;
+import java.math.BigDecimal;
+
+import com.google.gson.internal.LazilyParsedNumber;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.MalformedJsonException;
+
+/**
+ * An enumeration that defines two standard number reading strategies and a couple of
+ * strategies to overcome some historical Gson limitations while deserializing numbers as
+ * {@link Object} and {@link Number}.
+ *
+ * @see ToNumberStrategy
+ */
+public enum ToNumberPolicy implements ToNumberStrategy {
+
+  /**
+   * Using this policy will ensure that numbers will be read as {@link Double} values.
+   * This is the default strategy used during deserialization of numbers as {@link Object}.
+   */
+  DOUBLE {
+    @Override public Double readNumber(JsonReader in) throws IOException {
+      return in.nextDouble();
+    }
+  },
+
+  /**
+   * Using this policy will ensure that numbers will be read as a lazily parsed number backed
+   * by a string. This is the default strategy used during deserialization of numbers as
+   * {@link Number}.
+   */
+  LAZILY_PARSED_NUMBER {
+    @Override public Number readNumber(JsonReader in) throws IOException {
+      return new LazilyParsedNumber(in.nextString());
+    }
+  },
+
+  /**
+   * Using this policy will ensure that numbers will be read as {@link Long} or {@link Double}
+   * values depending on how JSON numbers are represented: {@code Long} if the JSON number can
+   * be parsed as a {@code Long} value, or otherwise {@code Double} if it can be parsed as a
+   * {@code Double} value. If the parsed double-precision number results in a positive or negative
+   * infinity ({@link Double#isInfinite()}) or a NaN ({@link Double#isNaN()}) value and the
+   * {@code JsonReader} is not {@link JsonReader#isLenient() lenient}, a {@link MalformedJsonException}
+   * is thrown.
+   */
+  LONG_OR_DOUBLE {
+    @Override public Number readNumber(JsonReader in) throws IOException, JsonParseException {
+      String value = in.nextString();
+      try {
+        return Long.parseLong(value);
+      } catch (NumberFormatException longE) {
+        try {
+          Double d = Double.valueOf(value);
+          if ((d.isInfinite() || d.isNaN()) && !in.isLenient()) {
+            throw new MalformedJsonException("JSON forbids NaN and infinities: " + d + "; at path " + in.getPreviousPath());
+          }
+          return d;
+        } catch (NumberFormatException doubleE) {
+          throw new JsonParseException("Cannot parse " + value + "; at path " + in.getPreviousPath(), doubleE);
+        }
+      }
+    }
+  },
+
+  /**
+   * Using this policy will ensure that numbers will be read as numbers of arbitrary length
+   * using {@link BigDecimal}.
+   */
+  BIG_DECIMAL {
+    @Override public BigDecimal readNumber(JsonReader in) throws IOException {
+      String value = in.nextString();
+      try {
+        return new BigDecimal(value);
+      } catch (NumberFormatException e) {
+        throw new JsonParseException("Cannot parse " + value + "; at path " + in.getPreviousPath(), e);
+      }
+    }
+  }
+
+}
diff --git a/gson/src/main/java/com/google/gson/ToNumberStrategy.java b/gson/src/main/java/com/google/gson/ToNumberStrategy.java
new file mode 100644
index 0000000..3cd84fa
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/ToNumberStrategy.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2021 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import java.io.IOException;
+
+import com.google.gson.stream.JsonReader;
+
+/**
+ * A strategy that is used to control how numbers should be deserialized for {@link Object} and {@link Number}
+ * when a concrete type of the deserialized number is unknown in advance. By default, Gson uses the following
+ * deserialization strategies:
+ *
+ * <ul>
+ * <li>{@link Double} values are returned for JSON numbers if the deserialization type is declared as
+ * {@code Object}, see {@link ToNumberPolicy#DOUBLE};</li>
+ * <li>Lazily parsed number values are returned if the deserialization type is declared as {@code Number},
+ * see {@link ToNumberPolicy#LAZILY_PARSED_NUMBER}.</li>
+ * </ul>
+ *
+ * <p>For historical reasons, Gson does not support deserialization of arbitrary-length numbers for
+ * {@code Object} and {@code Number} by default, potentially causing precision loss. However,
+ * <a href="https://tools.ietf.org/html/rfc8259#section-6">RFC 8259</a> permits this:
+ *
+ * <pre>
+ *   This specification allows implementations to set limits on the range
+ *   and precision of numbers accepted.  Since software that implements
+ *   IEEE 754 binary64 (double precision) numbers [IEEE754] is generally
+ *   available and widely used, good interoperability can be achieved by
+ *   implementations that expect no more precision or range than these
+ *   provide, in the sense that implementations will approximate JSON
+ *   numbers within the expected precision.  A JSON number such as 1E400
+ *   or 3.141592653589793238462643383279 may indicate potential
+ *   interoperability problems, since it suggests that the software that
+ *   created it expects receiving software to have greater capabilities
+ *   for numeric magnitude and precision than is widely available.
+ * </pre>
+ *
+ * <p>To overcome the precision loss, use for example {@link ToNumberPolicy#LONG_OR_DOUBLE} or
+ * {@link ToNumberPolicy#BIG_DECIMAL}.</p>
+ *
+ * @see ToNumberPolicy
+ * @see GsonBuilder#setObjectToNumberStrategy(ToNumberStrategy)
+ * @see GsonBuilder#setNumberToNumberStrategy(ToNumberStrategy)
+ */
+public interface ToNumberStrategy {
+
+  /**
+   * Reads a number from the given JSON reader. A strategy is supposed to read a single value from the
+   * reader, and the read value is guaranteed never to be {@code null}.
+   *
+   * @param in JSON reader to read a number from
+   * @return number read from the JSON reader.
+   */
+  public Number readNumber(JsonReader in) throws IOException;
+}
diff --git a/gson/src/main/java/com/google/gson/TypeAdapter.java b/gson/src/main/java/com/google/gson/TypeAdapter.java
new file mode 100644
index 0000000..ba79853
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/TypeAdapter.java
@@ -0,0 +1,297 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import com.google.gson.internal.bind.JsonTreeReader;
+import com.google.gson.internal.bind.JsonTreeWriter;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonToken;
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
+import java.io.Reader;
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.io.Writer;
+
+/**
+ * Converts Java objects to and from JSON.
+ *
+ * <h3>Defining a type's JSON form</h3>
+ * By default Gson converts application classes to JSON using its built-in type
+ * adapters. If Gson's default JSON conversion isn't appropriate for a type,
+ * extend this class to customize the conversion. Here's an example of a type
+ * adapter for an (X,Y) coordinate point: <pre>   {@code
+ *
+ *   public class PointAdapter extends TypeAdapter<Point> {
+ *     public Point read(JsonReader reader) throws IOException {
+ *       if (reader.peek() == JsonToken.NULL) {
+ *         reader.nextNull();
+ *         return null;
+ *       }
+ *       String xy = reader.nextString();
+ *       String[] parts = xy.split(",");
+ *       int x = Integer.parseInt(parts[0]);
+ *       int y = Integer.parseInt(parts[1]);
+ *       return new Point(x, y);
+ *     }
+ *     public void write(JsonWriter writer, Point value) throws IOException {
+ *       if (value == null) {
+ *         writer.nullValue();
+ *         return;
+ *       }
+ *       String xy = value.getX() + "," + value.getY();
+ *       writer.value(xy);
+ *     }
+ *   }}</pre>
+ * With this type adapter installed, Gson will convert {@code Points} to JSON as
+ * strings like {@code "5,8"} rather than objects like {@code {"x":5,"y":8}}. In
+ * this case the type adapter binds a rich Java class to a compact JSON value.
+ *
+ * <p>The {@link #read(JsonReader) read()} method must read exactly one value
+ * and {@link #write(JsonWriter,Object) write()} must write exactly one value.
+ * For primitive types this is means readers should make exactly one call to
+ * {@code nextBoolean()}, {@code nextDouble()}, {@code nextInt()}, {@code
+ * nextLong()}, {@code nextString()} or {@code nextNull()}. Writers should make
+ * exactly one call to one of <code>value()</code> or <code>nullValue()</code>.
+ * For arrays, type adapters should start with a call to {@code beginArray()},
+ * convert all elements, and finish with a call to {@code endArray()}. For
+ * objects, they should start with {@code beginObject()}, convert the object,
+ * and finish with {@code endObject()}. Failing to convert a value or converting
+ * too many values may cause the application to crash.
+ *
+ * <p>Type adapters should be prepared to read null from the stream and write it
+ * to the stream. Alternatively, they should use {@link #nullSafe()} method while
+ * registering the type adapter with Gson. If your {@code Gson} instance
+ * has been configured to {@link GsonBuilder#serializeNulls()}, these nulls will be
+ * written to the final document. Otherwise the value (and the corresponding name
+ * when writing to a JSON object) will be omitted automatically. In either case
+ * your type adapter must handle null.
+ *
+ * <p>To use a custom type adapter with Gson, you must <i>register</i> it with a
+ * {@link GsonBuilder}: <pre>   {@code
+ *
+ *   GsonBuilder builder = new GsonBuilder();
+ *   builder.registerTypeAdapter(Point.class, new PointAdapter());
+ *   // if PointAdapter didn't check for nulls in its read/write methods, you should instead use
+ *   // builder.registerTypeAdapter(Point.class, new PointAdapter().nullSafe());
+ *   ...
+ *   Gson gson = builder.create();
+ * }</pre>
+ *
+ * @since 2.1
+ */
+// non-Javadoc:
+//
+// <h3>JSON Conversion</h3>
+// <p>A type adapter registered with Gson is automatically invoked while serializing
+// or deserializing JSON. However, you can also use type adapters directly to serialize
+// and deserialize JSON. Here is an example for deserialization: <pre>   {@code
+//
+//   String json = "{'origin':'0,0','points':['1,2','3,4']}";
+//   TypeAdapter<Graph> graphAdapter = gson.getAdapter(Graph.class);
+//   Graph graph = graphAdapter.fromJson(json);
+// }</pre>
+// And an example for serialization: <pre>   {@code
+//
+//   Graph graph = new Graph(...);
+//   TypeAdapter<Graph> graphAdapter = gson.getAdapter(Graph.class);
+//   String json = graphAdapter.toJson(graph);
+// }</pre>
+//
+// <p>Type adapters are <strong>type-specific</strong>. For example, a {@code
+// TypeAdapter<Date>} can convert {@code Date} instances to JSON and JSON to
+// instances of {@code Date}, but cannot convert any other types.
+//
+public abstract class TypeAdapter<T> {
+
+  /**
+   * Writes one JSON value (an array, object, string, number, boolean or null)
+   * for {@code value}.
+   *
+   * @param value the Java object to write. May be null.
+   */
+  public abstract void write(JsonWriter out, T value) throws IOException;
+
+  /**
+   * Converts {@code value} to a JSON document and writes it to {@code out}.
+   * Unlike Gson's similar {@link Gson#toJson(JsonElement, Appendable) toJson}
+   * method, this write is strict. Create a {@link
+   * JsonWriter#setLenient(boolean) lenient} {@code JsonWriter} and call
+   * {@link #write(com.google.gson.stream.JsonWriter, Object)} for lenient
+   * writing.
+   *
+   * @param value the Java object to convert. May be null.
+   * @since 2.2
+   */
+  public final void toJson(Writer out, T value) throws IOException {
+    JsonWriter writer = new JsonWriter(out);
+    write(writer, value);
+  }
+
+  /**
+   * This wrapper method is used to make a type adapter null tolerant. In general, a
+   * type adapter is required to handle nulls in write and read methods. Here is how this
+   * is typically done:<br>
+   * <pre>   {@code
+   *
+   * Gson gson = new GsonBuilder().registerTypeAdapter(Foo.class,
+   *   new TypeAdapter<Foo>() {
+   *     public Foo read(JsonReader in) throws IOException {
+   *       if (in.peek() == JsonToken.NULL) {
+   *         in.nextNull();
+   *         return null;
+   *       }
+   *       // read a Foo from in and return it
+   *     }
+   *     public void write(JsonWriter out, Foo src) throws IOException {
+   *       if (src == null) {
+   *         out.nullValue();
+   *         return;
+   *       }
+   *       // write src as JSON to out
+   *     }
+   *   }).create();
+   * }</pre>
+   * You can avoid this boilerplate handling of nulls by wrapping your type adapter with
+   * this method. Here is how we will rewrite the above example:
+   * <pre>   {@code
+   *
+   * Gson gson = new GsonBuilder().registerTypeAdapter(Foo.class,
+   *   new TypeAdapter<Foo>() {
+   *     public Foo read(JsonReader in) throws IOException {
+   *       // read a Foo from in and return it
+   *     }
+   *     public void write(JsonWriter out, Foo src) throws IOException {
+   *       // write src as JSON to out
+   *     }
+   *   }.nullSafe()).create();
+   * }</pre>
+   * Note that we didn't need to check for nulls in our type adapter after we used nullSafe.
+   */
+  public final TypeAdapter<T> nullSafe() {
+    return new TypeAdapter<T>() {
+      @Override public void write(JsonWriter out, T value) throws IOException {
+        if (value == null) {
+          out.nullValue();
+        } else {
+          TypeAdapter.this.write(out, value);
+        }
+      }
+      @Override public T read(JsonReader reader) throws IOException {
+        if (reader.peek() == JsonToken.NULL) {
+          reader.nextNull();
+          return null;
+        }
+        return TypeAdapter.this.read(reader);
+      }
+    };
+  }
+
+  /**
+   * Converts {@code value} to a JSON document. Unlike Gson's similar {@link
+   * Gson#toJson(Object) toJson} method, this write is strict. Create a {@link
+   * JsonWriter#setLenient(boolean) lenient} {@code JsonWriter} and call
+   * {@link #write(com.google.gson.stream.JsonWriter, Object)} for lenient
+   * writing.
+   *
+   * @param value the Java object to convert. May be null.
+   * @since 2.2
+   */
+  public final String toJson(T value) {
+    StringWriter stringWriter = new StringWriter();
+    try {
+      toJson(stringWriter, value);
+    } catch (IOException e) {
+      throw new AssertionError(e); // No I/O writing to a StringWriter.
+    }
+    return stringWriter.toString();
+  }
+
+  /**
+   * Converts {@code value} to a JSON tree.
+   *
+   * @param value the Java object to convert. May be null.
+   * @return the converted JSON tree. May be {@link JsonNull}.
+   * @since 2.2
+   */
+  public final JsonElement toJsonTree(T value) {
+    try {
+      JsonTreeWriter jsonWriter = new JsonTreeWriter();
+      write(jsonWriter, value);
+      return jsonWriter.get();
+    } catch (IOException e) {
+      throw new JsonIOException(e);
+    }
+  }
+
+  /**
+   * Reads one JSON value (an array, object, string, number, boolean or null)
+   * and converts it to a Java object. Returns the converted object.
+   *
+   * @return the converted Java object. May be null.
+   */
+  public abstract T read(JsonReader in) throws IOException;
+
+  /**
+   * Converts the JSON document in {@code in} to a Java object. Unlike Gson's
+   * similar {@link Gson#fromJson(java.io.Reader, Class) fromJson} method, this
+   * read is strict. Create a {@link JsonReader#setLenient(boolean) lenient}
+   * {@code JsonReader} and call {@link #read(JsonReader)} for lenient reading.
+   *
+   * <p>No exception is thrown if the JSON data has multiple top-level JSON elements,
+   * or if there is trailing data.
+   *
+   * @return the converted Java object. May be null.
+   * @since 2.2
+   */
+  public final T fromJson(Reader in) throws IOException {
+    JsonReader reader = new JsonReader(in);
+    return read(reader);
+  }
+
+  /**
+   * Converts the JSON document in {@code json} to a Java object. Unlike Gson's
+   * similar {@link Gson#fromJson(String, Class) fromJson} method, this read is
+   * strict. Create a {@link JsonReader#setLenient(boolean) lenient} {@code
+   * JsonReader} and call {@link #read(JsonReader)} for lenient reading.
+   *
+   * <p>No exception is thrown if the JSON data has multiple top-level JSON elements,
+   * or if there is trailing data.
+   *
+   * @return the converted Java object. May be null.
+   * @since 2.2
+   */
+  public final T fromJson(String json) throws IOException {
+    return fromJson(new StringReader(json));
+  }
+
+  /**
+   * Converts {@code jsonTree} to a Java object.
+   *
+   * @param jsonTree the JSON element to convert. May be {@link JsonNull}.
+   * @return the converted Java object. May be null.
+   * @since 2.2
+   */
+  public final T fromJsonTree(JsonElement jsonTree) {
+    try {
+      JsonReader jsonReader = new JsonTreeReader(jsonTree);
+      return read(jsonReader);
+    } catch (IOException e) {
+      throw new JsonIOException(e);
+    }
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/TypeAdapterFactory.java b/gson/src/main/java/com/google/gson/TypeAdapterFactory.java
new file mode 100644
index 0000000..c12429e
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/TypeAdapterFactory.java
@@ -0,0 +1,170 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import com.google.gson.reflect.TypeToken;
+
+/**
+ * Creates type adapters for set of related types. Type adapter factories are
+ * most useful when several types share similar structure in their JSON form.
+ *
+ * <h3>Example: Converting enums to lowercase</h3>
+ * In this example, we implement a factory that creates type adapters for all
+ * enums. The type adapters will write enums in lowercase, despite the fact
+ * that they're defined in {@code CONSTANT_CASE} in the corresponding Java
+ * model: <pre>   {@code
+ *
+ *   public class LowercaseEnumTypeAdapterFactory implements TypeAdapterFactory {
+ *     public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
+ *       Class<T> rawType = (Class<T>) type.getRawType();
+ *       if (!rawType.isEnum()) {
+ *         return null;
+ *       }
+ *
+ *       final Map<String, T> lowercaseToConstant = new HashMap<>();
+ *       for (T constant : rawType.getEnumConstants()) {
+ *         lowercaseToConstant.put(toLowercase(constant), constant);
+ *       }
+ *
+ *       return new TypeAdapter<T>() {
+ *         public void write(JsonWriter out, T value) throws IOException {
+ *           if (value == null) {
+ *             out.nullValue();
+ *           } else {
+ *             out.value(toLowercase(value));
+ *           }
+ *         }
+ *
+ *         public T read(JsonReader reader) throws IOException {
+ *           if (reader.peek() == JsonToken.NULL) {
+ *             reader.nextNull();
+ *             return null;
+ *           } else {
+ *             return lowercaseToConstant.get(reader.nextString());
+ *           }
+ *         }
+ *       };
+ *     }
+ *
+ *     private String toLowercase(Object o) {
+ *       return o.toString().toLowerCase(Locale.US);
+ *     }
+ *   }
+ * }</pre>
+ *
+ * <p>Type adapter factories select which types they provide type adapters
+ * for. If a factory cannot support a given type, it must return null when
+ * that type is passed to {@link #create}. Factories should expect {@code
+ * create()} to be called on them for many types and should return null for
+ * most of those types. In the above example the factory returns null for
+ * calls to {@code create()} where {@code type} is not an enum.
+ *
+ * <p>A factory is typically called once per type, but the returned type
+ * adapter may be used many times. It is most efficient to do expensive work
+ * like reflection in {@code create()} so that the type adapter's {@code
+ * read()} and {@code write()} methods can be very fast. In this example the
+ * mapping from lowercase name to enum value is computed eagerly.
+ *
+ * <p>As with type adapters, factories must be <i>registered</i> with a {@link
+ * com.google.gson.GsonBuilder} for them to take effect: <pre>   {@code
+ *
+ *  GsonBuilder builder = new GsonBuilder();
+ *  builder.registerTypeAdapterFactory(new LowercaseEnumTypeAdapterFactory());
+ *  ...
+ *  Gson gson = builder.create();
+ * }</pre>
+ * If multiple factories support the same type, the factory registered earlier
+ * takes precedence.
+ *
+ * <h3>Example: composing other type adapters</h3>
+ * In this example we implement a factory for Guava's {@code Multiset}
+ * collection type. The factory can be used to create type adapters for
+ * multisets of any element type: the type adapter for {@code
+ * Multiset<String>} is different from the type adapter for {@code
+ * Multiset<URL>}.
+ *
+ * <p>The type adapter <i>delegates</i> to another type adapter for the
+ * multiset elements. It figures out the element type by reflecting on the
+ * multiset's type token. A {@code Gson} is passed in to {@code create} for
+ * just this purpose: <pre>   {@code
+ *
+ *   public class MultisetTypeAdapterFactory implements TypeAdapterFactory {
+ *     public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
+ *       Type type = typeToken.getType();
+ *       if (typeToken.getRawType() != Multiset.class
+ *           || !(type instanceof ParameterizedType)) {
+ *         return null;
+ *       }
+ *
+ *       Type elementType = ((ParameterizedType) type).getActualTypeArguments()[0];
+ *       TypeAdapter<?> elementAdapter = gson.getAdapter(TypeToken.get(elementType));
+ *       return (TypeAdapter<T>) newMultisetAdapter(elementAdapter);
+ *     }
+ *
+ *     private <E> TypeAdapter<Multiset<E>> newMultisetAdapter(
+ *         final TypeAdapter<E> elementAdapter) {
+ *       return new TypeAdapter<Multiset<E>>() {
+ *         public void write(JsonWriter out, Multiset<E> value) throws IOException {
+ *           if (value == null) {
+ *             out.nullValue();
+ *             return;
+ *           }
+ *
+ *           out.beginArray();
+ *           for (Multiset.Entry<E> entry : value.entrySet()) {
+ *             out.value(entry.getCount());
+ *             elementAdapter.write(out, entry.getElement());
+ *           }
+ *           out.endArray();
+ *         }
+ *
+ *         public Multiset<E> read(JsonReader in) throws IOException {
+ *           if (in.peek() == JsonToken.NULL) {
+ *             in.nextNull();
+ *             return null;
+ *           }
+ *
+ *           Multiset<E> result = LinkedHashMultiset.create();
+ *           in.beginArray();
+ *           while (in.hasNext()) {
+ *             int count = in.nextInt();
+ *             E element = elementAdapter.read(in);
+ *             result.add(element, count);
+ *           }
+ *           in.endArray();
+ *           return result;
+ *         }
+ *       };
+ *     }
+ *   }
+ * }</pre>
+ * Delegating from one type adapter to another is extremely powerful; it's
+ * the foundation of how Gson converts Java objects and collections. Whenever
+ * possible your factory should retrieve its delegate type adapter in the
+ * {@code create()} method; this ensures potentially-expensive type adapter
+ * creation happens only once.
+ *
+ * @since 2.1
+ */
+public interface TypeAdapterFactory {
+
+  /**
+   * Returns a type adapter for {@code type}, or null if this factory doesn't
+   * support {@code type}.
+   */
+  <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type);
+}
diff --git a/gson/src/main/java/com/google/gson/annotations/Expose.java b/gson/src/main/java/com/google/gson/annotations/Expose.java
new file mode 100644
index 0000000..966460d
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/annotations/Expose.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.annotations;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * An annotation that indicates this member should be exposed for JSON
+ * serialization or deserialization.
+ *
+ * <p>This annotation has no effect unless you build {@link com.google.gson.Gson}
+ * with a {@link com.google.gson.GsonBuilder} and invoke
+ * {@link com.google.gson.GsonBuilder#excludeFieldsWithoutExposeAnnotation()}
+ * method.</p>
+ *
+ * <p>Here is an example of how this annotation is meant to be used:
+ * <pre>
+ * public class User {
+ *   &#64;Expose private String firstName;
+ *   &#64;Expose(serialize = false) private String lastName;
+ *   &#64;Expose (serialize = false, deserialize = false) private String emailAddress;
+ *   private String password;
+ * }
+ * </pre>
+ * If you created Gson with {@code new Gson()}, the {@code toJson()} and {@code fromJson()}
+ * methods will use the {@code password} field along-with {@code firstName}, {@code lastName},
+ * and {@code emailAddress} for serialization and deserialization. However, if you created Gson
+ * with {@code Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()}
+ * then the {@code toJson()} and {@code fromJson()} methods of Gson will exclude the
+ * {@code password} field. This is because the {@code password} field is not marked with the
+ * {@code @Expose} annotation. Gson will also exclude {@code lastName} and {@code emailAddress}
+ * from serialization since {@code serialize} is set to {@code false}. Similarly, Gson will
+ * exclude {@code emailAddress} from deserialization since {@code deserialize} is set to false.
+ *
+ * <p>Note that another way to achieve the same effect would have been to just mark the
+ * {@code password} field as {@code transient}, and Gson would have excluded it even with default
+ * settings. The {@code @Expose} annotation is useful in a style of programming where you want to
+ * explicitly specify all fields that should get considered for serialization or deserialization.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+@Documented
+@Retention(RetentionPolicy.RUNTIME)
+@Target(ElementType.FIELD)
+public @interface Expose {
+  
+  /**
+   * If {@code true}, the field marked with this annotation is written out in the JSON while
+   * serializing. If {@code false}, the field marked with this annotation is skipped from the
+   * serialized output. Defaults to {@code true}.
+   * @since 1.4
+   */
+  public boolean serialize() default true;
+
+  /**
+   * If {@code true}, the field marked with this annotation is deserialized from the JSON.
+   * If {@code false}, the field marked with this annotation is skipped during deserialization. 
+   * Defaults to {@code true}.
+   * @since 1.4
+   */
+  public boolean deserialize() default true;
+}
diff --git a/gson/src/main/java/com/google/gson/annotations/JsonAdapter.java b/gson/src/main/java/com/google/gson/annotations/JsonAdapter.java
new file mode 100644
index 0000000..a01d77a
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/annotations/JsonAdapter.java
@@ -0,0 +1,104 @@
+/*
+ * Copyright (C) 2014 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.annotations;
+
+import com.google.gson.JsonDeserializer;
+import com.google.gson.JsonSerializer;
+import com.google.gson.TypeAdapter;
+import com.google.gson.TypeAdapterFactory;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * An annotation that indicates the Gson {@link TypeAdapter} to use with a class
+ * or field.
+ *
+ * <p>Here is an example of how this annotation is used:</p>
+ * <pre>
+ * &#64;JsonAdapter(UserJsonAdapter.class)
+ * public class User {
+ *   public final String firstName, lastName;
+ *   private User(String firstName, String lastName) {
+ *     this.firstName = firstName;
+ *     this.lastName = lastName;
+ *   }
+ * }
+ * public class UserJsonAdapter extends TypeAdapter&lt;User&gt; {
+ *   &#64;Override public void write(JsonWriter out, User user) throws IOException {
+ *     // implement write: combine firstName and lastName into name
+ *     out.beginObject();
+ *     out.name("name");
+ *     out.value(user.firstName + " " + user.lastName);
+ *     out.endObject();
+ *     // implement the write method
+ *   }
+ *   &#64;Override public User read(JsonReader in) throws IOException {
+ *     // implement read: split name into firstName and lastName
+ *     in.beginObject();
+ *     in.nextName();
+ *     String[] nameParts = in.nextString().split(" ");
+ *     in.endObject();
+ *     return new User(nameParts[0], nameParts[1]);
+ *   }
+ * }
+ * </pre>
+ *
+ * Since User class specified UserJsonAdapter.class in &#64;JsonAdapter annotation, it
+ * will automatically be invoked to serialize/deserialize User instances. <br>
+ *
+ * <p> Here is an example of how to apply this annotation to a field.
+ * <pre>
+ * private static final class Gadget {
+ *   &#64;JsonAdapter(UserJsonAdapter2.class)
+ *   final User user;
+ *   Gadget(User user) {
+ *     this.user = user;
+ *   }
+ * }
+ * </pre>
+ *
+ * It's possible to specify different type adapters on a field, that
+ * field's type, and in the {@link com.google.gson.GsonBuilder}. Field
+ * annotations take precedence over {@code GsonBuilder}-registered type
+ * adapters, which in turn take precedence over annotated types.
+ *
+ * <p>The class referenced by this annotation must be either a {@link
+ * TypeAdapter} or a {@link TypeAdapterFactory}, or must implement one
+ * or both of {@link JsonDeserializer} or {@link JsonSerializer}. 
+ * Using {@link TypeAdapterFactory} makes it possible to delegate 
+ * to the enclosing {@code Gson} instance.
+ *
+ * @since 2.3
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ * @author Jesse Wilson
+ */
+// Note that the above example is taken from AdaptAnnotationTest.
+@Retention(RetentionPolicy.RUNTIME)
+@Target({ElementType.TYPE, ElementType.FIELD})
+public @interface JsonAdapter {
+
+  /** Either a {@link TypeAdapter} or {@link TypeAdapterFactory}, or one or both of {@link JsonDeserializer} or {@link JsonSerializer}. */
+  Class<?> value();
+
+  /** false, to be able to handle {@code null} values within the adapter, default value is true. */
+  boolean nullSafe() default true;
+
+}
diff --git a/gson/src/main/java/com/google/gson/annotations/SerializedName.java b/gson/src/main/java/com/google/gson/annotations/SerializedName.java
new file mode 100644
index 0000000..e50ad55
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/annotations/SerializedName.java
@@ -0,0 +1,93 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.annotations;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * An annotation that indicates this member should be serialized to JSON with
+ * the provided name value as its field name.
+ *
+ * <p>This annotation will override any {@link com.google.gson.FieldNamingPolicy}, including
+ * the default field naming policy, that may have been set on the {@link com.google.gson.Gson}
+ * instance. A different naming policy can set using the {@code GsonBuilder} class. See
+ * {@link com.google.gson.GsonBuilder#setFieldNamingPolicy(com.google.gson.FieldNamingPolicy)}
+ * for more information.</p>
+ *
+ * <p>Here is an example of how this annotation is meant to be used:</p>
+ * <pre>
+ * public class MyClass {
+ *   &#64;SerializedName("name") String a;
+ *   &#64;SerializedName(value="name1", alternate={"name2", "name3"}) String b;
+ *   String c;
+ *
+ *   public MyClass(String a, String b, String c) {
+ *     this.a = a;
+ *     this.b = b;
+ *     this.c = c;
+ *   }
+ * }
+ * </pre>
+ *
+ * <p>The following shows the output that is generated when serializing an instance of the
+ * above example class:</p>
+ * <pre>
+ * MyClass target = new MyClass("v1", "v2", "v3");
+ * Gson gson = new Gson();
+ * String json = gson.toJson(target);
+ * System.out.println(json);
+ *
+ * ===== OUTPUT =====
+ * {"name":"v1","name1":"v2","c":"v3"}
+ * </pre>
+ *
+ * <p>NOTE: The value you specify in this annotation must be a valid JSON field name.</p>
+ * While deserializing, all values specified in the annotation will be deserialized into the field.
+ * For example:
+ * <pre>
+ *   MyClass target = gson.fromJson("{'name1':'v1'}", MyClass.class);
+ *   assertEquals("v1", target.b);
+ *   target = gson.fromJson("{'name2':'v2'}", MyClass.class);
+ *   assertEquals("v2", target.b);
+ *   target = gson.fromJson("{'name3':'v3'}", MyClass.class);
+ *   assertEquals("v3", target.b);
+ * </pre>
+ * Note that MyClass.b is now deserialized from either name1, name2 or name3.
+ *
+ * @see com.google.gson.FieldNamingPolicy
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+@Documented
+@Retention(RetentionPolicy.RUNTIME)
+@Target({ElementType.FIELD, ElementType.METHOD})
+public @interface SerializedName {
+
+  /**
+   * @return the desired name of the field when it is serialized or deserialized
+   */
+  String value();
+  /**
+   * @return the alternative names of the field when it is deserialized
+   */
+  String[] alternate() default {};
+}
diff --git a/gson/src/main/java/com/google/gson/annotations/Since.java b/gson/src/main/java/com/google/gson/annotations/Since.java
new file mode 100644
index 0000000..e23b6ec
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/annotations/Since.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.annotations;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * An annotation that indicates the version number since a member or a type has been present.
+ * This annotation is useful to manage versioning of your Json classes for a web-service.
+ *
+ * <p>
+ * This annotation has no effect unless you build {@link com.google.gson.Gson} with a
+ * {@link com.google.gson.GsonBuilder} and invoke
+ * {@link com.google.gson.GsonBuilder#setVersion(double)} method.
+ *
+ * <p>Here is an example of how this annotation is meant to be used:</p>
+ * <pre>
+ * public class User {
+ *   private String firstName;
+ *   private String lastName;
+ *   &#64;Since(1.0) private String emailAddress;
+ *   &#64;Since(1.0) private String password;
+ *   &#64;Since(1.1) private Address address;
+ * }
+ * </pre>
+ *
+ * <p>If you created Gson with {@code new Gson()}, the {@code toJson()} and {@code fromJson()}
+ * methods will use all the fields for serialization and deserialization. However, if you created
+ * Gson with {@code Gson gson = new GsonBuilder().setVersion(1.0).create()} then the
+ * {@code toJson()} and {@code fromJson()} methods of Gson will exclude the {@code address} field
+ * since it's version number is set to {@code 1.1}.</p>
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+@Documented
+@Retention(RetentionPolicy.RUNTIME)
+@Target({ElementType.FIELD, ElementType.TYPE})
+public @interface Since {
+  /**
+   * the value indicating a version number since this member
+   * or type has been present.
+   */
+  double value();
+}
diff --git a/gson/src/main/java/com/google/gson/annotations/Until.java b/gson/src/main/java/com/google/gson/annotations/Until.java
new file mode 100644
index 0000000..7c61d10
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/annotations/Until.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.annotations;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * An annotation that indicates the version number until a member or a type should be present.
+ * Basically, if Gson is created with a version number that exceeds the value stored in the
+ * {@code Until} annotation then the field will be ignored from the JSON output. This annotation
+ * is useful to manage versioning of your JSON classes for a web-service.
+ *
+ * <p>
+ * This annotation has no effect unless you build {@link com.google.gson.Gson} with a
+ * {@link com.google.gson.GsonBuilder} and invoke
+ * {@link com.google.gson.GsonBuilder#setVersion(double)} method.
+ *
+ * <p>Here is an example of how this annotation is meant to be used:</p>
+ * <pre>
+ * public class User {
+ *   private String firstName;
+ *   private String lastName;
+ *   &#64;Until(1.1) private String emailAddress;
+ *   &#64;Until(1.1) private String password;
+ * }
+ * </pre>
+ *
+ * <p>If you created Gson with {@code new Gson()}, the {@code toJson()} and {@code fromJson()}
+ * methods will use all the fields for serialization and deserialization. However, if you created
+ * Gson with {@code Gson gson = new GsonBuilder().setVersion(1.2).create()} then the
+ * {@code toJson()} and {@code fromJson()} methods of Gson will exclude the {@code emailAddress}
+ * and {@code password} fields from the example above, because the version number passed to the 
+ * GsonBuilder, {@code 1.2}, exceeds the version number set on the {@code Until} annotation,
+ * {@code 1.1}, for those fields.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ * @since 1.3
+ */
+@Documented
+@Retention(RetentionPolicy.RUNTIME)
+@Target({ElementType.FIELD, ElementType.TYPE})
+public @interface Until {
+
+  /**
+   * the value indicating a version number until this member
+   * or type should be ignored.
+   */
+  double value();
+}
diff --git a/gson/src/main/java/com/google/gson/annotations/package-info.java b/gson/src/main/java/com/google/gson/annotations/package-info.java
new file mode 100644
index 0000000..1c461fd
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/annotations/package-info.java
@@ -0,0 +1,6 @@
+/**
+ * This package provides annotations that can be used with {@link com.google.gson.Gson}.
+ * 
+ * @author Inderjeet Singh, Joel Leitch
+ */
+package com.google.gson.annotations;
\ No newline at end of file
diff --git a/gson/src/main/java/com/google/gson/internal/$Gson$Preconditions.java b/gson/src/main/java/com/google/gson/internal/$Gson$Preconditions.java
new file mode 100644
index 0000000..f0e7d3f
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/internal/$Gson$Preconditions.java
@@ -0,0 +1,49 @@
+/*

+ * Copyright (C) 2008 Google Inc.

+ *

+ * Licensed under the Apache License, Version 2.0 (the "License");

+ * you may not use this file except in compliance with the License.

+ * You may obtain a copy of the License at

+ *

+ * http://www.apache.org/licenses/LICENSE-2.0

+ *

+ * Unless required by applicable law or agreed to in writing, software

+ * distributed under the License is distributed on an "AS IS" BASIS,

+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

+ * See the License for the specific language governing permissions and

+ * limitations under the License.

+ */

+

+package com.google.gson.internal;

+

+/**

+ * A simple utility class used to check method Preconditions.

+ *

+ * <pre>

+ * public long divideBy(long value) {

+ *   Preconditions.checkArgument(value != 0);

+ *   return this.value / value;

+ * }

+ * </pre>

+ *

+ * @author Inderjeet Singh

+ * @author Joel Leitch

+ */

+public final class $Gson$Preconditions {

+  private $Gson$Preconditions() {

+    throw new UnsupportedOperationException();

+  }

+

+  public static <T> T checkNotNull(T obj) {

+    if (obj == null) {

+      throw new NullPointerException();

+    }

+    return obj;

+  }

+

+  public static void checkArgument(boolean condition) {

+    if (!condition) {

+      throw new IllegalArgumentException();

+    }

+  }

+}

diff --git a/gson/src/main/java/com/google/gson/internal/$Gson$Types.java b/gson/src/main/java/com/google/gson/internal/$Gson$Types.java
new file mode 100644
index 0000000..9891154
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/internal/$Gson$Types.java
@@ -0,0 +1,638 @@
+/**
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.internal;
+
+import java.io.Serializable;
+import java.lang.reflect.Array;
+import java.lang.reflect.GenericArrayType;
+import java.lang.reflect.GenericDeclaration;
+import java.lang.reflect.Modifier;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.lang.reflect.TypeVariable;
+import java.lang.reflect.WildcardType;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.Properties;
+
+import static com.google.gson.internal.$Gson$Preconditions.checkArgument;
+import static com.google.gson.internal.$Gson$Preconditions.checkNotNull;
+
+/**
+ * Static methods for working with types.
+ *
+ * @author Bob Lee
+ * @author Jesse Wilson
+ */
+public final class $Gson$Types {
+  static final Type[] EMPTY_TYPE_ARRAY = new Type[] {};
+
+  private $Gson$Types() {
+    throw new UnsupportedOperationException();
+  }
+
+  /**
+   * Returns a new parameterized type, applying {@code typeArguments} to
+   * {@code rawType} and enclosed by {@code ownerType}.
+   *
+   * @return a {@link java.io.Serializable serializable} parameterized type.
+   */
+  public static ParameterizedType newParameterizedTypeWithOwner(
+      Type ownerType, Type rawType, Type... typeArguments) {
+    return new ParameterizedTypeImpl(ownerType, rawType, typeArguments);
+  }
+
+  /**
+   * Returns an array type whose elements are all instances of
+   * {@code componentType}.
+   *
+   * @return a {@link java.io.Serializable serializable} generic array type.
+   */
+  public static GenericArrayType arrayOf(Type componentType) {
+    return new GenericArrayTypeImpl(componentType);
+  }
+
+  /**
+   * Returns a type that represents an unknown type that extends {@code bound}.
+   * For example, if {@code bound} is {@code CharSequence.class}, this returns
+   * {@code ? extends CharSequence}. If {@code bound} is {@code Object.class},
+   * this returns {@code ?}, which is shorthand for {@code ? extends Object}.
+   */
+  public static WildcardType subtypeOf(Type bound) {
+    Type[] upperBounds;
+    if (bound instanceof WildcardType) {
+      upperBounds = ((WildcardType) bound).getUpperBounds();
+    } else {
+      upperBounds = new Type[] { bound };
+    }
+    return new WildcardTypeImpl(upperBounds, EMPTY_TYPE_ARRAY);
+  }
+
+  /**
+   * Returns a type that represents an unknown supertype of {@code bound}. For
+   * example, if {@code bound} is {@code String.class}, this returns {@code ?
+   * super String}.
+   */
+  public static WildcardType supertypeOf(Type bound) {
+    Type[] lowerBounds;
+    if (bound instanceof WildcardType) {
+      lowerBounds = ((WildcardType) bound).getLowerBounds();
+    } else {
+      lowerBounds = new Type[] { bound };
+    }
+    return new WildcardTypeImpl(new Type[] { Object.class }, lowerBounds);
+  }
+
+  /**
+   * Returns a type that is functionally equal but not necessarily equal
+   * according to {@link Object#equals(Object) Object.equals()}. The returned
+   * type is {@link java.io.Serializable}.
+   */
+  public static Type canonicalize(Type type) {
+    if (type instanceof Class) {
+      Class<?> c = (Class<?>) type;
+      return c.isArray() ? new GenericArrayTypeImpl(canonicalize(c.getComponentType())) : c;
+
+    } else if (type instanceof ParameterizedType) {
+      ParameterizedType p = (ParameterizedType) type;
+      return new ParameterizedTypeImpl(p.getOwnerType(),
+          p.getRawType(), p.getActualTypeArguments());
+
+    } else if (type instanceof GenericArrayType) {
+      GenericArrayType g = (GenericArrayType) type;
+      return new GenericArrayTypeImpl(g.getGenericComponentType());
+
+    } else if (type instanceof WildcardType) {
+      WildcardType w = (WildcardType) type;
+      return new WildcardTypeImpl(w.getUpperBounds(), w.getLowerBounds());
+
+    } else {
+      // type is either serializable as-is or unsupported
+      return type;
+    }
+  }
+
+  public static Class<?> getRawType(Type type) {
+    if (type instanceof Class<?>) {
+      // type is a normal class.
+      return (Class<?>) type;
+
+    } else if (type instanceof ParameterizedType) {
+      ParameterizedType parameterizedType = (ParameterizedType) type;
+
+      // I'm not exactly sure why getRawType() returns Type instead of Class.
+      // Neal isn't either but suspects some pathological case related
+      // to nested classes exists.
+      Type rawType = parameterizedType.getRawType();
+      checkArgument(rawType instanceof Class);
+      return (Class<?>) rawType;
+
+    } else if (type instanceof GenericArrayType) {
+      Type componentType = ((GenericArrayType)type).getGenericComponentType();
+      return Array.newInstance(getRawType(componentType), 0).getClass();
+
+    } else if (type instanceof TypeVariable) {
+      // we could use the variable's bounds, but that won't work if there are multiple.
+      // having a raw type that's more general than necessary is okay
+      return Object.class;
+
+    } else if (type instanceof WildcardType) {
+      Type[] bounds = ((WildcardType) type).getUpperBounds();
+      // Currently the JLS only permits one bound for wildcards so using first bound is safe
+      assert bounds.length == 1;
+      return getRawType(bounds[0]);
+
+    } else {
+      String className = type == null ? "null" : type.getClass().getName();
+      throw new IllegalArgumentException("Expected a Class, ParameterizedType, or "
+          + "GenericArrayType, but <" + type + "> is of type " + className);
+    }
+  }
+
+  private static boolean equal(Object a, Object b) {
+    return a == b || (a != null && a.equals(b));
+  }
+
+  /**
+   * Returns true if {@code a} and {@code b} are equal.
+   */
+  public static boolean equals(Type a, Type b) {
+    if (a == b) {
+      // also handles (a == null && b == null)
+      return true;
+
+    } else if (a instanceof Class) {
+      // Class already specifies equals().
+      return a.equals(b);
+
+    } else if (a instanceof ParameterizedType) {
+      if (!(b instanceof ParameterizedType)) {
+        return false;
+      }
+
+      // TODO: save a .clone() call
+      ParameterizedType pa = (ParameterizedType) a;
+      ParameterizedType pb = (ParameterizedType) b;
+      return equal(pa.getOwnerType(), pb.getOwnerType())
+          && pa.getRawType().equals(pb.getRawType())
+          && Arrays.equals(pa.getActualTypeArguments(), pb.getActualTypeArguments());
+
+    } else if (a instanceof GenericArrayType) {
+      if (!(b instanceof GenericArrayType)) {
+        return false;
+      }
+
+      GenericArrayType ga = (GenericArrayType) a;
+      GenericArrayType gb = (GenericArrayType) b;
+      return equals(ga.getGenericComponentType(), gb.getGenericComponentType());
+
+    } else if (a instanceof WildcardType) {
+      if (!(b instanceof WildcardType)) {
+        return false;
+      }
+
+      WildcardType wa = (WildcardType) a;
+      WildcardType wb = (WildcardType) b;
+      return Arrays.equals(wa.getUpperBounds(), wb.getUpperBounds())
+          && Arrays.equals(wa.getLowerBounds(), wb.getLowerBounds());
+
+    } else if (a instanceof TypeVariable) {
+      if (!(b instanceof TypeVariable)) {
+        return false;
+      }
+      TypeVariable<?> va = (TypeVariable<?>) a;
+      TypeVariable<?> vb = (TypeVariable<?>) b;
+      return va.getGenericDeclaration() == vb.getGenericDeclaration()
+          && va.getName().equals(vb.getName());
+
+    } else {
+      // This isn't a type we support. Could be a generic array type, wildcard type, etc.
+      return false;
+    }
+  }
+
+  public static String typeToString(Type type) {
+    return type instanceof Class ? ((Class<?>) type).getName() : type.toString();
+  }
+
+  /**
+   * Returns the generic supertype for {@code supertype}. For example, given a class {@code
+   * IntegerSet}, the result for when supertype is {@code Set.class} is {@code Set<Integer>} and the
+   * result when the supertype is {@code Collection.class} is {@code Collection<Integer>}.
+   */
+  private static Type getGenericSupertype(Type context, Class<?> rawType, Class<?> supertype) {
+    if (supertype == rawType) {
+      return context;
+    }
+
+    // we skip searching through interfaces if unknown is an interface
+    if (supertype.isInterface()) {
+      Class<?>[] interfaces = rawType.getInterfaces();
+      for (int i = 0, length = interfaces.length; i < length; i++) {
+        if (interfaces[i] == supertype) {
+          return rawType.getGenericInterfaces()[i];
+        } else if (supertype.isAssignableFrom(interfaces[i])) {
+          return getGenericSupertype(rawType.getGenericInterfaces()[i], interfaces[i], supertype);
+        }
+      }
+    }
+
+    // check our supertypes
+    if (!rawType.isInterface()) {
+      while (rawType != Object.class) {
+        Class<?> rawSupertype = rawType.getSuperclass();
+        if (rawSupertype == supertype) {
+          return rawType.getGenericSuperclass();
+        } else if (supertype.isAssignableFrom(rawSupertype)) {
+          return getGenericSupertype(rawType.getGenericSuperclass(), rawSupertype, supertype);
+        }
+        rawType = rawSupertype;
+      }
+    }
+
+    // we can't resolve this further
+    return supertype;
+  }
+
+  /**
+   * Returns the generic form of {@code supertype}. For example, if this is {@code
+   * ArrayList<String>}, this returns {@code Iterable<String>} given the input {@code
+   * Iterable.class}.
+   *
+   * @param supertype a superclass of, or interface implemented by, this.
+   */
+  private static Type getSupertype(Type context, Class<?> contextRawType, Class<?> supertype) {
+    if (context instanceof WildcardType) {
+      // wildcards are useless for resolving supertypes. As the upper bound has the same raw type, use it instead
+      Type[] bounds = ((WildcardType)context).getUpperBounds();
+      // Currently the JLS only permits one bound for wildcards so using first bound is safe
+      assert bounds.length == 1;
+      context = bounds[0];
+    }
+    checkArgument(supertype.isAssignableFrom(contextRawType));
+    return resolve(context, contextRawType,
+        $Gson$Types.getGenericSupertype(context, contextRawType, supertype));
+  }
+
+  /**
+   * Returns the component type of this array type.
+   * @throws ClassCastException if this type is not an array.
+   */
+  public static Type getArrayComponentType(Type array) {
+    return array instanceof GenericArrayType
+        ? ((GenericArrayType) array).getGenericComponentType()
+        : ((Class<?>) array).getComponentType();
+  }
+
+  /**
+   * Returns the element type of this collection type.
+   * @throws IllegalArgumentException if this type is not a collection.
+   */
+  public static Type getCollectionElementType(Type context, Class<?> contextRawType) {
+    Type collectionType = getSupertype(context, contextRawType, Collection.class);
+
+    if (collectionType instanceof ParameterizedType) {
+      return ((ParameterizedType) collectionType).getActualTypeArguments()[0];
+    }
+    return Object.class;
+  }
+
+  /**
+   * Returns a two element array containing this map's key and value types in
+   * positions 0 and 1 respectively.
+   */
+  public static Type[] getMapKeyAndValueTypes(Type context, Class<?> contextRawType) {
+    /*
+     * Work around a problem with the declaration of java.util.Properties. That
+     * class should extend Hashtable<String, String>, but it's declared to
+     * extend Hashtable<Object, Object>.
+     */
+    if (context == Properties.class) {
+      return new Type[] { String.class, String.class }; // TODO: test subclasses of Properties!
+    }
+
+    Type mapType = getSupertype(context, contextRawType, Map.class);
+    // TODO: strip wildcards?
+    if (mapType instanceof ParameterizedType) {
+      ParameterizedType mapParameterizedType = (ParameterizedType) mapType;
+      return mapParameterizedType.getActualTypeArguments();
+    }
+    return new Type[] { Object.class, Object.class };
+  }
+
+  public static Type resolve(Type context, Class<?> contextRawType, Type toResolve) {
+
+    return resolve(context, contextRawType, toResolve, new HashMap<TypeVariable<?>, Type>());
+  }
+
+  private static Type resolve(Type context, Class<?> contextRawType, Type toResolve,
+                              Map<TypeVariable<?>, Type> visitedTypeVariables) {
+    // this implementation is made a little more complicated in an attempt to avoid object-creation
+    TypeVariable<?> resolving = null;
+    while (true) {
+      if (toResolve instanceof TypeVariable) {
+        TypeVariable<?> typeVariable = (TypeVariable<?>) toResolve;
+        Type previouslyResolved = visitedTypeVariables.get(typeVariable);
+        if (previouslyResolved != null) {
+          // cannot reduce due to infinite recursion
+          return (previouslyResolved == Void.TYPE) ? toResolve : previouslyResolved;
+        }
+
+        // Insert a placeholder to mark the fact that we are in the process of resolving this type
+        visitedTypeVariables.put(typeVariable, Void.TYPE);
+        if (resolving == null) {
+          resolving = typeVariable;
+        }
+
+        toResolve = resolveTypeVariable(context, contextRawType, typeVariable);
+        if (toResolve == typeVariable) {
+          break;
+        }
+
+      } else if (toResolve instanceof Class && ((Class<?>) toResolve).isArray()) {
+        Class<?> original = (Class<?>) toResolve;
+        Type componentType = original.getComponentType();
+        Type newComponentType = resolve(context, contextRawType, componentType, visitedTypeVariables);
+        toResolve = equal(componentType, newComponentType)
+            ? original
+            : arrayOf(newComponentType);
+        break;
+
+      } else if (toResolve instanceof GenericArrayType) {
+        GenericArrayType original = (GenericArrayType) toResolve;
+        Type componentType = original.getGenericComponentType();
+        Type newComponentType = resolve(context, contextRawType, componentType, visitedTypeVariables);
+        toResolve = equal(componentType, newComponentType)
+            ? original
+            : arrayOf(newComponentType);
+        break;
+
+      } else if (toResolve instanceof ParameterizedType) {
+        ParameterizedType original = (ParameterizedType) toResolve;
+        Type ownerType = original.getOwnerType();
+        Type newOwnerType = resolve(context, contextRawType, ownerType, visitedTypeVariables);
+        boolean changed = !equal(newOwnerType, ownerType);
+
+        Type[] args = original.getActualTypeArguments();
+        for (int t = 0, length = args.length; t < length; t++) {
+          Type resolvedTypeArgument = resolve(context, contextRawType, args[t], visitedTypeVariables);
+          if (!equal(resolvedTypeArgument, args[t])) {
+            if (!changed) {
+              args = args.clone();
+              changed = true;
+            }
+            args[t] = resolvedTypeArgument;
+          }
+        }
+
+        toResolve = changed
+            ? newParameterizedTypeWithOwner(newOwnerType, original.getRawType(), args)
+            : original;
+        break;
+
+      } else if (toResolve instanceof WildcardType) {
+        WildcardType original = (WildcardType) toResolve;
+        Type[] originalLowerBound = original.getLowerBounds();
+        Type[] originalUpperBound = original.getUpperBounds();
+
+        if (originalLowerBound.length == 1) {
+          Type lowerBound = resolve(context, contextRawType, originalLowerBound[0], visitedTypeVariables);
+          if (lowerBound != originalLowerBound[0]) {
+            toResolve = supertypeOf(lowerBound);
+            break;
+          }
+        } else if (originalUpperBound.length == 1) {
+          Type upperBound = resolve(context, contextRawType, originalUpperBound[0], visitedTypeVariables);
+          if (upperBound != originalUpperBound[0]) {
+            toResolve = subtypeOf(upperBound);
+            break;
+          }
+        }
+        toResolve = original;
+        break;
+
+      } else {
+        break;
+      }
+    }
+    // ensure that any in-process resolution gets updated with the final result
+    if (resolving != null) {
+      visitedTypeVariables.put(resolving, toResolve);
+    }
+    return toResolve;
+  }
+
+  private static Type resolveTypeVariable(Type context, Class<?> contextRawType, TypeVariable<?> unknown) {
+    Class<?> declaredByRaw = declaringClassOf(unknown);
+
+    // we can't reduce this further
+    if (declaredByRaw == null) {
+      return unknown;
+    }
+
+    Type declaredBy = getGenericSupertype(context, contextRawType, declaredByRaw);
+    if (declaredBy instanceof ParameterizedType) {
+      int index = indexOf(declaredByRaw.getTypeParameters(), unknown);
+      return ((ParameterizedType) declaredBy).getActualTypeArguments()[index];
+    }
+
+    return unknown;
+  }
+
+  private static int indexOf(Object[] array, Object toFind) {
+    for (int i = 0, length = array.length; i < length; i++) {
+      if (toFind.equals(array[i])) {
+        return i;
+      }
+    }
+    throw new NoSuchElementException();
+  }
+
+  /**
+   * Returns the declaring class of {@code typeVariable}, or {@code null} if it was not declared by
+   * a class.
+   */
+  private static Class<?> declaringClassOf(TypeVariable<?> typeVariable) {
+    GenericDeclaration genericDeclaration = typeVariable.getGenericDeclaration();
+    return genericDeclaration instanceof Class
+        ? (Class<?>) genericDeclaration
+        : null;
+  }
+
+  static void checkNotPrimitive(Type type) {
+    checkArgument(!(type instanceof Class<?>) || !((Class<?>) type).isPrimitive());
+  }
+
+  private static final class ParameterizedTypeImpl implements ParameterizedType, Serializable {
+    private final Type ownerType;
+    private final Type rawType;
+    private final Type[] typeArguments;
+
+    public ParameterizedTypeImpl(Type ownerType, Type rawType, Type... typeArguments) {
+      // require an owner type if the raw type needs it
+      if (rawType instanceof Class<?>) {
+        Class<?> rawTypeAsClass = (Class<?>) rawType;
+        boolean isStaticOrTopLevelClass = Modifier.isStatic(rawTypeAsClass.getModifiers())
+            || rawTypeAsClass.getEnclosingClass() == null;
+        checkArgument(ownerType != null || isStaticOrTopLevelClass);
+      }
+
+      this.ownerType = ownerType == null ? null : canonicalize(ownerType);
+      this.rawType = canonicalize(rawType);
+      this.typeArguments = typeArguments.clone();
+      for (int t = 0, length = this.typeArguments.length; t < length; t++) {
+        checkNotNull(this.typeArguments[t]);
+        checkNotPrimitive(this.typeArguments[t]);
+        this.typeArguments[t] = canonicalize(this.typeArguments[t]);
+      }
+    }
+
+    @Override public Type[] getActualTypeArguments() {
+      return typeArguments.clone();
+    }
+
+    @Override public Type getRawType() {
+      return rawType;
+    }
+
+    @Override public Type getOwnerType() {
+      return ownerType;
+    }
+
+    @Override public boolean equals(Object other) {
+      return other instanceof ParameterizedType
+          && $Gson$Types.equals(this, (ParameterizedType) other);
+    }
+
+    private static int hashCodeOrZero(Object o) {
+      return o != null ? o.hashCode() : 0;
+    }
+
+    @Override public int hashCode() {
+      return Arrays.hashCode(typeArguments)
+          ^ rawType.hashCode()
+          ^ hashCodeOrZero(ownerType);
+    }
+
+    @Override public String toString() {
+      int length = typeArguments.length;
+      if (length == 0) {
+        return typeToString(rawType);
+      }
+
+      StringBuilder stringBuilder = new StringBuilder(30 * (length + 1));
+      stringBuilder.append(typeToString(rawType)).append("<").append(typeToString(typeArguments[0]));
+      for (int i = 1; i < length; i++) {
+        stringBuilder.append(", ").append(typeToString(typeArguments[i]));
+      }
+      return stringBuilder.append(">").toString();
+    }
+
+    private static final long serialVersionUID = 0;
+  }
+
+  private static final class GenericArrayTypeImpl implements GenericArrayType, Serializable {
+    private final Type componentType;
+
+    public GenericArrayTypeImpl(Type componentType) {
+      this.componentType = canonicalize(componentType);
+    }
+
+    @Override public Type getGenericComponentType() {
+      return componentType;
+    }
+
+    @Override public boolean equals(Object o) {
+      return o instanceof GenericArrayType
+          && $Gson$Types.equals(this, (GenericArrayType) o);
+    }
+
+    @Override public int hashCode() {
+      return componentType.hashCode();
+    }
+
+    @Override public String toString() {
+      return typeToString(componentType) + "[]";
+    }
+
+    private static final long serialVersionUID = 0;
+  }
+
+  /**
+   * The WildcardType interface supports multiple upper bounds and multiple
+   * lower bounds. We only support what the target Java version supports - at most one
+   * bound, see also https://bugs.openjdk.java.net/browse/JDK-8250660. If a lower bound
+   * is set, the upper bound must be Object.class.
+   */
+  private static final class WildcardTypeImpl implements WildcardType, Serializable {
+    private final Type upperBound;
+    private final Type lowerBound;
+
+    public WildcardTypeImpl(Type[] upperBounds, Type[] lowerBounds) {
+      checkArgument(lowerBounds.length <= 1);
+      checkArgument(upperBounds.length == 1);
+
+      if (lowerBounds.length == 1) {
+        checkNotNull(lowerBounds[0]);
+        checkNotPrimitive(lowerBounds[0]);
+        checkArgument(upperBounds[0] == Object.class);
+        this.lowerBound = canonicalize(lowerBounds[0]);
+        this.upperBound = Object.class;
+
+      } else {
+        checkNotNull(upperBounds[0]);
+        checkNotPrimitive(upperBounds[0]);
+        this.lowerBound = null;
+        this.upperBound = canonicalize(upperBounds[0]);
+      }
+    }
+
+    @Override public Type[] getUpperBounds() {
+      return new Type[] { upperBound };
+    }
+
+    @Override public Type[] getLowerBounds() {
+      return lowerBound != null ? new Type[] { lowerBound } : EMPTY_TYPE_ARRAY;
+    }
+
+    @Override public boolean equals(Object other) {
+      return other instanceof WildcardType
+          && $Gson$Types.equals(this, (WildcardType) other);
+    }
+
+    @Override public int hashCode() {
+      // this equals Arrays.hashCode(getLowerBounds()) ^ Arrays.hashCode(getUpperBounds());
+      return (lowerBound != null ? 31 + lowerBound.hashCode() : 1)
+          ^ (31 + upperBound.hashCode());
+    }
+
+    @Override public String toString() {
+      if (lowerBound != null) {
+        return "? super " + typeToString(lowerBound);
+      } else if (upperBound == Object.class) {
+        return "?";
+      } else {
+        return "? extends " + typeToString(upperBound);
+      }
+    }
+
+    private static final long serialVersionUID = 0;
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/internal/ConstructorConstructor.java b/gson/src/main/java/com/google/gson/internal/ConstructorConstructor.java
new file mode 100644
index 0000000..68b2bd6
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/internal/ConstructorConstructor.java
@@ -0,0 +1,373 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.internal;
+
+import com.google.gson.InstanceCreator;
+import com.google.gson.JsonIOException;
+import com.google.gson.ReflectionAccessFilter;
+import com.google.gson.ReflectionAccessFilter.FilterResult;
+import com.google.gson.internal.reflect.ReflectionHelper;
+import com.google.gson.reflect.TypeToken;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Modifier;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.EnumMap;
+import java.util.EnumSet;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Queue;
+import java.util.Set;
+import java.util.SortedMap;
+import java.util.SortedSet;
+import java.util.TreeMap;
+import java.util.TreeSet;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.ConcurrentNavigableMap;
+import java.util.concurrent.ConcurrentSkipListMap;
+
+/**
+ * Returns a function that can construct an instance of a requested type.
+ */
+public final class ConstructorConstructor {
+  private final Map<Type, InstanceCreator<?>> instanceCreators;
+  private final boolean useJdkUnsafe;
+  private final List<ReflectionAccessFilter> reflectionFilters;
+
+  public ConstructorConstructor(Map<Type, InstanceCreator<?>> instanceCreators, boolean useJdkUnsafe, List<ReflectionAccessFilter> reflectionFilters) {
+    this.instanceCreators = instanceCreators;
+    this.useJdkUnsafe = useJdkUnsafe;
+    this.reflectionFilters = reflectionFilters;
+  }
+
+  public <T> ObjectConstructor<T> get(TypeToken<T> typeToken) {
+    final Type type = typeToken.getType();
+    final Class<? super T> rawType = typeToken.getRawType();
+
+    // first try an instance creator
+
+    @SuppressWarnings("unchecked") // types must agree
+    final InstanceCreator<T> typeCreator = (InstanceCreator<T>) instanceCreators.get(type);
+    if (typeCreator != null) {
+      return new ObjectConstructor<T>() {
+        @Override public T construct() {
+          return typeCreator.createInstance(type);
+        }
+      };
+    }
+
+    // Next try raw type match for instance creators
+    @SuppressWarnings("unchecked") // types must agree
+    final InstanceCreator<T> rawTypeCreator =
+        (InstanceCreator<T>) instanceCreators.get(rawType);
+    if (rawTypeCreator != null) {
+      return new ObjectConstructor<T>() {
+        @Override public T construct() {
+          return rawTypeCreator.createInstance(type);
+        }
+      };
+    }
+
+    // First consider special constructors before checking for no-args constructors
+    // below to avoid matching internal no-args constructors which might be added in
+    // future JDK versions
+    ObjectConstructor<T> specialConstructor = newSpecialCollectionConstructor(type, rawType);
+    if (specialConstructor != null) {
+      return specialConstructor;
+    }
+
+    FilterResult filterResult = ReflectionAccessFilterHelper.getFilterResult(reflectionFilters, rawType);
+    ObjectConstructor<T> defaultConstructor = newDefaultConstructor(rawType, filterResult);
+    if (defaultConstructor != null) {
+      return defaultConstructor;
+    }
+
+    ObjectConstructor<T> defaultImplementation = newDefaultImplementationConstructor(type, rawType);
+    if (defaultImplementation != null) {
+      return defaultImplementation;
+    }
+
+    // Check whether type is instantiable; otherwise ReflectionAccessFilter recommendation
+    // of adjusting filter suggested below is irrelevant since it would not solve the problem
+    final String exceptionMessage = UnsafeAllocator.checkInstantiable(rawType);
+    if (exceptionMessage != null) {
+      return new ObjectConstructor<T>() {
+        @Override public T construct() {
+          throw new JsonIOException(exceptionMessage);
+        }
+      };
+    }
+
+    // Consider usage of Unsafe as reflection, so don't use if BLOCK_ALL
+    // Additionally, since it is not calling any constructor at all, don't use if BLOCK_INACCESSIBLE
+    if (filterResult == FilterResult.ALLOW) {
+      // finally try unsafe
+      return newUnsafeAllocator(rawType);
+    } else {
+      final String message = "Unable to create instance of " + rawType + "; ReflectionAccessFilter "
+          + "does not permit using reflection or Unsafe. Register an InstanceCreator or a TypeAdapter "
+          + "for this type or adjust the access filter to allow using reflection.";
+      return new ObjectConstructor<T>() {
+        @Override public T construct() {
+          throw new JsonIOException(message);
+        }
+      };
+    }
+  }
+
+  /**
+   * Creates constructors for special JDK collection types which do not have a public no-args constructor.
+   */
+  private static <T> ObjectConstructor<T> newSpecialCollectionConstructor(final Type type, Class<? super T> rawType) {
+    if (EnumSet.class.isAssignableFrom(rawType)) {
+      return new ObjectConstructor<T>() {
+        @Override public T construct() {
+          if (type instanceof ParameterizedType) {
+            Type elementType = ((ParameterizedType) type).getActualTypeArguments()[0];
+            if (elementType instanceof Class) {
+              @SuppressWarnings({"unchecked", "rawtypes"})
+              T set = (T) EnumSet.noneOf((Class)elementType);
+              return set;
+            } else {
+              throw new JsonIOException("Invalid EnumSet type: " + type.toString());
+            }
+          } else {
+            throw new JsonIOException("Invalid EnumSet type: " + type.toString());
+          }
+        }
+      };
+    }
+    // Only support creation of EnumMap, but not of custom subtypes; for them type parameters
+    // and constructor parameter might have completely different meaning
+    else if (rawType == EnumMap.class) {
+      return new ObjectConstructor<T>() {
+        @Override public T construct() {
+          if (type instanceof ParameterizedType) {
+            Type elementType = ((ParameterizedType) type).getActualTypeArguments()[0];
+            if (elementType instanceof Class) {
+              @SuppressWarnings({"unchecked", "rawtypes"})
+              T map = (T) new EnumMap((Class) elementType);
+              return map;
+            } else {
+              throw new JsonIOException("Invalid EnumMap type: " + type.toString());
+            }
+          } else {
+            throw new JsonIOException("Invalid EnumMap type: " + type.toString());
+          }
+        }
+      };
+    }
+
+    return null;
+  }
+
+  private static <T> ObjectConstructor<T> newDefaultConstructor(Class<? super T> rawType, FilterResult filterResult) {
+    // Cannot invoke constructor of abstract class
+    if (Modifier.isAbstract(rawType.getModifiers())) {
+      return null;
+    }
+
+    final Constructor<? super T> constructor;
+    try {
+      constructor = rawType.getDeclaredConstructor();
+    } catch (NoSuchMethodException e) {
+      return null;
+    }
+
+    boolean canAccess = filterResult == FilterResult.ALLOW || (ReflectionAccessFilterHelper.canAccess(constructor, null)
+        // Be a bit more lenient here for BLOCK_ALL; if constructor is accessible and public then allow calling it
+        && (filterResult != FilterResult.BLOCK_ALL || Modifier.isPublic(constructor.getModifiers())));
+
+    if (!canAccess) {
+      final String message = "Unable to invoke no-args constructor of " + rawType + "; "
+          + "constructor is not accessible and ReflectionAccessFilter does not permit making "
+          + "it accessible. Register an InstanceCreator or a TypeAdapter for this type, change "
+          + "the visibility of the constructor or adjust the access filter.";
+      return new ObjectConstructor<T>() {
+        @Override public T construct() {
+          throw new JsonIOException(message);
+        }
+      };
+    }
+
+    // Only try to make accessible if allowed; in all other cases checks above should
+    // have verified that constructor is accessible
+    if (filterResult == FilterResult.ALLOW) {
+      final String exceptionMessage = ReflectionHelper.tryMakeAccessible(constructor);
+      if (exceptionMessage != null) {
+        /*
+         * Create ObjectConstructor which throws exception.
+         * This keeps backward compatibility (compared to returning `null` which
+         * would then choose another way of creating object).
+         * And it supports types which are only serialized but not deserialized
+         * (compared to directly throwing exception here), e.g. when runtime type
+         * of object is inaccessible, but compile-time type is accessible.
+         */
+        return new ObjectConstructor<T>() {
+          @Override
+          public T construct() {
+            // New exception is created every time to avoid keeping reference
+            // to exception with potentially long stack trace, causing a
+            // memory leak
+            throw new JsonIOException(exceptionMessage);
+          }
+        };
+      }
+    }
+
+    return new ObjectConstructor<T>() {
+      @Override public T construct() {
+        try {
+          @SuppressWarnings("unchecked") // T is the same raw type as is requested
+          T newInstance = (T) constructor.newInstance();
+          return newInstance;
+        } catch (InstantiationException e) {
+          // TODO: JsonParseException ?
+          throw new RuntimeException("Failed to invoke " + constructor + " with no args", e);
+        } catch (InvocationTargetException e) {
+          // TODO: don't wrap if cause is unchecked!
+          // TODO: JsonParseException ?
+          throw new RuntimeException("Failed to invoke " + constructor + " with no args",
+              e.getTargetException());
+        } catch (IllegalAccessException e) {
+          throw ReflectionHelper.createExceptionForUnexpectedIllegalAccess(e);
+        }
+      }
+    };
+  }
+
+  /**
+   * Constructors for common interface types like Map and List and their
+   * subtypes.
+   */
+  @SuppressWarnings("unchecked") // use runtime checks to guarantee that 'T' is what it is
+  private static <T> ObjectConstructor<T> newDefaultImplementationConstructor(
+      final Type type, Class<? super T> rawType) {
+
+    /*
+     * IMPORTANT: Must only create instances for classes with public no-args constructor.
+     * For classes with special constructors / factory methods (e.g. EnumSet)
+     * `newSpecialCollectionConstructor` defined above must be used, to avoid no-args
+     * constructor check (which is called before this method) detecting internal no-args
+     * constructors which might be added in a future JDK version
+     */
+
+    if (Collection.class.isAssignableFrom(rawType)) {
+      if (SortedSet.class.isAssignableFrom(rawType)) {
+        return new ObjectConstructor<T>() {
+          @Override public T construct() {
+            return (T) new TreeSet<>();
+          }
+        };
+      } else if (Set.class.isAssignableFrom(rawType)) {
+        return new ObjectConstructor<T>() {
+          @Override public T construct() {
+            return (T) new LinkedHashSet<>();
+          }
+        };
+      } else if (Queue.class.isAssignableFrom(rawType)) {
+        return new ObjectConstructor<T>() {
+          @Override public T construct() {
+            return (T) new ArrayDeque<>();
+          }
+        };
+      } else {
+        return new ObjectConstructor<T>() {
+          @Override public T construct() {
+            return (T) new ArrayList<>();
+          }
+        };
+      }
+    }
+
+    if (Map.class.isAssignableFrom(rawType)) {
+      if (ConcurrentNavigableMap.class.isAssignableFrom(rawType)) {
+        return new ObjectConstructor<T>() {
+          @Override public T construct() {
+            return (T) new ConcurrentSkipListMap<>();
+          }
+        };
+      } else if (ConcurrentMap.class.isAssignableFrom(rawType)) {
+        return new ObjectConstructor<T>() {
+          @Override public T construct() {
+            return (T) new ConcurrentHashMap<>();
+          }
+        };
+      } else if (SortedMap.class.isAssignableFrom(rawType)) {
+        return new ObjectConstructor<T>() {
+          @Override public T construct() {
+            return (T) new TreeMap<>();
+          }
+        };
+      } else if (type instanceof ParameterizedType && !(String.class.isAssignableFrom(
+          TypeToken.get(((ParameterizedType) type).getActualTypeArguments()[0]).getRawType()))) {
+        return new ObjectConstructor<T>() {
+          @Override public T construct() {
+            return (T) new LinkedHashMap<>();
+          }
+        };
+      } else {
+        return new ObjectConstructor<T>() {
+          @Override public T construct() {
+            return (T) new LinkedTreeMap<>();
+          }
+        };
+      }
+    }
+
+    return null;
+  }
+
+  private <T> ObjectConstructor<T> newUnsafeAllocator(final Class<? super T> rawType) {
+    if (useJdkUnsafe) {
+      return new ObjectConstructor<T>() {
+        private final UnsafeAllocator unsafeAllocator = UnsafeAllocator.create();
+        @Override public T construct() {
+          try {
+            @SuppressWarnings("unchecked")
+            T newInstance = (T) unsafeAllocator.newInstance(rawType);
+            return newInstance;
+          } catch (Exception e) {
+            throw new RuntimeException(("Unable to create instance of " + rawType + ". "
+                + "Registering an InstanceCreator or a TypeAdapter for this type, or adding a no-args "
+                + "constructor may fix this problem."), e);
+          }
+        }
+      };
+    } else {
+      final String exceptionMessage = "Unable to create instance of " + rawType + "; 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.";
+      return new ObjectConstructor<T>() {
+        @Override public T construct() {
+          throw new JsonIOException(exceptionMessage);
+        }
+      };
+    }
+  }
+
+  @Override public String toString() {
+    return instanceCreators.toString();
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/internal/Excluder.java b/gson/src/main/java/com/google/gson/internal/Excluder.java
new file mode 100644
index 0000000..8d8a25f
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/internal/Excluder.java
@@ -0,0 +1,259 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.internal;
+
+import com.google.gson.ExclusionStrategy;
+import com.google.gson.FieldAttributes;
+import com.google.gson.Gson;
+import com.google.gson.TypeAdapter;
+import com.google.gson.TypeAdapterFactory;
+import com.google.gson.annotations.Expose;
+import com.google.gson.annotations.Since;
+import com.google.gson.annotations.Until;
+import com.google.gson.reflect.TypeToken;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * This class selects which fields and types to omit. It is configurable,
+ * supporting version attributes {@link Since} and {@link Until}, modifiers,
+ * synthetic fields, anonymous and local classes, inner classes, and fields with
+ * the {@link Expose} annotation.
+ *
+ * <p>This class is a type adapter factory; types that are excluded will be
+ * adapted to null. It may delegate to another type adapter if only one
+ * direction is excluded.
+ *
+ * @author Joel Leitch
+ * @author Jesse Wilson
+ */
+public final class Excluder implements TypeAdapterFactory, Cloneable {
+  private static final double IGNORE_VERSIONS = -1.0d;
+  public static final Excluder DEFAULT = new Excluder();
+
+  private double version = IGNORE_VERSIONS;
+  private int modifiers = Modifier.TRANSIENT | Modifier.STATIC;
+  private boolean serializeInnerClasses = true;
+  private boolean requireExpose;
+  private List<ExclusionStrategy> serializationStrategies = Collections.emptyList();
+  private List<ExclusionStrategy> deserializationStrategies = Collections.emptyList();
+
+  @Override protected Excluder clone() {
+    try {
+      return (Excluder) super.clone();
+    } catch (CloneNotSupportedException e) {
+      throw new AssertionError(e);
+    }
+  }
+
+  public Excluder withVersion(double ignoreVersionsAfter) {
+    Excluder result = clone();
+    result.version = ignoreVersionsAfter;
+    return result;
+  }
+
+  public Excluder withModifiers(int... modifiers) {
+    Excluder result = clone();
+    result.modifiers = 0;
+    for (int modifier : modifiers) {
+      result.modifiers |= modifier;
+    }
+    return result;
+  }
+
+  public Excluder disableInnerClassSerialization() {
+    Excluder result = clone();
+    result.serializeInnerClasses = false;
+    return result;
+  }
+
+  public Excluder excludeFieldsWithoutExposeAnnotation() {
+    Excluder result = clone();
+    result.requireExpose = true;
+    return result;
+  }
+
+  public Excluder withExclusionStrategy(ExclusionStrategy exclusionStrategy,
+      boolean serialization, boolean deserialization) {
+    Excluder result = clone();
+    if (serialization) {
+      result.serializationStrategies = new ArrayList<>(serializationStrategies);
+      result.serializationStrategies.add(exclusionStrategy);
+    }
+    if (deserialization) {
+      result.deserializationStrategies = new ArrayList<>(deserializationStrategies);
+      result.deserializationStrategies.add(exclusionStrategy);
+    }
+    return result;
+  }
+
+  @Override public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
+    Class<?> rawType = type.getRawType();
+    boolean excludeClass = excludeClassChecks(rawType);
+
+    final boolean skipSerialize = excludeClass || excludeClassInStrategy(rawType, true);
+    final boolean skipDeserialize = excludeClass ||  excludeClassInStrategy(rawType, false);
+
+    if (!skipSerialize && !skipDeserialize) {
+      return null;
+    }
+
+    return new TypeAdapter<T>() {
+      /** The delegate is lazily created because it may not be needed, and creating it may fail. */
+      private TypeAdapter<T> delegate;
+
+      @Override public T read(JsonReader in) throws IOException {
+        if (skipDeserialize) {
+          in.skipValue();
+          return null;
+        }
+        return delegate().read(in);
+      }
+
+      @Override public void write(JsonWriter out, T value) throws IOException {
+        if (skipSerialize) {
+          out.nullValue();
+          return;
+        }
+        delegate().write(out, value);
+      }
+
+      private TypeAdapter<T> delegate() {
+        TypeAdapter<T> d = delegate;
+        return d != null
+            ? d
+            : (delegate = gson.getDelegateAdapter(Excluder.this, type));
+      }
+    };
+  }
+
+  public boolean excludeField(Field field, boolean serialize) {
+    if ((modifiers & field.getModifiers()) != 0) {
+      return true;
+    }
+
+    if (version != Excluder.IGNORE_VERSIONS
+        && !isValidVersion(field.getAnnotation(Since.class), field.getAnnotation(Until.class))) {
+      return true;
+    }
+
+    if (field.isSynthetic()) {
+      return true;
+    }
+
+    if (requireExpose) {
+      Expose annotation = field.getAnnotation(Expose.class);
+      if (annotation == null || (serialize ? !annotation.serialize() : !annotation.deserialize())) {
+        return true;
+      }
+    }
+
+    if (!serializeInnerClasses && isInnerClass(field.getType())) {
+      return true;
+    }
+
+    if (isAnonymousOrNonStaticLocal(field.getType())) {
+      return true;
+    }
+
+    List<ExclusionStrategy> list = serialize ? serializationStrategies : deserializationStrategies;
+    if (!list.isEmpty()) {
+      FieldAttributes fieldAttributes = new FieldAttributes(field);
+      for (ExclusionStrategy exclusionStrategy : list) {
+        if (exclusionStrategy.shouldSkipField(fieldAttributes)) {
+          return true;
+        }
+      }
+    }
+
+    return false;
+  }
+
+  private boolean excludeClassChecks(Class<?> clazz) {
+      if (version != Excluder.IGNORE_VERSIONS && !isValidVersion(clazz.getAnnotation(Since.class), clazz.getAnnotation(Until.class))) {
+          return true;
+      }
+
+      if (!serializeInnerClasses && isInnerClass(clazz)) {
+          return true;
+      }
+
+      if (isAnonymousOrNonStaticLocal(clazz)) {
+          return true;
+      }
+
+      return false;
+  }
+
+  public boolean excludeClass(Class<?> clazz, boolean serialize) {
+      return excludeClassChecks(clazz) ||
+              excludeClassInStrategy(clazz, serialize);
+  }
+
+  private boolean excludeClassInStrategy(Class<?> clazz, boolean serialize) {
+      List<ExclusionStrategy> list = serialize ? serializationStrategies : deserializationStrategies;
+      for (ExclusionStrategy exclusionStrategy : list) {
+          if (exclusionStrategy.shouldSkipClass(clazz)) {
+              return true;
+          }
+      }
+      return false;
+  }
+
+  private boolean isAnonymousOrNonStaticLocal(Class<?> clazz) {
+    return !Enum.class.isAssignableFrom(clazz) && !isStatic(clazz)
+        && (clazz.isAnonymousClass() || clazz.isLocalClass());
+  }
+
+  private boolean isInnerClass(Class<?> clazz) {
+    return clazz.isMemberClass() && !isStatic(clazz);
+  }
+
+  private boolean isStatic(Class<?> clazz) {
+    return (clazz.getModifiers() & Modifier.STATIC) != 0;
+  }
+
+  private boolean isValidVersion(Since since, Until until) {
+    return isValidSince(since) && isValidUntil(until);
+  }
+
+  private boolean isValidSince(Since annotation) {
+    if (annotation != null) {
+      double annotationVersion = annotation.value();
+      if (annotationVersion > version) {
+        return false;
+      }
+    }
+    return true;
+  }
+
+  private boolean isValidUntil(Until annotation) {
+    if (annotation != null) {
+      double annotationVersion = annotation.value();
+      if (annotationVersion <= version) {
+        return false;
+      }
+    }
+    return true;
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/internal/JavaVersion.java b/gson/src/main/java/com/google/gson/internal/JavaVersion.java
new file mode 100644
index 0000000..fab1b7c
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/internal/JavaVersion.java
@@ -0,0 +1,92 @@
+/*
+ * Copyright (C) 2017 The Gson authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.internal;
+
+/**
+ * Utility to check the major Java version of the current JVM.
+ */
+public final class JavaVersion {
+  // Oracle defines naming conventions at http://www.oracle.com/technetwork/java/javase/versioning-naming-139433.html
+  // However, many alternate implementations differ. For example, Debian used 9-debian as the version string
+
+  private static final int majorJavaVersion = determineMajorJavaVersion();
+
+  private static int determineMajorJavaVersion() {
+    String javaVersion = System.getProperty("java.version");
+    return getMajorJavaVersion(javaVersion);
+  }
+
+  // Visible for testing only
+  static int getMajorJavaVersion(String javaVersion) {
+    int version = parseDotted(javaVersion);
+    if (version == -1) {
+      version = extractBeginningInt(javaVersion);
+    }
+    if (version == -1) {
+      return 6;  // Choose minimum supported JDK version as default
+    }
+    return version;
+  }
+
+  // Parses both legacy 1.8 style and newer 9.0.4 style 
+  private static int parseDotted(String javaVersion) {
+    try {
+      String[] parts = javaVersion.split("[._]");
+      int firstVer = Integer.parseInt(parts[0]);
+      if (firstVer == 1 && parts.length > 1) {
+        return Integer.parseInt(parts[1]);
+      } else {
+        return firstVer;
+      }
+    } catch (NumberFormatException e) {
+      return -1;
+    }
+  }
+
+  private static int extractBeginningInt(String javaVersion) {
+    try {
+      StringBuilder num = new StringBuilder();
+      for (int i = 0; i < javaVersion.length(); ++i) {
+        char c = javaVersion.charAt(i);
+        if (Character.isDigit(c)) {
+          num.append(c);
+        } else {
+          break;
+        }
+      }
+      return Integer.parseInt(num.toString());
+    } catch (NumberFormatException e) {
+      return -1;
+    }
+  }
+
+  /**
+   * @return the major Java version, i.e. '8' for Java 1.8, '9' for Java 9 etc.
+   */
+  public static int getMajorJavaVersion() {
+    return majorJavaVersion;
+  }
+
+  /**
+   * @return {@code true} if the application is running on Java 9 or later; and {@code false} otherwise.
+   */
+  public static boolean isJava9OrLater() {
+    return majorJavaVersion >= 9;
+  }
+
+  private JavaVersion() { }
+}
diff --git a/gson/src/main/java/com/google/gson/internal/JsonReaderInternalAccess.java b/gson/src/main/java/com/google/gson/internal/JsonReaderInternalAccess.java
new file mode 100644
index 0000000..bbd4720
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/internal/JsonReaderInternalAccess.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.internal;
+
+import com.google.gson.stream.JsonReader;
+import java.io.IOException;
+
+/**
+ * Internal-only APIs of JsonReader available only to other classes in Gson.
+ */
+public abstract class JsonReaderInternalAccess {
+  public static JsonReaderInternalAccess INSTANCE;
+
+  /**
+   * Changes the type of the current property name token to a string value.
+   */
+  public abstract void promoteNameToValue(JsonReader reader) throws IOException;
+}
diff --git a/gson/src/main/java/com/google/gson/internal/LazilyParsedNumber.java b/gson/src/main/java/com/google/gson/internal/LazilyParsedNumber.java
new file mode 100644
index 0000000..6138dff
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/internal/LazilyParsedNumber.java
@@ -0,0 +1,104 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.internal;
+
+import java.io.IOException;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
+import java.io.ObjectStreamException;
+import java.math.BigDecimal;
+
+/**
+ * This class holds a number value that is lazily converted to a specific number type
+ *
+ * @author Inderjeet Singh
+ */
+public final class LazilyParsedNumber extends Number {
+  private final String value;
+
+  /** @param value must not be null */
+  public LazilyParsedNumber(String value) {
+    this.value = value;
+  }
+
+  @Override
+  public int intValue() {
+    try {
+      return Integer.parseInt(value);
+    } catch (NumberFormatException e) {
+      try {
+        return (int) Long.parseLong(value);
+      } catch (NumberFormatException nfe) {
+        return new BigDecimal(value).intValue();
+      }
+    }
+  }
+
+  @Override
+  public long longValue() {
+    try {
+      return Long.parseLong(value);
+    } catch (NumberFormatException e) {
+      return new BigDecimal(value).longValue();
+    }
+  }
+
+  @Override
+  public float floatValue() {
+    return Float.parseFloat(value);
+  }
+
+  @Override
+  public double doubleValue() {
+    return Double.parseDouble(value);
+  }
+
+  @Override
+  public String toString() {
+    return value;
+  }
+
+  /**
+   * If somebody is unlucky enough to have to serialize one of these, serialize
+   * it as a BigDecimal so that they won't need Gson on the other side to
+   * deserialize it.
+   */
+  private Object writeReplace() throws ObjectStreamException {
+    return new BigDecimal(value);
+  }
+
+  private void readObject(ObjectInputStream in) throws IOException {
+    // Don't permit directly deserializing this class; writeReplace() should have written a replacement
+    throw new InvalidObjectException("Deserialization is unsupported");
+  }
+
+  @Override
+  public int hashCode() {
+    return value.hashCode();
+  }
+
+  @Override
+  public boolean equals(Object obj) {
+    if (this == obj) {
+      return true;
+    }
+    if (obj instanceof LazilyParsedNumber) {
+      LazilyParsedNumber other = (LazilyParsedNumber) obj;
+      return value == other.value || value.equals(other.value);
+    }
+    return false;
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/internal/LinkedTreeMap.java b/gson/src/main/java/com/google/gson/internal/LinkedTreeMap.java
new file mode 100644
index 0000000..40eb8bb
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/internal/LinkedTreeMap.java
@@ -0,0 +1,638 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ * Copyright (C) 2012 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.internal;
+
+import java.io.IOException;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
+import java.io.ObjectStreamException;
+import java.io.Serializable;
+import java.util.AbstractMap;
+import java.util.AbstractSet;
+import java.util.Comparator;
+import java.util.ConcurrentModificationException;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.NoSuchElementException;
+import java.util.Set;
+
+/**
+ * A map of comparable keys to values. Unlike {@code TreeMap}, this class uses
+ * insertion order for iteration order. Comparison order is only used as an
+ * optimization for efficient insertion and removal.
+ *
+ * <p>This implementation was derived from Android 4.1's TreeMap class.
+ */
+public final class LinkedTreeMap<K, V> extends AbstractMap<K, V> implements Serializable {
+  @SuppressWarnings({ "unchecked", "rawtypes" }) // to avoid Comparable<Comparable<Comparable<...>>>
+  private static final Comparator<Comparable> NATURAL_ORDER = new Comparator<Comparable>() {
+    @Override public int compare(Comparable a, Comparable b) {
+      return a.compareTo(b);
+    }
+  };
+
+  Comparator<? super K> comparator;
+  Node<K, V> root;
+  int size = 0;
+  int modCount = 0;
+
+  // Used to preserve iteration order
+  final Node<K, V> header = new Node<>();
+
+  /**
+   * Create a natural order, empty tree map whose keys must be mutually
+   * comparable and non-null.
+   */
+  @SuppressWarnings("unchecked") // unsafe! this assumes K is comparable
+  public LinkedTreeMap() {
+    this((Comparator<? super K>) NATURAL_ORDER);
+  }
+
+  /**
+   * Create a tree map ordered by {@code comparator}. This map's keys may only
+   * be null if {@code comparator} permits.
+   *
+   * @param comparator the comparator to order elements with, or {@code null} to
+   *     use the natural ordering.
+   */
+  @SuppressWarnings({ "unchecked", "rawtypes" }) // unsafe! if comparator is null, this assumes K is comparable
+  public LinkedTreeMap(Comparator<? super K> comparator) {
+    this.comparator = comparator != null
+        ? comparator
+        : (Comparator) NATURAL_ORDER;
+  }
+
+  @Override public int size() {
+    return size;
+  }
+
+  @Override public V get(Object key) {
+    Node<K, V> node = findByObject(key);
+    return node != null ? node.value : null;
+  }
+
+  @Override public boolean containsKey(Object key) {
+    return findByObject(key) != null;
+  }
+
+  @Override public V put(K key, V value) {
+    if (key == null) {
+      throw new NullPointerException("key == null");
+    }
+    Node<K, V> created = find(key, true);
+    V result = created.value;
+    created.value = value;
+    return result;
+  }
+
+  @Override public void clear() {
+    root = null;
+    size = 0;
+    modCount++;
+
+    // Clear iteration order
+    Node<K, V> header = this.header;
+    header.next = header.prev = header;
+  }
+
+  @Override public V remove(Object key) {
+    Node<K, V> node = removeInternalByKey(key);
+    return node != null ? node.value : null;
+  }
+
+  /**
+   * Returns the node at or adjacent to the given key, creating it if requested.
+   *
+   * @throws ClassCastException if {@code key} and the tree's keys aren't
+   *     mutually comparable.
+   */
+  Node<K, V> find(K key, boolean create) {
+    Comparator<? super K> comparator = this.comparator;
+    Node<K, V> nearest = root;
+    int comparison = 0;
+
+    if (nearest != null) {
+      // Micro-optimization: avoid polymorphic calls to Comparator.compare().
+      @SuppressWarnings("unchecked") // Throws a ClassCastException below if there's trouble.
+          Comparable<Object> comparableKey = (comparator == NATURAL_ORDER)
+          ? (Comparable<Object>) key
+          : null;
+
+      while (true) {
+        comparison = (comparableKey != null)
+            ? comparableKey.compareTo(nearest.key)
+            : comparator.compare(key, nearest.key);
+
+        // We found the requested key.
+        if (comparison == 0) {
+          return nearest;
+        }
+
+        // If it exists, the key is in a subtree. Go deeper.
+        Node<K, V> child = (comparison < 0) ? nearest.left : nearest.right;
+        if (child == null) {
+          break;
+        }
+
+        nearest = child;
+      }
+    }
+
+    // The key doesn't exist in this tree.
+    if (!create) {
+      return null;
+    }
+
+    // Create the node and add it to the tree or the table.
+    Node<K, V> header = this.header;
+    Node<K, V> created;
+    if (nearest == null) {
+      // Check that the value is comparable if we didn't do any comparisons.
+      if (comparator == NATURAL_ORDER && !(key instanceof Comparable)) {
+        throw new ClassCastException(key.getClass().getName() + " is not Comparable");
+      }
+      created = new Node<>(nearest, key, header, header.prev);
+      root = created;
+    } else {
+      created = new Node<>(nearest, key, header, header.prev);
+      if (comparison < 0) { // nearest.key is higher
+        nearest.left = created;
+      } else { // comparison > 0, nearest.key is lower
+        nearest.right = created;
+      }
+      rebalance(nearest, true);
+    }
+    size++;
+    modCount++;
+
+    return created;
+  }
+
+  @SuppressWarnings("unchecked")
+  Node<K, V> findByObject(Object key) {
+    try {
+      return key != null ? find((K) key, false) : null;
+    } catch (ClassCastException e) {
+      return null;
+    }
+  }
+
+  /**
+   * Returns this map's entry that has the same key and value as {@code
+   * entry}, or null if this map has no such entry.
+   *
+   * <p>This method uses the comparator for key equality rather than {@code
+   * equals}. If this map's comparator isn't consistent with equals (such as
+   * {@code String.CASE_INSENSITIVE_ORDER}), then {@code remove()} and {@code
+   * contains()} will violate the collections API.
+   */
+  Node<K, V> findByEntry(Entry<?, ?> entry) {
+    Node<K, V> mine = findByObject(entry.getKey());
+    boolean valuesEqual = mine != null && equal(mine.value, entry.getValue());
+    return valuesEqual ? mine : null;
+  }
+
+  private boolean equal(Object a, Object b) {
+    return a == b || (a != null && a.equals(b));
+  }
+
+  /**
+   * Removes {@code node} from this tree, rearranging the tree's structure as
+   * necessary.
+   *
+   * @param unlink true to also unlink this node from the iteration linked list.
+   */
+  void removeInternal(Node<K, V> node, boolean unlink) {
+    if (unlink) {
+      node.prev.next = node.next;
+      node.next.prev = node.prev;
+    }
+
+    Node<K, V> left = node.left;
+    Node<K, V> right = node.right;
+    Node<K, V> originalParent = node.parent;
+    if (left != null && right != null) {
+
+      /*
+       * To remove a node with both left and right subtrees, move an
+       * adjacent node from one of those subtrees into this node's place.
+       *
+       * Removing the adjacent node may change this node's subtrees. This
+       * node may no longer have two subtrees once the adjacent node is
+       * gone!
+       */
+
+      Node<K, V> adjacent = (left.height > right.height) ? left.last() : right.first();
+      removeInternal(adjacent, false); // takes care of rebalance and size--
+
+      int leftHeight = 0;
+      left = node.left;
+      if (left != null) {
+        leftHeight = left.height;
+        adjacent.left = left;
+        left.parent = adjacent;
+        node.left = null;
+      }
+
+      int rightHeight = 0;
+      right = node.right;
+      if (right != null) {
+        rightHeight = right.height;
+        adjacent.right = right;
+        right.parent = adjacent;
+        node.right = null;
+      }
+
+      adjacent.height = Math.max(leftHeight, rightHeight) + 1;
+      replaceInParent(node, adjacent);
+      return;
+    } else if (left != null) {
+      replaceInParent(node, left);
+      node.left = null;
+    } else if (right != null) {
+      replaceInParent(node, right);
+      node.right = null;
+    } else {
+      replaceInParent(node, null);
+    }
+
+    rebalance(originalParent, false);
+    size--;
+    modCount++;
+  }
+
+  Node<K, V> removeInternalByKey(Object key) {
+    Node<K, V> node = findByObject(key);
+    if (node != null) {
+      removeInternal(node, true);
+    }
+    return node;
+  }
+
+  private void replaceInParent(Node<K, V> node, Node<K, V> replacement) {
+    Node<K, V> parent = node.parent;
+    node.parent = null;
+    if (replacement != null) {
+      replacement.parent = parent;
+    }
+
+    if (parent != null) {
+      if (parent.left == node) {
+        parent.left = replacement;
+      } else {
+        assert (parent.right == node);
+        parent.right = replacement;
+      }
+    } else {
+      root = replacement;
+    }
+  }
+
+  /**
+   * Rebalances the tree by making any AVL rotations necessary between the
+   * newly-unbalanced node and the tree's root.
+   *
+   * @param insert true if the node was unbalanced by an insert; false if it
+   *     was by a removal.
+   */
+  private void rebalance(Node<K, V> unbalanced, boolean insert) {
+    for (Node<K, V> node = unbalanced; node != null; node = node.parent) {
+      Node<K, V> left = node.left;
+      Node<K, V> right = node.right;
+      int leftHeight = left != null ? left.height : 0;
+      int rightHeight = right != null ? right.height : 0;
+
+      int delta = leftHeight - rightHeight;
+      if (delta == -2) {
+        Node<K, V> rightLeft = right.left;
+        Node<K, V> rightRight = right.right;
+        int rightRightHeight = rightRight != null ? rightRight.height : 0;
+        int rightLeftHeight = rightLeft != null ? rightLeft.height : 0;
+
+        int rightDelta = rightLeftHeight - rightRightHeight;
+        if (rightDelta == -1 || (rightDelta == 0 && !insert)) {
+          rotateLeft(node); // AVL right right
+        } else {
+          assert (rightDelta == 1);
+          rotateRight(right); // AVL right left
+          rotateLeft(node);
+        }
+        if (insert) {
+          break; // no further rotations will be necessary
+        }
+
+      } else if (delta == 2) {
+        Node<K, V> leftLeft = left.left;
+        Node<K, V> leftRight = left.right;
+        int leftRightHeight = leftRight != null ? leftRight.height : 0;
+        int leftLeftHeight = leftLeft != null ? leftLeft.height : 0;
+
+        int leftDelta = leftLeftHeight - leftRightHeight;
+        if (leftDelta == 1 || (leftDelta == 0 && !insert)) {
+          rotateRight(node); // AVL left left
+        } else {
+          assert (leftDelta == -1);
+          rotateLeft(left); // AVL left right
+          rotateRight(node);
+        }
+        if (insert) {
+          break; // no further rotations will be necessary
+        }
+
+      } else if (delta == 0) {
+        node.height = leftHeight + 1; // leftHeight == rightHeight
+        if (insert) {
+          break; // the insert caused balance, so rebalancing is done!
+        }
+
+      } else {
+        assert (delta == -1 || delta == 1);
+        node.height = Math.max(leftHeight, rightHeight) + 1;
+        if (!insert) {
+          break; // the height hasn't changed, so rebalancing is done!
+        }
+      }
+    }
+  }
+
+  /**
+   * Rotates the subtree so that its root's right child is the new root.
+   */
+  private void rotateLeft(Node<K, V> root) {
+    Node<K, V> left = root.left;
+    Node<K, V> pivot = root.right;
+    Node<K, V> pivotLeft = pivot.left;
+    Node<K, V> pivotRight = pivot.right;
+
+    // move the pivot's left child to the root's right
+    root.right = pivotLeft;
+    if (pivotLeft != null) {
+      pivotLeft.parent = root;
+    }
+
+    replaceInParent(root, pivot);
+
+    // move the root to the pivot's left
+    pivot.left = root;
+    root.parent = pivot;
+
+    // fix heights
+    root.height = Math.max(left != null ? left.height : 0,
+        pivotLeft != null ? pivotLeft.height : 0) + 1;
+    pivot.height = Math.max(root.height,
+        pivotRight != null ? pivotRight.height : 0) + 1;
+  }
+
+  /**
+   * Rotates the subtree so that its root's left child is the new root.
+   */
+  private void rotateRight(Node<K, V> root) {
+    Node<K, V> pivot = root.left;
+    Node<K, V> right = root.right;
+    Node<K, V> pivotLeft = pivot.left;
+    Node<K, V> pivotRight = pivot.right;
+
+    // move the pivot's right child to the root's left
+    root.left = pivotRight;
+    if (pivotRight != null) {
+      pivotRight.parent = root;
+    }
+
+    replaceInParent(root, pivot);
+
+    // move the root to the pivot's right
+    pivot.right = root;
+    root.parent = pivot;
+
+    // fixup heights
+    root.height = Math.max(right != null ? right.height : 0,
+        pivotRight != null ? pivotRight.height : 0) + 1;
+    pivot.height = Math.max(root.height,
+        pivotLeft != null ? pivotLeft.height : 0) + 1;
+  }
+
+  private EntrySet entrySet;
+  private KeySet keySet;
+
+  @Override public Set<Entry<K, V>> entrySet() {
+    EntrySet result = entrySet;
+    return result != null ? result : (entrySet = new EntrySet());
+  }
+
+  @Override public Set<K> keySet() {
+    KeySet result = keySet;
+    return result != null ? result : (keySet = new KeySet());
+  }
+
+  static final class Node<K, V> implements Entry<K, V> {
+    Node<K, V> parent;
+    Node<K, V> left;
+    Node<K, V> right;
+    Node<K, V> next;
+    Node<K, V> prev;
+    final K key;
+    V value;
+    int height;
+
+    /** Create the header entry */
+    Node() {
+      key = null;
+      next = prev = this;
+    }
+
+    /** Create a regular entry */
+    Node(Node<K, V> parent, K key, Node<K, V> next, Node<K, V> prev) {
+      this.parent = parent;
+      this.key = key;
+      this.height = 1;
+      this.next = next;
+      this.prev = prev;
+      prev.next = this;
+      next.prev = this;
+    }
+
+    @Override public K getKey() {
+      return key;
+    }
+
+    @Override public V getValue() {
+      return value;
+    }
+
+    @Override public V setValue(V value) {
+      V oldValue = this.value;
+      this.value = value;
+      return oldValue;
+    }
+
+    @SuppressWarnings("rawtypes")
+    @Override public boolean equals(Object o) {
+      if (o instanceof Entry) {
+        Entry other = (Entry) o;
+        return (key == null ? other.getKey() == null : key.equals(other.getKey()))
+            && (value == null ? other.getValue() == null : value.equals(other.getValue()));
+      }
+      return false;
+    }
+
+    @Override public int hashCode() {
+      return (key == null ? 0 : key.hashCode())
+          ^ (value == null ? 0 : value.hashCode());
+    }
+
+    @Override public String toString() {
+      return key + "=" + value;
+    }
+
+    /**
+     * Returns the first node in this subtree.
+     */
+    public Node<K, V> first() {
+      Node<K, V> node = this;
+      Node<K, V> child = node.left;
+      while (child != null) {
+        node = child;
+        child = node.left;
+      }
+      return node;
+    }
+
+    /**
+     * Returns the last node in this subtree.
+     */
+    public Node<K, V> last() {
+      Node<K, V> node = this;
+      Node<K, V> child = node.right;
+      while (child != null) {
+        node = child;
+        child = node.right;
+      }
+      return node;
+    }
+  }
+
+  private abstract class LinkedTreeMapIterator<T> implements Iterator<T> {
+    Node<K, V> next = header.next;
+    Node<K, V> lastReturned = null;
+    int expectedModCount = modCount;
+
+    LinkedTreeMapIterator() {
+    }
+
+    @Override public final boolean hasNext() {
+      return next != header;
+    }
+
+    final Node<K, V> nextNode() {
+      Node<K, V> e = next;
+      if (e == header) {
+        throw new NoSuchElementException();
+      }
+      if (modCount != expectedModCount) {
+        throw new ConcurrentModificationException();
+      }
+      next = e.next;
+      return lastReturned = e;
+    }
+
+    @Override public final void remove() {
+      if (lastReturned == null) {
+        throw new IllegalStateException();
+      }
+      removeInternal(lastReturned, true);
+      lastReturned = null;
+      expectedModCount = modCount;
+    }
+  }
+
+  class EntrySet extends AbstractSet<Entry<K, V>> {
+    @Override public int size() {
+      return size;
+    }
+
+    @Override public Iterator<Entry<K, V>> iterator() {
+      return new LinkedTreeMapIterator<Entry<K, V>>() {
+        @Override public Entry<K, V> next() {
+          return nextNode();
+        }
+      };
+    }
+
+    @Override public boolean contains(Object o) {
+      return o instanceof Entry && findByEntry((Entry<?, ?>) o) != null;
+    }
+
+    @Override public boolean remove(Object o) {
+      if (!(o instanceof Entry)) {
+        return false;
+      }
+
+      Node<K, V> node = findByEntry((Entry<?, ?>) o);
+      if (node == null) {
+        return false;
+      }
+      removeInternal(node, true);
+      return true;
+    }
+
+    @Override public void clear() {
+      LinkedTreeMap.this.clear();
+    }
+  }
+
+  final class KeySet extends AbstractSet<K> {
+    @Override public int size() {
+      return size;
+    }
+
+    @Override public Iterator<K> iterator() {
+      return new LinkedTreeMapIterator<K>() {
+        @Override public K next() {
+          return nextNode().key;
+        }
+      };
+    }
+
+    @Override public boolean contains(Object o) {
+      return containsKey(o);
+    }
+
+    @Override public boolean remove(Object key) {
+      return removeInternalByKey(key) != null;
+    }
+
+    @Override public void clear() {
+      LinkedTreeMap.this.clear();
+    }
+  }
+
+  /**
+   * If somebody is unlucky enough to have to serialize one of these, serialize
+   * it as a LinkedHashMap so that they won't need Gson on the other side to
+   * deserialize it. Using serialization defeats our DoS defence, so most apps
+   * shouldn't use it.
+   */
+  private Object writeReplace() throws ObjectStreamException {
+    return new LinkedHashMap<>(this);
+  }
+
+  private void readObject(ObjectInputStream in) throws IOException {
+    // Don't permit directly deserializing this class; writeReplace() should have written a replacement
+    throw new InvalidObjectException("Deserialization is unsupported");
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/internal/ObjectConstructor.java b/gson/src/main/java/com/google/gson/internal/ObjectConstructor.java
new file mode 100644
index 0000000..6ef2060
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/internal/ObjectConstructor.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.internal;
+
+/**
+ * Defines a generic object construction factory.  The purpose of this class
+ * is to construct a default instance of a class that can be used for object
+ * navigation while deserialization from its JSON representation.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public interface ObjectConstructor<T> {
+
+  /**
+   * Returns a new instance.
+   */
+  public T construct();
+}
\ No newline at end of file
diff --git a/gson/src/main/java/com/google/gson/internal/PreJava9DateFormatProvider.java b/gson/src/main/java/com/google/gson/internal/PreJava9DateFormatProvider.java
new file mode 100644
index 0000000..beb527c
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/internal/PreJava9DateFormatProvider.java
@@ -0,0 +1,86 @@
+/*
+ * Copyright (C) 2017 The Gson authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.internal;
+
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.Locale;
+
+/**
+ * Provides DateFormats for US locale with patterns which were the default ones before Java 9.
+ */
+public class PreJava9DateFormatProvider {
+
+  /**
+   * Returns the same DateFormat as {@code DateFormat.getDateInstance(style, Locale.US)} in Java 8 or below.
+   */
+  public static DateFormat getUSDateFormat(int style) {
+    return new SimpleDateFormat(getDateFormatPattern(style), Locale.US);
+  }
+
+  /**
+   * Returns the same DateFormat as {@code DateFormat.getDateTimeInstance(dateStyle, timeStyle, Locale.US)}
+   * in Java 8 or below.
+   */
+  public static DateFormat getUSDateTimeFormat(int dateStyle, int timeStyle) {
+    String pattern = getDatePartOfDateTimePattern(dateStyle) + " " + getTimePartOfDateTimePattern(timeStyle);
+    return new SimpleDateFormat(pattern, Locale.US);
+  }
+
+  private static String getDateFormatPattern(int style) {
+    switch (style) {
+    case DateFormat.SHORT:
+      return "M/d/yy";
+    case DateFormat.MEDIUM:
+      return "MMM d, y";
+    case DateFormat.LONG:
+      return "MMMM d, y";
+    case DateFormat.FULL:
+      return "EEEE, MMMM d, y";
+    default:
+      throw new IllegalArgumentException("Unknown DateFormat style: " + style);
+    }
+  }
+
+  private static String getDatePartOfDateTimePattern(int dateStyle) {
+    switch (dateStyle) {
+    case DateFormat.SHORT:
+      return "M/d/yy";
+    case DateFormat.MEDIUM:
+      return "MMM d, yyyy";
+    case DateFormat.LONG:
+      return "MMMM d, yyyy";
+    case DateFormat.FULL:
+      return "EEEE, MMMM d, yyyy";
+    default:
+      throw new IllegalArgumentException("Unknown DateFormat style: " + dateStyle);
+    }
+  }
+
+  private static String getTimePartOfDateTimePattern(int timeStyle) {
+    switch (timeStyle) {
+    case DateFormat.SHORT:
+      return "h:mm a";
+    case DateFormat.MEDIUM:
+      return "h:mm:ss a";
+    case DateFormat.FULL:
+    case DateFormat.LONG:
+      return "h:mm:ss a z";
+    default:
+      throw new IllegalArgumentException("Unknown DateFormat style: " + timeStyle);
+    }
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/internal/Primitives.java b/gson/src/main/java/com/google/gson/internal/Primitives.java
new file mode 100644
index 0000000..2506fd0
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/internal/Primitives.java
@@ -0,0 +1,100 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.internal;
+
+import java.lang.reflect.Type;
+
+/**
+ * Contains static utility methods pertaining to primitive types and their
+ * corresponding wrapper types.
+ *
+ * @author Kevin Bourrillion
+ */
+public final class Primitives {
+  private Primitives() {}
+
+  /**
+   * Returns true if this type is a primitive.
+   */
+  public static boolean isPrimitive(Type type) {
+    return type instanceof Class<?> && ((Class<?>) type).isPrimitive();
+  }
+
+  /**
+   * Returns {@code true} if {@code type} is one of the nine
+   * primitive-wrapper types, such as {@link Integer}.
+   *
+   * @see Class#isPrimitive
+   */
+  public static boolean isWrapperType(Type type) {
+    return type == Integer.class
+        || type == Float.class
+        || type == Byte.class
+        || type == Double.class
+        || type == Long.class
+        || type == Character.class
+        || type == Boolean.class
+        || type == Short.class
+        || type == Void.class;
+  }
+
+  /**
+   * Returns the corresponding wrapper type of {@code type} if it is a primitive
+   * type; otherwise returns {@code type} itself. Idempotent.
+   * <pre>
+   *     wrap(int.class) == Integer.class
+   *     wrap(Integer.class) == Integer.class
+   *     wrap(String.class) == String.class
+   * </pre>
+   */
+  @SuppressWarnings("unchecked")
+  public static <T> Class<T> wrap(Class<T> type) {
+    if (type == int.class) return (Class<T>) Integer.class;
+    if (type == float.class) return (Class<T>) Float.class;
+    if (type == byte.class) return (Class<T>) Byte.class;
+    if (type == double.class) return (Class<T>) Double.class;
+    if (type == long.class) return (Class<T>) Long.class;
+    if (type == char.class) return (Class<T>) Character.class;
+    if (type == boolean.class) return (Class<T>) Boolean.class;
+    if (type == short.class) return (Class<T>) Short.class;
+    if (type == void.class) return (Class<T>) Void.class;
+    return type;
+  }
+
+  /**
+   * Returns the corresponding primitive type of {@code type} if it is a
+   * wrapper type; otherwise returns {@code type} itself. Idempotent.
+   * <pre>
+   *     unwrap(Integer.class) == int.class
+   *     unwrap(int.class) == int.class
+   *     unwrap(String.class) == String.class
+   * </pre>
+   */
+  @SuppressWarnings("unchecked")
+  public static <T> Class<T> unwrap(Class<T> type) {
+    if (type == Integer.class) return (Class<T>) int.class;
+    if (type == Float.class) return (Class<T>) float.class;
+    if (type == Byte.class) return (Class<T>) byte.class;
+    if (type == Double.class) return (Class<T>) double.class;
+    if (type == Long.class) return (Class<T>) long.class;
+    if (type == Character.class) return (Class<T>) char.class;
+    if (type == Boolean.class) return (Class<T>) boolean.class;
+    if (type == Short.class) return (Class<T>) short.class;
+    if (type == Void.class) return (Class<T>) void.class;
+    return type;
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/internal/ReflectionAccessFilterHelper.java b/gson/src/main/java/com/google/gson/internal/ReflectionAccessFilterHelper.java
new file mode 100644
index 0000000..a07b2c7
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/internal/ReflectionAccessFilterHelper.java
@@ -0,0 +1,101 @@
+package com.google.gson.internal;
+
+import java.lang.reflect.AccessibleObject;
+import java.lang.reflect.Method;
+import java.util.List;
+
+import com.google.gson.ReflectionAccessFilter;
+import com.google.gson.ReflectionAccessFilter.FilterResult;
+
+/**
+ * Internal helper class for {@link ReflectionAccessFilter}.
+ */
+public class ReflectionAccessFilterHelper {
+  private ReflectionAccessFilterHelper() { }
+
+  // Platform type detection is based on Moshi's Util.isPlatformType(Class)
+  // See https://github.com/square/moshi/blob/3c108919ee1cce88a433ffda04eeeddc0341eae7/moshi/src/main/java/com/squareup/moshi/internal/Util.java#L141
+
+  public static boolean isJavaType(Class<?> c) {
+    return isJavaType(c.getName());
+  }
+
+  private static boolean isJavaType(String className) {
+    return className.startsWith("java.") || className.startsWith("javax.");
+  }
+
+  public static boolean isAndroidType(Class<?> c) {
+    return isAndroidType(c.getName());
+  }
+
+  private static boolean isAndroidType(String className) {
+    return className.startsWith("android.")
+        || className.startsWith("androidx.")
+        || isJavaType(className);
+  }
+
+  public static boolean isAnyPlatformType(Class<?> c) {
+    String className = c.getName();
+    return isAndroidType(className) // Covers Android and Java
+      || className.startsWith("kotlin.")
+      || className.startsWith("kotlinx.")
+      || className.startsWith("scala.");
+  }
+
+  /**
+   * Gets the result of applying all filters until the first one returns a result
+   * other than {@link FilterResult#INDECISIVE}, or {@link FilterResult#ALLOW} if
+   * the list of filters is empty or all returned {@code INDECISIVE}.
+   */
+  public static FilterResult getFilterResult(List<ReflectionAccessFilter> reflectionFilters, Class<?> c) {
+    for (ReflectionAccessFilter filter : reflectionFilters) {
+      FilterResult result = filter.check(c);
+      if (result != FilterResult.INDECISIVE) {
+        return result;
+      }
+    }
+    return FilterResult.ALLOW;
+  }
+
+  /**
+   * See {@link AccessibleObject#canAccess(Object)} (Java >= 9)
+   */
+  public static boolean canAccess(AccessibleObject accessibleObject, Object object) {
+    return AccessChecker.INSTANCE.canAccess(accessibleObject, object);
+  }
+
+  private static abstract class AccessChecker {
+    public static final AccessChecker INSTANCE;
+    static {
+      AccessChecker accessChecker = null;
+      // TODO: Ideally should use Multi-Release JAR for this version specific code
+      if (JavaVersion.isJava9OrLater()) {
+        try {
+          final Method canAccessMethod = AccessibleObject.class.getDeclaredMethod("canAccess", Object.class);
+          accessChecker = new AccessChecker() {
+            @Override public boolean canAccess(AccessibleObject accessibleObject, Object object) {
+              try {
+                return (Boolean) canAccessMethod.invoke(accessibleObject, object);
+              } catch (Exception e) {
+                throw new RuntimeException("Failed invoking canAccess", e);
+              }
+            }
+          };
+        } catch (NoSuchMethodException ignored) {
+        }
+      }
+
+      if (accessChecker == null) {
+        accessChecker = new AccessChecker() {
+          @Override public boolean canAccess(AccessibleObject accessibleObject, Object object) {
+            // Cannot determine whether object can be accessed, so assume it can be accessed
+            return true;
+          }
+        };
+      }
+      INSTANCE = accessChecker;
+    }
+
+    public abstract boolean canAccess(AccessibleObject accessibleObject, Object object);
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/internal/Streams.java b/gson/src/main/java/com/google/gson/internal/Streams.java
new file mode 100644
index 0000000..0bb73aa
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/internal/Streams.java
@@ -0,0 +1,120 @@
+/*
+ * Copyright (C) 2010 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.internal;
+
+import com.google.gson.JsonElement;
+import com.google.gson.JsonIOException;
+import com.google.gson.JsonNull;
+import com.google.gson.JsonParseException;
+import com.google.gson.JsonSyntaxException;
+import com.google.gson.internal.bind.TypeAdapters;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonWriter;
+import com.google.gson.stream.MalformedJsonException;
+import java.io.EOFException;
+import java.io.IOException;
+import java.io.Writer;
+
+/**
+ * Reads and writes GSON parse trees over streams.
+ */
+public final class Streams {
+  private Streams() {
+    throw new UnsupportedOperationException();
+  }
+
+  /**
+   * Takes a reader in any state and returns the next value as a JsonElement.
+   */
+  public static JsonElement parse(JsonReader reader) throws JsonParseException {
+    boolean isEmpty = true;
+    try {
+      reader.peek();
+      isEmpty = false;
+      return TypeAdapters.JSON_ELEMENT.read(reader);
+    } catch (EOFException e) {
+      /*
+       * For compatibility with JSON 1.5 and earlier, we return a JsonNull for
+       * empty documents instead of throwing.
+       */
+      if (isEmpty) {
+        return JsonNull.INSTANCE;
+      }
+      // The stream ended prematurely so it is likely a syntax error.
+      throw new JsonSyntaxException(e);
+    } catch (MalformedJsonException e) {
+      throw new JsonSyntaxException(e);
+    } catch (IOException e) {
+      throw new JsonIOException(e);
+    } catch (NumberFormatException e) {
+      throw new JsonSyntaxException(e);
+    }
+  }
+
+  /**
+   * Writes the JSON element to the writer, recursively.
+   */
+  public static void write(JsonElement element, JsonWriter writer) throws IOException {
+    TypeAdapters.JSON_ELEMENT.write(writer, element);
+  }
+
+  public static Writer writerForAppendable(Appendable appendable) {
+    return appendable instanceof Writer ? (Writer) appendable : new AppendableWriter(appendable);
+  }
+
+  /**
+   * Adapts an {@link Appendable} so it can be passed anywhere a {@link Writer}
+   * is used.
+   */
+  private static final class AppendableWriter extends Writer {
+    private final Appendable appendable;
+    private final CurrentWrite currentWrite = new CurrentWrite();
+
+    AppendableWriter(Appendable appendable) {
+      this.appendable = appendable;
+    }
+
+    @Override public void write(char[] chars, int offset, int length) throws IOException {
+      currentWrite.chars = chars;
+      appendable.append(currentWrite, offset, offset + length);
+    }
+
+    @Override public void write(int i) throws IOException {
+      appendable.append((char) i);
+    }
+
+    @Override public void flush() {}
+    @Override public void close() {}
+
+    /**
+     * A mutable char sequence pointing at a single char[].
+     */
+    static class CurrentWrite implements CharSequence {
+      char[] chars;
+      @Override public int length() {
+        return chars.length;
+      }
+      @Override public char charAt(int i) {
+        return chars[i];
+      }
+      @Override public CharSequence subSequence(int start, int end) {
+        return new String(chars, start, end - start);
+      }
+    }
+  }
+
+}
diff --git a/gson/src/main/java/com/google/gson/internal/UnsafeAllocator.java b/gson/src/main/java/com/google/gson/internal/UnsafeAllocator.java
new file mode 100644
index 0000000..429bac6
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/internal/UnsafeAllocator.java
@@ -0,0 +1,140 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.internal;
+
+import java.io.ObjectInputStream;
+import java.io.ObjectStreamClass;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+
+/**
+ * Do sneaky things to allocate objects without invoking their constructors.
+ *
+ * @author Joel Leitch
+ * @author Jesse Wilson
+ */
+public abstract class UnsafeAllocator {
+  public abstract <T> T newInstance(Class<T> c) throws Exception;
+
+  /**
+   * Check if the class can be instantiated by Unsafe allocator. If the instance has interface or abstract modifiers
+   * return an exception message.
+   * @param c instance of the class to be checked
+   * @return if instantiable {@code null}, else a non-{@code null} exception message
+   */
+  static String checkInstantiable(Class<?> c) {
+    int modifiers = c.getModifiers();
+    if (Modifier.isInterface(modifiers)) {
+      return "Interfaces can't be instantiated! Register an InstanceCreator "
+          + "or a TypeAdapter for this type. Interface name: " + c.getName();
+    }
+    if (Modifier.isAbstract(modifiers)) {
+      return "Abstract classes can't be instantiated! Register an InstanceCreator "
+          + "or a TypeAdapter for this type. Class name: " + c.getName();
+    }
+    return null;
+  }
+
+  /**
+   * Asserts that the class is instantiable. This check should have already occurred
+   * in {@link ConstructorConstructor}; this check here acts as safeguard since trying
+   * to use Unsafe for non-instantiable classes might crash the JVM on some devices.
+   */
+  private static void assertInstantiable(Class<?> c) {
+    String exceptionMessage = checkInstantiable(c);
+    if (exceptionMessage != null) {
+      throw new AssertionError("UnsafeAllocator is used for non-instantiable type: " + exceptionMessage);
+    }
+  }
+
+  public static UnsafeAllocator create() {
+    // try JVM
+    // public class Unsafe {
+    //   public Object allocateInstance(Class<?> type);
+    // }
+    try {
+      Class<?> unsafeClass = Class.forName("sun.misc.Unsafe");
+      Field f = unsafeClass.getDeclaredField("theUnsafe");
+      f.setAccessible(true);
+      final Object unsafe = f.get(null);
+      final Method allocateInstance = unsafeClass.getMethod("allocateInstance", Class.class);
+      return new UnsafeAllocator() {
+        @Override
+        @SuppressWarnings("unchecked")
+        public <T> T newInstance(Class<T> c) throws Exception {
+          assertInstantiable(c);
+          return (T) allocateInstance.invoke(unsafe, c);
+        }
+      };
+    } catch (Exception ignored) {
+    }
+
+    // try dalvikvm, post-gingerbread
+    // public class ObjectStreamClass {
+    //   private static native int getConstructorId(Class<?> c);
+    //   private static native Object newInstance(Class<?> instantiationClass, int methodId);
+    // }
+    try {
+      Method getConstructorId = ObjectStreamClass.class
+          .getDeclaredMethod("getConstructorId", Class.class);
+      getConstructorId.setAccessible(true);
+      final int constructorId = (Integer) getConstructorId.invoke(null, Object.class);
+      final Method newInstance = ObjectStreamClass.class
+          .getDeclaredMethod("newInstance", Class.class, int.class);
+      newInstance.setAccessible(true);
+      return new UnsafeAllocator() {
+        @Override
+        @SuppressWarnings("unchecked")
+        public <T> T newInstance(Class<T> c) throws Exception {
+          assertInstantiable(c);
+          return (T) newInstance.invoke(null, c, constructorId);
+        }
+      };
+    } catch (Exception ignored) {
+    }
+
+    // try dalvikvm, pre-gingerbread
+    // public class ObjectInputStream {
+    //   private static native Object newInstance(
+    //     Class<?> instantiationClass, Class<?> constructorClass);
+    // }
+    try {
+      final Method newInstance = ObjectInputStream.class
+          .getDeclaredMethod("newInstance", Class.class, Class.class);
+      newInstance.setAccessible(true);
+      return new UnsafeAllocator() {
+        @Override
+        @SuppressWarnings("unchecked")
+        public <T> T newInstance(Class<T> c) throws Exception {
+          assertInstantiable(c);
+          return (T) newInstance.invoke(null, c, Object.class);
+        }
+      };
+    } catch (Exception ignored) {
+    }
+
+    // give up
+    return new UnsafeAllocator() {
+      @Override
+      public <T> T newInstance(Class<T> c) {
+        throw new UnsupportedOperationException("Cannot allocate " + c + ". Usage of JDK sun.misc.Unsafe is enabled, "
+            + "but it could not be used. Make sure your runtime is configured correctly.");
+      }
+    };
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/internal/bind/ArrayTypeAdapter.java b/gson/src/main/java/com/google/gson/internal/bind/ArrayTypeAdapter.java
new file mode 100644
index 0000000..efaa834
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/internal/bind/ArrayTypeAdapter.java
@@ -0,0 +1,99 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.internal.bind;
+
+import java.io.IOException;
+import java.lang.reflect.Array;
+import java.lang.reflect.GenericArrayType;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.List;
+
+import com.google.gson.Gson;
+import com.google.gson.TypeAdapter;
+import com.google.gson.TypeAdapterFactory;
+import com.google.gson.internal.$Gson$Types;
+import com.google.gson.reflect.TypeToken;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonToken;
+import com.google.gson.stream.JsonWriter;
+
+/**
+ * Adapt an array of objects.
+ */
+public final class ArrayTypeAdapter<E> extends TypeAdapter<Object> {
+  public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() {
+    @SuppressWarnings({"unchecked", "rawtypes"})
+    @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
+      Type type = typeToken.getType();
+      if (!(type instanceof GenericArrayType || type instanceof Class && ((Class<?>) type).isArray())) {
+        return null;
+      }
+
+      Type componentType = $Gson$Types.getArrayComponentType(type);
+      TypeAdapter<?> componentTypeAdapter = gson.getAdapter(TypeToken.get(componentType));
+      return new ArrayTypeAdapter(
+              gson, componentTypeAdapter, $Gson$Types.getRawType(componentType));
+    }
+  };
+
+  private final Class<E> componentType;
+  private final TypeAdapter<E> componentTypeAdapter;
+
+  public ArrayTypeAdapter(Gson context, TypeAdapter<E> componentTypeAdapter, Class<E> componentType) {
+    this.componentTypeAdapter =
+      new TypeAdapterRuntimeTypeWrapper<>(context, componentTypeAdapter, componentType);
+    this.componentType = componentType;
+  }
+
+  @Override public Object read(JsonReader in) throws IOException {
+    if (in.peek() == JsonToken.NULL) {
+      in.nextNull();
+      return null;
+    }
+
+    List<E> list = new ArrayList<>();
+    in.beginArray();
+    while (in.hasNext()) {
+      E instance = componentTypeAdapter.read(in);
+      list.add(instance);
+    }
+    in.endArray();
+
+    int size = list.size();
+    Object array = Array.newInstance(componentType, size);
+    for (int i = 0; i < size; i++) {
+      Array.set(array, i, list.get(i));
+    }
+    return array;
+  }
+
+  @SuppressWarnings("unchecked")
+  @Override public void write(JsonWriter out, Object array) throws IOException {
+    if (array == null) {
+      out.nullValue();
+      return;
+    }
+
+    out.beginArray();
+    for (int i = 0, length = Array.getLength(array); i < length; i++) {
+      E value = (E) Array.get(array, i);
+      componentTypeAdapter.write(out, value);
+    }
+    out.endArray();
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/internal/bind/CollectionTypeAdapterFactory.java b/gson/src/main/java/com/google/gson/internal/bind/CollectionTypeAdapterFactory.java
new file mode 100644
index 0000000..8c65491
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/internal/bind/CollectionTypeAdapterFactory.java
@@ -0,0 +1,102 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.internal.bind;
+
+import com.google.gson.Gson;
+import com.google.gson.TypeAdapter;
+import com.google.gson.TypeAdapterFactory;
+import com.google.gson.internal.$Gson$Types;
+import com.google.gson.internal.ConstructorConstructor;
+import com.google.gson.internal.ObjectConstructor;
+import com.google.gson.reflect.TypeToken;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonToken;
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
+import java.lang.reflect.Type;
+import java.util.Collection;
+
+/**
+ * Adapt a homogeneous collection of objects.
+ */
+public final class CollectionTypeAdapterFactory implements TypeAdapterFactory {
+  private final ConstructorConstructor constructorConstructor;
+
+  public CollectionTypeAdapterFactory(ConstructorConstructor constructorConstructor) {
+    this.constructorConstructor = constructorConstructor;
+  }
+
+  @Override
+  public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
+    Type type = typeToken.getType();
+
+    Class<? super T> rawType = typeToken.getRawType();
+    if (!Collection.class.isAssignableFrom(rawType)) {
+      return null;
+    }
+
+    Type elementType = $Gson$Types.getCollectionElementType(type, rawType);
+    TypeAdapter<?> elementTypeAdapter = gson.getAdapter(TypeToken.get(elementType));
+    ObjectConstructor<T> constructor = constructorConstructor.get(typeToken);
+
+    @SuppressWarnings({"unchecked", "rawtypes"}) // create() doesn't define a type parameter
+    TypeAdapter<T> result = new Adapter(gson, elementType, elementTypeAdapter, constructor);
+    return result;
+  }
+
+  private static final class Adapter<E> extends TypeAdapter<Collection<E>> {
+    private final TypeAdapter<E> elementTypeAdapter;
+    private final ObjectConstructor<? extends Collection<E>> constructor;
+
+    public Adapter(Gson context, Type elementType,
+        TypeAdapter<E> elementTypeAdapter,
+        ObjectConstructor<? extends Collection<E>> constructor) {
+      this.elementTypeAdapter =
+          new TypeAdapterRuntimeTypeWrapper<>(context, elementTypeAdapter, elementType);
+      this.constructor = constructor;
+    }
+
+    @Override public Collection<E> read(JsonReader in) throws IOException {
+      if (in.peek() == JsonToken.NULL) {
+        in.nextNull();
+        return null;
+      }
+
+      Collection<E> collection = constructor.construct();
+      in.beginArray();
+      while (in.hasNext()) {
+        E instance = elementTypeAdapter.read(in);
+        collection.add(instance);
+      }
+      in.endArray();
+      return collection;
+    }
+
+    @Override public void write(JsonWriter out, Collection<E> collection) throws IOException {
+      if (collection == null) {
+        out.nullValue();
+        return;
+      }
+
+      out.beginArray();
+      for (E element : collection) {
+        elementTypeAdapter.write(out, element);
+      }
+      out.endArray();
+    }
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/internal/bind/DateTypeAdapter.java b/gson/src/main/java/com/google/gson/internal/bind/DateTypeAdapter.java
new file mode 100644
index 0000000..decd3c5
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/internal/bind/DateTypeAdapter.java
@@ -0,0 +1,107 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.internal.bind;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonSyntaxException;
+import com.google.gson.TypeAdapter;
+import com.google.gson.TypeAdapterFactory;
+import com.google.gson.internal.JavaVersion;
+import com.google.gson.internal.PreJava9DateFormatProvider;
+import com.google.gson.internal.bind.util.ISO8601Utils;
+import com.google.gson.reflect.TypeToken;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonToken;
+import com.google.gson.stream.JsonWriter;
+
+import java.io.IOException;
+import java.text.DateFormat;
+import java.text.ParseException;
+import java.text.ParsePosition;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.Locale;
+
+/**
+ * Adapter for Date. Although this class appears stateless, it is not.
+ * DateFormat captures its time zone and locale when it is created, which gives
+ * this class state. DateFormat isn't thread safe either, so this class has
+ * to synchronize its read and write methods.
+ */
+public final class DateTypeAdapter extends TypeAdapter<Date> {
+  public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() {
+    @SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal
+    @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
+      return typeToken.getRawType() == Date.class ? (TypeAdapter<T>) new DateTypeAdapter() : null;
+    }
+  };
+
+  /**
+   * List of 1 or more different date formats used for de-serialization attempts.
+   * The first of them (default US format) is used for serialization as well.
+   */
+  private final List<DateFormat> dateFormats = new ArrayList<>();
+
+  public DateTypeAdapter() {
+    dateFormats.add(DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.US));
+    if (!Locale.getDefault().equals(Locale.US)) {
+      dateFormats.add(DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT));
+    }
+    if (JavaVersion.isJava9OrLater()) {
+      dateFormats.add(PreJava9DateFormatProvider.getUSDateTimeFormat(DateFormat.DEFAULT, DateFormat.DEFAULT));
+    }
+  }
+
+  @Override public Date read(JsonReader in) throws IOException {
+    if (in.peek() == JsonToken.NULL) {
+      in.nextNull();
+      return null;
+    }
+    return deserializeToDate(in);
+  }
+
+  private Date deserializeToDate(JsonReader in) throws IOException {
+    String s = in.nextString();
+    synchronized (dateFormats) {
+      for (DateFormat dateFormat : dateFormats) {
+        try {
+          return dateFormat.parse(s);
+        } catch (ParseException ignored) {}
+      }
+    }
+    try {
+      return ISO8601Utils.parse(s, new ParsePosition(0));
+    } catch (ParseException e) {
+      throw new JsonSyntaxException("Failed parsing '" + s + "' as Date; at path " + in.getPreviousPath(), e);
+    }
+  }
+
+  @Override public void write(JsonWriter out, Date value) throws IOException {
+    if (value == null) {
+      out.nullValue();
+      return;
+    }
+
+    DateFormat dateFormat = dateFormats.get(0);
+    String dateFormatAsString;
+    synchronized (dateFormats) {
+      dateFormatAsString = dateFormat.format(value);
+    }
+    out.value(dateFormatAsString);
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/internal/bind/DefaultDateTypeAdapter.java b/gson/src/main/java/com/google/gson/internal/bind/DefaultDateTypeAdapter.java
new file mode 100644
index 0000000..0b7435f
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/internal/bind/DefaultDateTypeAdapter.java
@@ -0,0 +1,178 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.internal.bind;
+
+import java.io.IOException;
+import java.text.DateFormat;
+import java.text.ParseException;
+import java.text.ParsePosition;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.Locale;
+
+import com.google.gson.JsonSyntaxException;
+import com.google.gson.TypeAdapter;
+import com.google.gson.TypeAdapterFactory;
+import com.google.gson.internal.$Gson$Preconditions;
+import com.google.gson.internal.JavaVersion;
+import com.google.gson.internal.PreJava9DateFormatProvider;
+import com.google.gson.internal.bind.util.ISO8601Utils;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonToken;
+import com.google.gson.stream.JsonWriter;
+
+/**
+ * This type adapter supports subclasses of date by defining a
+ * {@link DefaultDateTypeAdapter.DateType} and then using its {@code createAdapterFactory}
+ * methods.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public final class DefaultDateTypeAdapter<T extends Date> extends TypeAdapter<T> {
+  private static final String SIMPLE_NAME = "DefaultDateTypeAdapter";
+
+  public static abstract class DateType<T extends Date> {
+    public static final DateType<Date> DATE = new DateType<Date>(Date.class) {
+      @Override protected Date deserialize(Date date) {
+        return date;
+      }
+    };
+
+    private final Class<T> dateClass;
+
+    protected DateType(Class<T> dateClass) {
+      this.dateClass = dateClass;
+    }
+
+    protected abstract T deserialize(Date date);
+
+    private final TypeAdapterFactory createFactory(DefaultDateTypeAdapter<T> adapter) {
+      return TypeAdapters.newFactory(dateClass, adapter);
+    }
+
+    public final TypeAdapterFactory createAdapterFactory(String datePattern) {
+      return createFactory(new DefaultDateTypeAdapter<>(this, datePattern));
+    }
+
+    public final TypeAdapterFactory createAdapterFactory(int style) {
+      return createFactory(new DefaultDateTypeAdapter<>(this, style));
+    }
+
+    public final TypeAdapterFactory createAdapterFactory(int dateStyle, int timeStyle) {
+      return createFactory(new DefaultDateTypeAdapter<>(this, dateStyle, timeStyle));
+    }
+
+    public final TypeAdapterFactory createDefaultsAdapterFactory() {
+      return createFactory(new DefaultDateTypeAdapter<>(this, DateFormat.DEFAULT, DateFormat.DEFAULT));
+    }
+  }
+
+  private final DateType<T> dateType;
+
+  /**
+   * List of 1 or more different date formats used for de-serialization attempts.
+   * The first of them is used for serialization as well.
+   */
+  private final List<DateFormat> dateFormats = new ArrayList<>();
+
+  private DefaultDateTypeAdapter(DateType<T> dateType, String datePattern) {
+    this.dateType = $Gson$Preconditions.checkNotNull(dateType);
+    dateFormats.add(new SimpleDateFormat(datePattern, Locale.US));
+    if (!Locale.getDefault().equals(Locale.US)) {
+      dateFormats.add(new SimpleDateFormat(datePattern));
+    }
+  }
+
+  private DefaultDateTypeAdapter(DateType<T> dateType, int style) {
+    this.dateType = $Gson$Preconditions.checkNotNull(dateType);
+    dateFormats.add(DateFormat.getDateInstance(style, Locale.US));
+    if (!Locale.getDefault().equals(Locale.US)) {
+      dateFormats.add(DateFormat.getDateInstance(style));
+    }
+    if (JavaVersion.isJava9OrLater()) {
+      dateFormats.add(PreJava9DateFormatProvider.getUSDateFormat(style));
+    }
+  }
+
+  private DefaultDateTypeAdapter(DateType<T> dateType, int dateStyle, int timeStyle) {
+    this.dateType = $Gson$Preconditions.checkNotNull(dateType);
+    dateFormats.add(DateFormat.getDateTimeInstance(dateStyle, timeStyle, Locale.US));
+    if (!Locale.getDefault().equals(Locale.US)) {
+      dateFormats.add(DateFormat.getDateTimeInstance(dateStyle, timeStyle));
+    }
+    if (JavaVersion.isJava9OrLater()) {
+      dateFormats.add(PreJava9DateFormatProvider.getUSDateTimeFormat(dateStyle, timeStyle));
+    }
+  }
+
+  // These methods need to be synchronized since JDK DateFormat classes are not thread-safe
+  // See issue 162
+  @Override
+  public void write(JsonWriter out, Date value) throws IOException {
+    if (value == null) {
+      out.nullValue();
+      return;
+    }
+
+    DateFormat dateFormat = dateFormats.get(0);
+    String dateFormatAsString;
+    synchronized (dateFormats) {
+      dateFormatAsString = dateFormat.format(value);
+    }
+    out.value(dateFormatAsString);
+  }
+
+  @Override
+  public T read(JsonReader in) throws IOException {
+    if (in.peek() == JsonToken.NULL) {
+      in.nextNull();
+      return null;
+    }
+    Date date = deserializeToDate(in);
+    return dateType.deserialize(date);
+  }
+
+  private Date deserializeToDate(JsonReader in) throws IOException {
+    String s = in.nextString();
+    synchronized (dateFormats) {
+      for (DateFormat dateFormat : dateFormats) {
+        try {
+          return dateFormat.parse(s);
+        } catch (ParseException ignored) {}
+      }
+    }
+
+    try {
+      return ISO8601Utils.parse(s, new ParsePosition(0));
+    } catch (ParseException e) {
+      throw new JsonSyntaxException("Failed parsing '" + s + "' as Date; at path " + in.getPreviousPath(), e);
+    }
+  }
+
+  @Override
+  public String toString() {
+    DateFormat defaultFormat = dateFormats.get(0);
+    if (defaultFormat instanceof SimpleDateFormat) {
+      return SIMPLE_NAME + '(' + ((SimpleDateFormat) defaultFormat).toPattern() + ')';
+    } else {
+      return SIMPLE_NAME + '(' + defaultFormat.getClass().getSimpleName() + ')';
+    }
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/internal/bind/JsonAdapterAnnotationTypeAdapterFactory.java b/gson/src/main/java/com/google/gson/internal/bind/JsonAdapterAnnotationTypeAdapterFactory.java
new file mode 100644
index 0000000..13a7bb7
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/internal/bind/JsonAdapterAnnotationTypeAdapterFactory.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2014 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.internal.bind;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonDeserializer;
+import com.google.gson.JsonSerializer;
+import com.google.gson.TypeAdapter;
+import com.google.gson.TypeAdapterFactory;
+import com.google.gson.annotations.JsonAdapter;
+import com.google.gson.internal.ConstructorConstructor;
+import com.google.gson.reflect.TypeToken;
+
+/**
+ * Given a type T, looks for the annotation {@link JsonAdapter} and uses an instance of the
+ * specified class as the default type adapter.
+ *
+ * @since 2.3
+ */
+public final class JsonAdapterAnnotationTypeAdapterFactory implements TypeAdapterFactory {
+  private final ConstructorConstructor constructorConstructor;
+
+  public JsonAdapterAnnotationTypeAdapterFactory(ConstructorConstructor constructorConstructor) {
+    this.constructorConstructor = constructorConstructor;
+  }
+
+  @SuppressWarnings("unchecked")
+  @Override
+  public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> targetType) {
+    Class<? super T> rawType = targetType.getRawType();
+    JsonAdapter annotation = rawType.getAnnotation(JsonAdapter.class);
+    if (annotation == null) {
+      return null;
+    }
+    return (TypeAdapter<T>) getTypeAdapter(constructorConstructor, gson, targetType, annotation);
+  }
+
+  @SuppressWarnings({ "unchecked", "rawtypes" }) // Casts guarded by conditionals.
+  TypeAdapter<?> getTypeAdapter(ConstructorConstructor constructorConstructor, Gson gson,
+      TypeToken<?> type, JsonAdapter annotation) {
+    Object instance = constructorConstructor.get(TypeToken.get(annotation.value())).construct();
+
+    TypeAdapter<?> typeAdapter;
+    if (instance instanceof TypeAdapter) {
+      typeAdapter = (TypeAdapter<?>) instance;
+    } else if (instance instanceof TypeAdapterFactory) {
+      typeAdapter = ((TypeAdapterFactory) instance).create(gson, type);
+    } else if (instance instanceof JsonSerializer || instance instanceof JsonDeserializer) {
+      JsonSerializer<?> serializer = instance instanceof JsonSerializer
+          ? (JsonSerializer) instance
+          : null;
+      JsonDeserializer<?> deserializer = instance instanceof JsonDeserializer
+          ? (JsonDeserializer) instance
+          : null;
+      typeAdapter = new TreeTypeAdapter(serializer, deserializer, gson, type, null);
+    } else {
+      throw new IllegalArgumentException("Invalid attempt to bind an instance of "
+          + instance.getClass().getName() + " as a @JsonAdapter for " + type.toString()
+          + ". @JsonAdapter value must be a TypeAdapter, TypeAdapterFactory,"
+          + " JsonSerializer or JsonDeserializer.");
+    }
+
+    if (typeAdapter != null && annotation.nullSafe()) {
+      typeAdapter = typeAdapter.nullSafe();
+    }
+
+    return typeAdapter;
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/internal/bind/JsonTreeReader.java b/gson/src/main/java/com/google/gson/internal/bind/JsonTreeReader.java
new file mode 100644
index 0000000..a753402
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/internal/bind/JsonTreeReader.java
@@ -0,0 +1,344 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.internal.bind;
+
+import com.google.gson.JsonArray;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonNull;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonPrimitive;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonToken;
+import java.io.IOException;
+import java.io.Reader;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Arrays;
+
+/**
+ * This reader walks the elements of a JsonElement as if it was coming from a
+ * character stream.
+ *
+ * @author Jesse Wilson
+ */
+public final class JsonTreeReader extends JsonReader {
+  private static final Reader UNREADABLE_READER = new Reader() {
+    @Override public int read(char[] buffer, int offset, int count) throws IOException {
+      throw new AssertionError();
+    }
+    @Override public void close() throws IOException {
+      throw new AssertionError();
+    }
+  };
+  private static final Object SENTINEL_CLOSED = new Object();
+
+  /*
+   * The nesting stack. Using a manual array rather than an ArrayList saves 20%.
+   */
+  private Object[] stack = new Object[32];
+  private int stackSize = 0;
+
+  /*
+   * The path members. It corresponds directly to stack: At indices where the
+   * stack contains an object (EMPTY_OBJECT, DANGLING_NAME or NONEMPTY_OBJECT),
+   * pathNames contains the name at this scope. Where it contains an array
+   * (EMPTY_ARRAY, NONEMPTY_ARRAY) pathIndices contains the current index in
+   * that array. Otherwise the value is undefined, and we take advantage of that
+   * by incrementing pathIndices when doing so isn't useful.
+   */
+  private String[] pathNames = new String[32];
+  private int[] pathIndices = new int[32];
+
+  public JsonTreeReader(JsonElement element) {
+    super(UNREADABLE_READER);
+    push(element);
+  }
+
+  @Override public void beginArray() throws IOException {
+    expect(JsonToken.BEGIN_ARRAY);
+    JsonArray array = (JsonArray) peekStack();
+    push(array.iterator());
+    pathIndices[stackSize - 1] = 0;
+  }
+
+  @Override public void endArray() throws IOException {
+    expect(JsonToken.END_ARRAY);
+    popStack(); // empty iterator
+    popStack(); // array
+    if (stackSize > 0) {
+      pathIndices[stackSize - 1]++;
+    }
+  }
+
+  @Override public void beginObject() throws IOException {
+    expect(JsonToken.BEGIN_OBJECT);
+    JsonObject object = (JsonObject) peekStack();
+    push(object.entrySet().iterator());
+  }
+
+  @Override public void endObject() throws IOException {
+    expect(JsonToken.END_OBJECT);
+    popStack(); // empty iterator
+    popStack(); // object
+    if (stackSize > 0) {
+      pathIndices[stackSize - 1]++;
+    }
+  }
+
+  @Override public boolean hasNext() throws IOException {
+    JsonToken token = peek();
+    return token != JsonToken.END_OBJECT && token != JsonToken.END_ARRAY && token != JsonToken.END_DOCUMENT;
+  }
+
+  @Override public JsonToken peek() throws IOException {
+    if (stackSize == 0) {
+      return JsonToken.END_DOCUMENT;
+    }
+
+    Object o = peekStack();
+    if (o instanceof Iterator) {
+      boolean isObject = stack[stackSize - 2] instanceof JsonObject;
+      Iterator<?> iterator = (Iterator<?>) o;
+      if (iterator.hasNext()) {
+        if (isObject) {
+          return JsonToken.NAME;
+        } else {
+          push(iterator.next());
+          return peek();
+        }
+      } else {
+        return isObject ? JsonToken.END_OBJECT : JsonToken.END_ARRAY;
+      }
+    } else if (o instanceof JsonObject) {
+      return JsonToken.BEGIN_OBJECT;
+    } else if (o instanceof JsonArray) {
+      return JsonToken.BEGIN_ARRAY;
+    } else if (o instanceof JsonPrimitive) {
+      JsonPrimitive primitive = (JsonPrimitive) o;
+      if (primitive.isString()) {
+        return JsonToken.STRING;
+      } else if (primitive.isBoolean()) {
+        return JsonToken.BOOLEAN;
+      } else if (primitive.isNumber()) {
+        return JsonToken.NUMBER;
+      } else {
+        throw new AssertionError();
+      }
+    } else if (o instanceof JsonNull) {
+      return JsonToken.NULL;
+    } else if (o == SENTINEL_CLOSED) {
+      throw new IllegalStateException("JsonReader is closed");
+    } else {
+      throw new AssertionError();
+    }
+  }
+
+  private Object peekStack() {
+    return stack[stackSize - 1];
+  }
+
+  private Object popStack() {
+    Object result = stack[--stackSize];
+    stack[stackSize] = null;
+    return result;
+  }
+
+  private void expect(JsonToken expected) throws IOException {
+    if (peek() != expected) {
+      throw new IllegalStateException(
+          "Expected " + expected + " but was " + peek() + locationString());
+    }
+  }
+
+  @Override public String nextName() throws IOException {
+    expect(JsonToken.NAME);
+    Iterator<?> i = (Iterator<?>) peekStack();
+    Map.Entry<?, ?> entry = (Map.Entry<?, ?>) i.next();
+    String result = (String) entry.getKey();
+    pathNames[stackSize - 1] = result;
+    push(entry.getValue());
+    return result;
+  }
+
+  @Override public String nextString() throws IOException {
+    JsonToken token = peek();
+    if (token != JsonToken.STRING && token != JsonToken.NUMBER) {
+      throw new IllegalStateException(
+          "Expected " + JsonToken.STRING + " but was " + token + locationString());
+    }
+    String result = ((JsonPrimitive) popStack()).getAsString();
+    if (stackSize > 0) {
+      pathIndices[stackSize - 1]++;
+    }
+    return result;
+  }
+
+  @Override public boolean nextBoolean() throws IOException {
+    expect(JsonToken.BOOLEAN);
+    boolean result = ((JsonPrimitive) popStack()).getAsBoolean();
+    if (stackSize > 0) {
+      pathIndices[stackSize - 1]++;
+    }
+    return result;
+  }
+
+  @Override public void nextNull() throws IOException {
+    expect(JsonToken.NULL);
+    popStack();
+    if (stackSize > 0) {
+      pathIndices[stackSize - 1]++;
+    }
+  }
+
+  @Override public double nextDouble() throws IOException {
+    JsonToken token = peek();
+    if (token != JsonToken.NUMBER && token != JsonToken.STRING) {
+      throw new IllegalStateException(
+          "Expected " + JsonToken.NUMBER + " but was " + token + locationString());
+    }
+    double result = ((JsonPrimitive) peekStack()).getAsDouble();
+    if (!isLenient() && (Double.isNaN(result) || Double.isInfinite(result))) {
+      throw new NumberFormatException("JSON forbids NaN and infinities: " + result);
+    }
+    popStack();
+    if (stackSize > 0) {
+      pathIndices[stackSize - 1]++;
+    }
+    return result;
+  }
+
+  @Override public long nextLong() throws IOException {
+    JsonToken token = peek();
+    if (token != JsonToken.NUMBER && token != JsonToken.STRING) {
+      throw new IllegalStateException(
+          "Expected " + JsonToken.NUMBER + " but was " + token + locationString());
+    }
+    long result = ((JsonPrimitive) peekStack()).getAsLong();
+    popStack();
+    if (stackSize > 0) {
+      pathIndices[stackSize - 1]++;
+    }
+    return result;
+  }
+
+  @Override public int nextInt() throws IOException {
+    JsonToken token = peek();
+    if (token != JsonToken.NUMBER && token != JsonToken.STRING) {
+      throw new IllegalStateException(
+          "Expected " + JsonToken.NUMBER + " but was " + token + locationString());
+    }
+    int result = ((JsonPrimitive) peekStack()).getAsInt();
+    popStack();
+    if (stackSize > 0) {
+      pathIndices[stackSize - 1]++;
+    }
+    return result;
+  }
+
+  JsonElement nextJsonElement() throws IOException {
+    final JsonToken peeked = peek();
+    if (peeked == JsonToken.NAME
+        || peeked == JsonToken.END_ARRAY
+        || peeked == JsonToken.END_OBJECT
+        || peeked == JsonToken.END_DOCUMENT) {
+      throw new IllegalStateException("Unexpected " + peeked + " when reading a JsonElement.");
+    }
+    final JsonElement element = (JsonElement) peekStack();
+    skipValue();
+    return element;
+  }
+
+  @Override public void close() throws IOException {
+    stack = new Object[] { SENTINEL_CLOSED };
+    stackSize = 1;
+  }
+
+  @Override public void skipValue() throws IOException {
+    if (peek() == JsonToken.NAME) {
+      nextName();
+      pathNames[stackSize - 2] = "null";
+    } else {
+      popStack();
+      if (stackSize > 0) {
+        pathNames[stackSize - 1] = "null";
+      }
+    }
+    if (stackSize > 0) {
+      pathIndices[stackSize - 1]++;
+    }
+  }
+
+  @Override public String toString() {
+    return getClass().getSimpleName() + locationString();
+  }
+
+  public void promoteNameToValue() throws IOException {
+    expect(JsonToken.NAME);
+    Iterator<?> i = (Iterator<?>) peekStack();
+    Map.Entry<?, ?> entry = (Map.Entry<?, ?>) i.next();
+    push(entry.getValue());
+    push(new JsonPrimitive((String) entry.getKey()));
+  }
+
+  private void push(Object newTop) {
+    if (stackSize == stack.length) {
+      int newLength = stackSize * 2;
+      stack = Arrays.copyOf(stack, newLength);
+      pathIndices = Arrays.copyOf(pathIndices, newLength);
+      pathNames = Arrays.copyOf(pathNames, newLength);
+    }
+    stack[stackSize++] = newTop;
+  }
+
+  private String getPath(boolean usePreviousPath) {
+    StringBuilder result = new StringBuilder().append('$');
+    for (int i = 0; i < stackSize; i++) {
+      if (stack[i] instanceof JsonArray) {
+        if (++i < stackSize && stack[i] instanceof Iterator) {
+          int pathIndex = pathIndices[i];
+          // If index is last path element it points to next array element; have to decrement
+          // `- 1` covers case where iterator for next element is on stack
+          // `- 2` covers case where peek() already pushed next element onto stack
+          if (usePreviousPath && pathIndex > 0 && (i == stackSize - 1 || i == stackSize - 2)) {
+            pathIndex--;
+          }
+          result.append('[').append(pathIndex).append(']');
+        }
+      } else if (stack[i] instanceof JsonObject) {
+        if (++i < stackSize && stack[i] instanceof Iterator) {
+          result.append('.');
+          if (pathNames[i] != null) {
+            result.append(pathNames[i]);
+          }
+        }
+      }
+    }
+    return result.toString();
+  }
+
+  @Override public String getPreviousPath() {
+    return getPath(true);
+  }
+
+  @Override public String getPath() {
+    return getPath(false);
+  }
+
+  private String locationString() {
+    return " at path " + getPath();
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/internal/bind/JsonTreeWriter.java b/gson/src/main/java/com/google/gson/internal/bind/JsonTreeWriter.java
new file mode 100644
index 0000000..e28fbfe
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/internal/bind/JsonTreeWriter.java
@@ -0,0 +1,219 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.internal.bind;
+
+import com.google.gson.JsonArray;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonNull;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonPrimitive;
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
+import java.io.Writer;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * This writer creates a JsonElement.
+ */
+public final class JsonTreeWriter extends JsonWriter {
+  private static final Writer UNWRITABLE_WRITER = new Writer() {
+    @Override public void write(char[] buffer, int offset, int counter) {
+      throw new AssertionError();
+    }
+    @Override public void flush() throws IOException {
+      throw new AssertionError();
+    }
+    @Override public void close() throws IOException {
+      throw new AssertionError();
+    }
+  };
+  /** Added to the top of the stack when this writer is closed to cause following ops to fail. */
+  private static final JsonPrimitive SENTINEL_CLOSED = new JsonPrimitive("closed");
+
+  /** The JsonElements and JsonArrays under modification, outermost to innermost. */
+  private final List<JsonElement> stack = new ArrayList<>();
+
+  /** The name for the next JSON object value. If non-null, the top of the stack is a JsonObject. */
+  private String pendingName;
+
+  /** the JSON element constructed by this writer. */
+  private JsonElement product = JsonNull.INSTANCE; // TODO: is this really what we want?;
+
+  public JsonTreeWriter() {
+    super(UNWRITABLE_WRITER);
+  }
+
+  /**
+   * Returns the top level object produced by this writer.
+   */
+  public JsonElement get() {
+    if (!stack.isEmpty()) {
+      throw new IllegalStateException("Expected one JSON element but was " + stack);
+    }
+    return product;
+  }
+
+  private JsonElement peek() {
+    return stack.get(stack.size() - 1);
+  }
+
+  private void put(JsonElement value) {
+    if (pendingName != null) {
+      if (!value.isJsonNull() || getSerializeNulls()) {
+        JsonObject object = (JsonObject) peek();
+        object.add(pendingName, value);
+      }
+      pendingName = null;
+    } else if (stack.isEmpty()) {
+      product = value;
+    } else {
+      JsonElement element = peek();
+      if (element instanceof JsonArray) {
+        ((JsonArray) element).add(value);
+      } else {
+        throw new IllegalStateException();
+      }
+    }
+  }
+
+  @Override public JsonWriter beginArray() throws IOException {
+    JsonArray array = new JsonArray();
+    put(array);
+    stack.add(array);
+    return this;
+  }
+
+  @Override public JsonWriter endArray() throws IOException {
+    if (stack.isEmpty() || pendingName != null) {
+      throw new IllegalStateException();
+    }
+    JsonElement element = peek();
+    if (element instanceof JsonArray) {
+      stack.remove(stack.size() - 1);
+      return this;
+    }
+    throw new IllegalStateException();
+  }
+
+  @Override public JsonWriter beginObject() throws IOException {
+    JsonObject object = new JsonObject();
+    put(object);
+    stack.add(object);
+    return this;
+  }
+
+  @Override public JsonWriter endObject() throws IOException {
+    if (stack.isEmpty() || pendingName != null) {
+      throw new IllegalStateException();
+    }
+    JsonElement element = peek();
+    if (element instanceof JsonObject) {
+      stack.remove(stack.size() - 1);
+      return this;
+    }
+    throw new IllegalStateException();
+  }
+
+  @Override public JsonWriter name(String name) throws IOException {
+    if (name == null) {
+      throw new NullPointerException("name == null");
+    }
+    if (stack.isEmpty() || pendingName != null) {
+      throw new IllegalStateException();
+    }
+    JsonElement element = peek();
+    if (element instanceof JsonObject) {
+      pendingName = name;
+      return this;
+    }
+    throw new IllegalStateException();
+  }
+
+  @Override public JsonWriter value(String value) throws IOException {
+    if (value == null) {
+      return nullValue();
+    }
+    put(new JsonPrimitive(value));
+    return this;
+  }
+
+  @Override public JsonWriter nullValue() throws IOException {
+    put(JsonNull.INSTANCE);
+    return this;
+  }
+
+  @Override public JsonWriter value(boolean value) throws IOException {
+    put(new JsonPrimitive(value));
+    return this;
+  }
+
+  @Override public JsonWriter value(Boolean value) throws IOException {
+    if (value == null) {
+      return nullValue();
+    }
+    put(new JsonPrimitive(value));
+    return this;
+  }
+
+  @Override public JsonWriter value(float value) throws IOException {
+    if (!isLenient() && (Float.isNaN(value) || Float.isInfinite(value))) {
+      throw new IllegalArgumentException("JSON forbids NaN and infinities: " + value);
+    }
+    put(new JsonPrimitive(value));
+    return this;
+  }
+
+  @Override public JsonWriter value(double value) throws IOException {
+    if (!isLenient() && (Double.isNaN(value) || Double.isInfinite(value))) {
+      throw new IllegalArgumentException("JSON forbids NaN and infinities: " + value);
+    }
+    put(new JsonPrimitive(value));
+    return this;
+  }
+
+  @Override public JsonWriter value(long value) throws IOException {
+    put(new JsonPrimitive(value));
+    return this;
+  }
+
+  @Override public JsonWriter value(Number value) throws IOException {
+    if (value == null) {
+      return nullValue();
+    }
+
+    if (!isLenient()) {
+      double d = value.doubleValue();
+      if (Double.isNaN(d) || Double.isInfinite(d)) {
+        throw new IllegalArgumentException("JSON forbids NaN and infinities: " + value);
+      }
+    }
+
+    put(new JsonPrimitive(value));
+    return this;
+  }
+
+  @Override public void flush() throws IOException {
+  }
+
+  @Override public void close() throws IOException {
+    if (!stack.isEmpty()) {
+      throw new IOException("Incomplete document");
+    }
+    stack.add(SENTINEL_CLOSED);
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/internal/bind/MapTypeAdapterFactory.java b/gson/src/main/java/com/google/gson/internal/bind/MapTypeAdapterFactory.java
new file mode 100644
index 0000000..f7c5a55
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/internal/bind/MapTypeAdapterFactory.java
@@ -0,0 +1,263 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.internal.bind;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonPrimitive;
+import com.google.gson.JsonSyntaxException;
+import com.google.gson.TypeAdapter;
+import com.google.gson.TypeAdapterFactory;
+import com.google.gson.internal.$Gson$Types;
+import com.google.gson.internal.ConstructorConstructor;
+import com.google.gson.internal.JsonReaderInternalAccess;
+import com.google.gson.internal.ObjectConstructor;
+import com.google.gson.internal.Streams;
+import com.google.gson.reflect.TypeToken;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonToken;
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Adapts maps to either JSON objects or JSON arrays.
+ *
+ * <h3>Maps as JSON objects</h3>
+ * For primitive keys or when complex map key serialization is not enabled, this
+ * converts Java {@link Map Maps} to JSON Objects. This requires that map keys
+ * can be serialized as strings; this is insufficient for some key types. For
+ * example, consider a map whose keys are points on a grid. The default JSON
+ * form encodes reasonably: <pre>   {@code
+ *   Map<Point, String> original = new LinkedHashMap<>();
+ *   original.put(new Point(5, 6), "a");
+ *   original.put(new Point(8, 8), "b");
+ *   System.out.println(gson.toJson(original, type));
+ * }</pre>
+ * The above code prints this JSON object:<pre>   {@code
+ *   {
+ *     "(5,6)": "a",
+ *     "(8,8)": "b"
+ *   }
+ * }</pre>
+ * But GSON is unable to deserialize this value because the JSON string name is
+ * just the {@link Object#toString() toString()} of the map key. Attempting to
+ * convert the above JSON to an object fails with a parse exception:
+ * <pre>com.google.gson.JsonParseException: Expecting object found: "(5,6)"
+ *   at com.google.gson.JsonObjectDeserializationVisitor.visitFieldUsingCustomHandler
+ *   at com.google.gson.ObjectNavigator.navigateClassFields
+ *   ...</pre>
+ *
+ * <h3>Maps as JSON arrays</h3>
+ * An alternative approach taken by this type adapter when it is required and
+ * complex map key serialization is enabled is to encode maps as arrays of map
+ * entries. Each map entry is a two element array containing a key and a value.
+ * This approach is more flexible because any type can be used as the map's key;
+ * not just strings. But it's also less portable because the receiver of such
+ * JSON must be aware of the map entry convention.
+ *
+ * <p>Register this adapter when you are creating your GSON instance.
+ * <pre>   {@code
+ *   Gson gson = new GsonBuilder()
+ *     .registerTypeAdapter(Map.class, new MapAsArrayTypeAdapter())
+ *     .create();
+ * }</pre>
+ * This will change the structure of the JSON emitted by the code above. Now we
+ * get an array. In this case the arrays elements are map entries:
+ * <pre>   {@code
+ *   [
+ *     [
+ *       {
+ *         "x": 5,
+ *         "y": 6
+ *       },
+ *       "a",
+ *     ],
+ *     [
+ *       {
+ *         "x": 8,
+ *         "y": 8
+ *       },
+ *       "b"
+ *     ]
+ *   ]
+ * }</pre>
+ * This format will serialize and deserialize just fine as long as this adapter
+ * is registered.
+ */
+public final class MapTypeAdapterFactory implements TypeAdapterFactory {
+  private final ConstructorConstructor constructorConstructor;
+  final boolean complexMapKeySerialization;
+
+  public MapTypeAdapterFactory(ConstructorConstructor constructorConstructor,
+      boolean complexMapKeySerialization) {
+    this.constructorConstructor = constructorConstructor;
+    this.complexMapKeySerialization = complexMapKeySerialization;
+  }
+
+  @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
+    Type type = typeToken.getType();
+
+    Class<? super T> rawType = typeToken.getRawType();
+    if (!Map.class.isAssignableFrom(rawType)) {
+      return null;
+    }
+
+    Type[] keyAndValueTypes = $Gson$Types.getMapKeyAndValueTypes(type, rawType);
+    TypeAdapter<?> keyAdapter = getKeyAdapter(gson, keyAndValueTypes[0]);
+    TypeAdapter<?> valueAdapter = gson.getAdapter(TypeToken.get(keyAndValueTypes[1]));
+    ObjectConstructor<T> constructor = constructorConstructor.get(typeToken);
+
+    @SuppressWarnings({"unchecked", "rawtypes"})
+    // we don't define a type parameter for the key or value types
+    TypeAdapter<T> result = new Adapter(gson, keyAndValueTypes[0], keyAdapter,
+        keyAndValueTypes[1], valueAdapter, constructor);
+    return result;
+  }
+
+  /**
+   * Returns a type adapter that writes the value as a string.
+   */
+  private TypeAdapter<?> getKeyAdapter(Gson context, Type keyType) {
+    return (keyType == boolean.class || keyType == Boolean.class)
+        ? TypeAdapters.BOOLEAN_AS_STRING
+        : context.getAdapter(TypeToken.get(keyType));
+  }
+
+  private final class Adapter<K, V> extends TypeAdapter<Map<K, V>> {
+    private final TypeAdapter<K> keyTypeAdapter;
+    private final TypeAdapter<V> valueTypeAdapter;
+    private final ObjectConstructor<? extends Map<K, V>> constructor;
+
+    public Adapter(Gson context, Type keyType, TypeAdapter<K> keyTypeAdapter,
+        Type valueType, TypeAdapter<V> valueTypeAdapter,
+        ObjectConstructor<? extends Map<K, V>> constructor) {
+      this.keyTypeAdapter =
+        new TypeAdapterRuntimeTypeWrapper<>(context, keyTypeAdapter, keyType);
+      this.valueTypeAdapter =
+        new TypeAdapterRuntimeTypeWrapper<>(context, valueTypeAdapter, valueType);
+      this.constructor = constructor;
+    }
+
+    @Override public Map<K, V> read(JsonReader in) throws IOException {
+      JsonToken peek = in.peek();
+      if (peek == JsonToken.NULL) {
+        in.nextNull();
+        return null;
+      }
+
+      Map<K, V> map = constructor.construct();
+
+      if (peek == JsonToken.BEGIN_ARRAY) {
+        in.beginArray();
+        while (in.hasNext()) {
+          in.beginArray(); // entry array
+          K key = keyTypeAdapter.read(in);
+          V value = valueTypeAdapter.read(in);
+          V replaced = map.put(key, value);
+          if (replaced != null) {
+            throw new JsonSyntaxException("duplicate key: " + key);
+          }
+          in.endArray();
+        }
+        in.endArray();
+      } else {
+        in.beginObject();
+        while (in.hasNext()) {
+          JsonReaderInternalAccess.INSTANCE.promoteNameToValue(in);
+          K key = keyTypeAdapter.read(in);
+          V value = valueTypeAdapter.read(in);
+          V replaced = map.put(key, value);
+          if (replaced != null) {
+            throw new JsonSyntaxException("duplicate key: " + key);
+          }
+        }
+        in.endObject();
+      }
+      return map;
+    }
+
+    @Override public void write(JsonWriter out, Map<K, V> map) throws IOException {
+      if (map == null) {
+        out.nullValue();
+        return;
+      }
+
+      if (!complexMapKeySerialization) {
+        out.beginObject();
+        for (Map.Entry<K, V> entry : map.entrySet()) {
+          out.name(String.valueOf(entry.getKey()));
+          valueTypeAdapter.write(out, entry.getValue());
+        }
+        out.endObject();
+        return;
+      }
+
+      boolean hasComplexKeys = false;
+      List<JsonElement> keys = new ArrayList<>(map.size());
+
+      List<V> values = new ArrayList<>(map.size());
+      for (Map.Entry<K, V> entry : map.entrySet()) {
+        JsonElement keyElement = keyTypeAdapter.toJsonTree(entry.getKey());
+        keys.add(keyElement);
+        values.add(entry.getValue());
+        hasComplexKeys |= keyElement.isJsonArray() || keyElement.isJsonObject();
+      }
+
+      if (hasComplexKeys) {
+        out.beginArray();
+        for (int i = 0, size = keys.size(); i < size; i++) {
+          out.beginArray(); // entry array
+          Streams.write(keys.get(i), out);
+          valueTypeAdapter.write(out, values.get(i));
+          out.endArray();
+        }
+        out.endArray();
+      } else {
+        out.beginObject();
+        for (int i = 0, size = keys.size(); i < size; i++) {
+          JsonElement keyElement = keys.get(i);
+          out.name(keyToString(keyElement));
+          valueTypeAdapter.write(out, values.get(i));
+        }
+        out.endObject();
+      }
+    }
+
+    private String keyToString(JsonElement keyElement) {
+      if (keyElement.isJsonPrimitive()) {
+        JsonPrimitive primitive = keyElement.getAsJsonPrimitive();
+        if (primitive.isNumber()) {
+          return String.valueOf(primitive.getAsNumber());
+        } else if (primitive.isBoolean()) {
+          return Boolean.toString(primitive.getAsBoolean());
+        } else if (primitive.isString()) {
+          return primitive.getAsString();
+        } else {
+          throw new AssertionError();
+        }
+      } else if (keyElement.isJsonNull()) {
+        return "null";
+      } else {
+        throw new AssertionError();
+      }
+    }
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/internal/bind/NumberTypeAdapter.java b/gson/src/main/java/com/google/gson/internal/bind/NumberTypeAdapter.java
new file mode 100644
index 0000000..5aaeae3
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/internal/bind/NumberTypeAdapter.java
@@ -0,0 +1,82 @@
+/*
+ * Copyright (C) 2020 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.internal.bind;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonSyntaxException;
+import com.google.gson.ToNumberStrategy;
+import com.google.gson.ToNumberPolicy;
+import com.google.gson.TypeAdapter;
+import com.google.gson.TypeAdapterFactory;
+import com.google.gson.reflect.TypeToken;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonToken;
+import com.google.gson.stream.JsonWriter;
+
+import java.io.IOException;
+
+/**
+ * Type adapter for {@link Number}.
+ */
+public final class NumberTypeAdapter extends TypeAdapter<Number> {
+  /**
+   * Gson default factory using {@link ToNumberPolicy#LAZILY_PARSED_NUMBER}.
+   */
+  private static final TypeAdapterFactory LAZILY_PARSED_NUMBER_FACTORY = newFactory(ToNumberPolicy.LAZILY_PARSED_NUMBER);
+
+  private final ToNumberStrategy toNumberStrategy;
+
+  private NumberTypeAdapter(ToNumberStrategy toNumberStrategy) {
+    this.toNumberStrategy = toNumberStrategy;
+  }
+
+  private static TypeAdapterFactory newFactory(ToNumberStrategy toNumberStrategy) {
+    final NumberTypeAdapter adapter = new NumberTypeAdapter(toNumberStrategy);
+    return new TypeAdapterFactory() {
+      @SuppressWarnings("unchecked")
+      @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
+        return type.getRawType() == Number.class ? (TypeAdapter<T>) adapter : null;
+      }
+    };
+  }
+
+  public static TypeAdapterFactory getFactory(ToNumberStrategy toNumberStrategy) {
+    if (toNumberStrategy == ToNumberPolicy.LAZILY_PARSED_NUMBER) {
+      return LAZILY_PARSED_NUMBER_FACTORY;
+    } else {
+      return newFactory(toNumberStrategy);
+    }
+  }
+
+  @Override public Number read(JsonReader in) throws IOException {
+    JsonToken jsonToken = in.peek();
+    switch (jsonToken) {
+    case NULL:
+      in.nextNull();
+      return null;
+    case NUMBER:
+    case STRING:
+      return toNumberStrategy.readNumber(in);
+    default:
+      throw new JsonSyntaxException("Expecting number, got: " + jsonToken + "; at path " + in.getPath());
+    }
+  }
+
+  @Override public void write(JsonWriter out, Number value) throws IOException {
+    out.value(value);
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/internal/bind/ObjectTypeAdapter.java b/gson/src/main/java/com/google/gson/internal/bind/ObjectTypeAdapter.java
new file mode 100644
index 0000000..c5f2ec7
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/internal/bind/ObjectTypeAdapter.java
@@ -0,0 +1,185 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.internal.bind;
+
+import com.google.gson.Gson;
+import com.google.gson.ToNumberPolicy;
+import com.google.gson.ToNumberStrategy;
+import com.google.gson.TypeAdapter;
+import com.google.gson.TypeAdapterFactory;
+import com.google.gson.internal.LinkedTreeMap;
+import com.google.gson.reflect.TypeToken;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonToken;
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Adapts types whose static type is only 'Object'. Uses getClass() on
+ * serialization and a primitive/Map/List on deserialization.
+ */
+public final class ObjectTypeAdapter extends TypeAdapter<Object> {
+  /**
+   * Gson default factory using {@link ToNumberPolicy#DOUBLE}.
+   */
+  private static final TypeAdapterFactory DOUBLE_FACTORY = newFactory(ToNumberPolicy.DOUBLE);
+
+  private final Gson gson;
+  private final ToNumberStrategy toNumberStrategy;
+
+  private ObjectTypeAdapter(Gson gson, ToNumberStrategy toNumberStrategy) {
+    this.gson = gson;
+    this.toNumberStrategy = toNumberStrategy;
+  }
+
+  private static TypeAdapterFactory newFactory(final ToNumberStrategy toNumberStrategy) {
+    return new TypeAdapterFactory() {
+      @SuppressWarnings("unchecked")
+      @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
+        if (type.getRawType() == Object.class) {
+          return (TypeAdapter<T>) new ObjectTypeAdapter(gson, toNumberStrategy);
+        }
+        return null;
+      }
+    };
+  }
+
+  public static TypeAdapterFactory getFactory(ToNumberStrategy toNumberStrategy) {
+    if (toNumberStrategy == ToNumberPolicy.DOUBLE) {
+      return DOUBLE_FACTORY;
+    } else {
+      return newFactory(toNumberStrategy);
+    }
+  }
+
+  /**
+   * Tries to begin reading a JSON array or JSON object, returning {@code null} if
+   * the next element is neither of those.
+   */
+  private Object tryBeginNesting(JsonReader in, JsonToken peeked) throws IOException {
+    switch (peeked) {
+      case BEGIN_ARRAY:
+        in.beginArray();
+        return new ArrayList<>();
+      case BEGIN_OBJECT:
+        in.beginObject();
+        return new LinkedTreeMap<>();
+      default:
+        return null;
+    }
+  }
+
+  /** Reads an {@code Object} which cannot have any nested elements */
+  private Object readTerminal(JsonReader in, JsonToken peeked) throws IOException {
+    switch (peeked) {
+      case STRING:
+        return in.nextString();
+      case NUMBER:
+        return toNumberStrategy.readNumber(in);
+      case BOOLEAN:
+        return in.nextBoolean();
+      case NULL:
+        in.nextNull();
+        return null;
+      default:
+        // When read(JsonReader) is called with JsonReader in invalid state
+        throw new IllegalStateException("Unexpected token: " + peeked);
+    }
+  }
+
+  @Override public Object read(JsonReader in) throws IOException {
+    // Either List or Map
+    Object current;
+    JsonToken peeked = in.peek();
+
+    current = tryBeginNesting(in, peeked);
+    if (current == null) {
+      return readTerminal(in, peeked);
+    }
+
+    Deque<Object> stack = new ArrayDeque<>();
+
+    while (true) {
+      while (in.hasNext()) {
+        String name = null;
+        // Name is only used for JSON object members
+        if (current instanceof Map) {
+          name = in.nextName();
+        }
+
+        peeked = in.peek();
+        Object value = tryBeginNesting(in, peeked);
+        boolean isNesting = value != null;
+
+        if (value == null) {
+          value = readTerminal(in, peeked);
+        }
+
+        if (current instanceof List) {
+          @SuppressWarnings("unchecked")
+          List<Object> list = (List<Object>) current;
+          list.add(value);
+        } else {
+          @SuppressWarnings("unchecked")
+          Map<String, Object> map = (Map<String, Object>) current;
+          map.put(name, value);
+        }
+
+        if (isNesting) {
+          stack.addLast(current);
+          current = value;
+        }
+      }
+
+      // End current element
+      if (current instanceof List) {
+        in.endArray();
+      } else {
+        in.endObject();
+      }
+
+      if (stack.isEmpty()) {
+        return current;
+      } else {
+        // Continue with enclosing element
+        current = stack.removeLast();
+      }
+    }
+  }
+
+  @SuppressWarnings("unchecked")
+  @Override public void write(JsonWriter out, Object value) throws IOException {
+    if (value == null) {
+      out.nullValue();
+      return;
+    }
+
+    TypeAdapter<Object> typeAdapter = (TypeAdapter<Object>) gson.getAdapter(value.getClass());
+    if (typeAdapter instanceof ObjectTypeAdapter) {
+      out.beginObject();
+      out.endObject();
+      return;
+    }
+
+    typeAdapter.write(out, value);
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/internal/bind/ReflectiveTypeAdapterFactory.java b/gson/src/main/java/com/google/gson/internal/bind/ReflectiveTypeAdapterFactory.java
new file mode 100644
index 0000000..95d01ac
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/internal/bind/ReflectiveTypeAdapterFactory.java
@@ -0,0 +1,295 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.internal.bind;
+
+import com.google.gson.FieldNamingStrategy;
+import com.google.gson.Gson;
+import com.google.gson.JsonIOException;
+import com.google.gson.JsonSyntaxException;
+import com.google.gson.ReflectionAccessFilter;
+import com.google.gson.ReflectionAccessFilter.FilterResult;
+import com.google.gson.TypeAdapter;
+import com.google.gson.TypeAdapterFactory;
+import com.google.gson.annotations.JsonAdapter;
+import com.google.gson.annotations.SerializedName;
+import com.google.gson.internal.$Gson$Types;
+import com.google.gson.internal.ConstructorConstructor;
+import com.google.gson.internal.Excluder;
+import com.google.gson.internal.ObjectConstructor;
+import com.google.gson.internal.Primitives;
+import com.google.gson.internal.ReflectionAccessFilterHelper;
+import com.google.gson.internal.reflect.ReflectionHelper;
+import com.google.gson.reflect.TypeToken;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonToken;
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Type adapter that reflects over the fields and methods of a class.
+ */
+public final class ReflectiveTypeAdapterFactory implements TypeAdapterFactory {
+  private final ConstructorConstructor constructorConstructor;
+  private final FieldNamingStrategy fieldNamingPolicy;
+  private final Excluder excluder;
+  private final JsonAdapterAnnotationTypeAdapterFactory jsonAdapterFactory;
+  private final List<ReflectionAccessFilter> reflectionFilters;
+
+  public ReflectiveTypeAdapterFactory(ConstructorConstructor constructorConstructor,
+      FieldNamingStrategy fieldNamingPolicy, Excluder excluder,
+      JsonAdapterAnnotationTypeAdapterFactory jsonAdapterFactory,
+      List<ReflectionAccessFilter> reflectionFilters) {
+    this.constructorConstructor = constructorConstructor;
+    this.fieldNamingPolicy = fieldNamingPolicy;
+    this.excluder = excluder;
+    this.jsonAdapterFactory = jsonAdapterFactory;
+    this.reflectionFilters = reflectionFilters;
+  }
+
+  private boolean includeField(Field f, boolean serialize) {
+    return !excluder.excludeClass(f.getType(), serialize) && !excluder.excludeField(f, serialize);
+  }
+
+  /** first element holds the default name */
+  private List<String> getFieldNames(Field f) {
+    SerializedName annotation = f.getAnnotation(SerializedName.class);
+    if (annotation == null) {
+      String name = fieldNamingPolicy.translateName(f);
+      return Collections.singletonList(name);
+    }
+
+    String serializedName = annotation.value();
+    String[] alternates = annotation.alternate();
+    if (alternates.length == 0) {
+      return Collections.singletonList(serializedName);
+    }
+
+    List<String> fieldNames = new ArrayList<>(alternates.length + 1);
+    fieldNames.add(serializedName);
+    for (String alternate : alternates) {
+      fieldNames.add(alternate);
+    }
+    return fieldNames;
+  }
+
+  @Override public <T> TypeAdapter<T> create(Gson gson, final TypeToken<T> type) {
+    Class<? super T> raw = type.getRawType();
+
+    if (!Object.class.isAssignableFrom(raw)) {
+      return null; // it's a primitive!
+    }
+
+    FilterResult filterResult = ReflectionAccessFilterHelper.getFilterResult(reflectionFilters, raw);
+    if (filterResult == FilterResult.BLOCK_ALL) {
+      throw new JsonIOException("ReflectionAccessFilter does not permit using reflection for "
+          + raw + ". Register a TypeAdapter for this type or adjust the access filter.");
+    }
+    boolean blockInaccessible = filterResult == FilterResult.BLOCK_INACCESSIBLE;
+
+    ObjectConstructor<T> constructor = constructorConstructor.get(type);
+    return new Adapter<>(constructor, getBoundFields(gson, type, raw, blockInaccessible));
+  }
+
+  private static void checkAccessible(Object object, Field field) {
+    if (!ReflectionAccessFilterHelper.canAccess(field, Modifier.isStatic(field.getModifiers()) ? null : object)) {
+      throw new JsonIOException("Field '" + field.getDeclaringClass().getName() + "#"
+          + field.getName() + "' is not accessible and ReflectionAccessFilter does not "
+          + "permit making it accessible. Register a TypeAdapter for the declaring type "
+          + "or adjust the access filter.");
+    }
+  }
+
+  private ReflectiveTypeAdapterFactory.BoundField createBoundField(
+      final Gson context, final Field field, final String name,
+      final TypeToken<?> fieldType, boolean serialize, boolean deserialize,
+      final boolean blockInaccessible) {
+    final boolean isPrimitive = Primitives.isPrimitive(fieldType.getRawType());
+    // special casing primitives here saves ~5% on Android...
+    JsonAdapter annotation = field.getAnnotation(JsonAdapter.class);
+    TypeAdapter<?> mapped = null;
+    if (annotation != null) {
+      mapped = jsonAdapterFactory.getTypeAdapter(
+          constructorConstructor, context, fieldType, annotation);
+    }
+    final boolean jsonAdapterPresent = mapped != null;
+    if (mapped == null) mapped = context.getAdapter(fieldType);
+
+    final TypeAdapter<?> typeAdapter = mapped;
+    return new ReflectiveTypeAdapterFactory.BoundField(name, serialize, deserialize) {
+      @SuppressWarnings({"unchecked", "rawtypes"}) // the type adapter and field type always agree
+      @Override void write(JsonWriter writer, Object value)
+          throws IOException, IllegalAccessException {
+        if (!serialized) return;
+        if (blockInaccessible) {
+          checkAccessible(value, field);
+        }
+
+        Object fieldValue = field.get(value);
+        if (fieldValue == value) {
+          // avoid direct recursion
+          return;
+        }
+        writer.name(name);
+        TypeAdapter t = jsonAdapterPresent ? typeAdapter
+            : new TypeAdapterRuntimeTypeWrapper(context, typeAdapter, fieldType.getType());
+        t.write(writer, fieldValue);
+      }
+      @Override void read(JsonReader reader, Object value)
+          throws IOException, IllegalAccessException {
+        Object fieldValue = typeAdapter.read(reader);
+        if (fieldValue != null || !isPrimitive) {
+          if (blockInaccessible) {
+            checkAccessible(value, field);
+          }
+          field.set(value, fieldValue);
+        }
+      }
+    };
+  }
+
+  private Map<String, BoundField> getBoundFields(Gson context, TypeToken<?> type, Class<?> raw, boolean blockInaccessible) {
+    Map<String, BoundField> result = new LinkedHashMap<>();
+    if (raw.isInterface()) {
+      return result;
+    }
+
+    Type declaredType = type.getType();
+    Class<?> originalRaw = raw;
+    while (raw != Object.class) {
+      Field[] fields = raw.getDeclaredFields();
+
+      // For inherited fields, check if access to their declaring class is allowed
+      if (raw != originalRaw && fields.length > 0) {
+        FilterResult filterResult = ReflectionAccessFilterHelper.getFilterResult(reflectionFilters, raw);
+        if (filterResult == FilterResult.BLOCK_ALL) {
+          throw new JsonIOException("ReflectionAccessFilter does not permit using reflection for "
+              + raw + " (supertype of " + originalRaw + "). Register a TypeAdapter for this type "
+              + "or adjust the access filter.");
+        }
+        blockInaccessible = filterResult == FilterResult.BLOCK_INACCESSIBLE;
+      }
+
+      for (Field field : fields) {
+        boolean serialize = includeField(field, true);
+        boolean deserialize = includeField(field, false);
+        if (!serialize && !deserialize) {
+          continue;
+        }
+
+        // If blockInaccessible, skip and perform access check later
+        if (!blockInaccessible) {
+          ReflectionHelper.makeAccessible(field);
+        }
+        Type fieldType = $Gson$Types.resolve(type.getType(), raw, field.getGenericType());
+        List<String> fieldNames = getFieldNames(field);
+        BoundField previous = null;
+        for (int i = 0, size = fieldNames.size(); i < size; ++i) {
+          String name = fieldNames.get(i);
+          if (i != 0) serialize = false; // only serialize the default name
+          BoundField boundField = createBoundField(context, field, name,
+              TypeToken.get(fieldType), serialize, deserialize, blockInaccessible);
+          BoundField replaced = result.put(name, boundField);
+          if (previous == null) previous = replaced;
+        }
+        if (previous != null) {
+          throw new IllegalArgumentException(declaredType
+              + " declares multiple JSON fields named " + previous.name);
+        }
+      }
+      type = TypeToken.get($Gson$Types.resolve(type.getType(), raw, raw.getGenericSuperclass()));
+      raw = type.getRawType();
+    }
+    return result;
+  }
+
+  static abstract class BoundField {
+    final String name;
+    final boolean serialized;
+    final boolean deserialized;
+
+    protected BoundField(String name, boolean serialized, boolean deserialized) {
+      this.name = name;
+      this.serialized = serialized;
+      this.deserialized = deserialized;
+    }
+    abstract void write(JsonWriter writer, Object value) throws IOException, IllegalAccessException;
+    abstract void read(JsonReader reader, Object value) throws IOException, IllegalAccessException;
+  }
+
+  public static final class Adapter<T> extends TypeAdapter<T> {
+    private final ObjectConstructor<T> constructor;
+    private final Map<String, BoundField> boundFields;
+
+    Adapter(ObjectConstructor<T> constructor, Map<String, BoundField> boundFields) {
+      this.constructor = constructor;
+      this.boundFields = boundFields;
+    }
+
+    @Override public T read(JsonReader in) throws IOException {
+      if (in.peek() == JsonToken.NULL) {
+        in.nextNull();
+        return null;
+      }
+
+      T instance = constructor.construct();
+
+      try {
+        in.beginObject();
+        while (in.hasNext()) {
+          String name = in.nextName();
+          BoundField field = boundFields.get(name);
+          if (field == null || !field.deserialized) {
+            in.skipValue();
+          } else {
+            field.read(in, instance);
+          }
+        }
+      } catch (IllegalStateException e) {
+        throw new JsonSyntaxException(e);
+      } catch (IllegalAccessException e) {
+        throw ReflectionHelper.createExceptionForUnexpectedIllegalAccess(e);
+      }
+      in.endObject();
+      return instance;
+    }
+
+    @Override public void write(JsonWriter out, T value) throws IOException {
+      if (value == null) {
+        out.nullValue();
+        return;
+      }
+
+      out.beginObject();
+      try {
+        for (BoundField boundField : boundFields.values()) {
+          boundField.write(out, value);
+        }
+      } catch (IllegalAccessException e) {
+        throw ReflectionHelper.createExceptionForUnexpectedIllegalAccess(e);
+      }
+      out.endObject();
+    }
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/internal/bind/TreeTypeAdapter.java b/gson/src/main/java/com/google/gson/internal/bind/TreeTypeAdapter.java
new file mode 100644
index 0000000..50f46b5
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/internal/bind/TreeTypeAdapter.java
@@ -0,0 +1,166 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.internal.bind;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonDeserializationContext;
+import com.google.gson.JsonDeserializer;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonParseException;
+import com.google.gson.JsonSerializationContext;
+import com.google.gson.JsonSerializer;
+import com.google.gson.TypeAdapter;
+import com.google.gson.TypeAdapterFactory;
+import com.google.gson.internal.$Gson$Preconditions;
+import com.google.gson.internal.Streams;
+import com.google.gson.reflect.TypeToken;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
+import java.lang.reflect.Type;
+
+/**
+ * Adapts a Gson 1.x tree-style adapter as a streaming TypeAdapter. Since the
+ * tree adapter may be serialization-only or deserialization-only, this class
+ * has a facility to lookup a delegate type adapter on demand.
+ */
+public final class TreeTypeAdapter<T> extends TypeAdapter<T> {
+  private final JsonSerializer<T> serializer;
+  private final JsonDeserializer<T> deserializer;
+  final Gson gson;
+  private final TypeToken<T> typeToken;
+  private final TypeAdapterFactory skipPast;
+  private final GsonContextImpl context = new GsonContextImpl();
+
+  /** The delegate is lazily created because it may not be needed, and creating it may fail. */
+  private volatile TypeAdapter<T> delegate;
+
+  public TreeTypeAdapter(JsonSerializer<T> serializer, JsonDeserializer<T> deserializer,
+      Gson gson, TypeToken<T> typeToken, TypeAdapterFactory skipPast) {
+    this.serializer = serializer;
+    this.deserializer = deserializer;
+    this.gson = gson;
+    this.typeToken = typeToken;
+    this.skipPast = skipPast;
+  }
+
+  @Override public T read(JsonReader in) throws IOException {
+    if (deserializer == null) {
+      return delegate().read(in);
+    }
+    JsonElement value = Streams.parse(in);
+    if (value.isJsonNull()) {
+      return null;
+    }
+    return deserializer.deserialize(value, typeToken.getType(), context);
+  }
+
+  @Override public void write(JsonWriter out, T value) throws IOException {
+    if (serializer == null) {
+      delegate().write(out, value);
+      return;
+    }
+    if (value == null) {
+      out.nullValue();
+      return;
+    }
+    JsonElement tree = serializer.serialize(value, typeToken.getType(), context);
+    Streams.write(tree, out);
+  }
+
+  private TypeAdapter<T> delegate() {
+    // A race might lead to `delegate` being assigned by multiple threads but the last assignment will stick
+    TypeAdapter<T> d = delegate;
+    return d != null
+        ? d
+        : (delegate = gson.getDelegateAdapter(skipPast, typeToken));
+  }
+
+  /**
+   * Returns a new factory that will match each type against {@code exactType}.
+   */
+  public static TypeAdapterFactory newFactory(TypeToken<?> exactType, Object typeAdapter) {
+    return new SingleTypeFactory(typeAdapter, exactType, false, null);
+  }
+
+  /**
+   * Returns a new factory that will match each type and its raw type against
+   * {@code exactType}.
+   */
+  public static TypeAdapterFactory newFactoryWithMatchRawType(
+      TypeToken<?> exactType, Object typeAdapter) {
+    // only bother matching raw types if exact type is a raw type
+    boolean matchRawType = exactType.getType() == exactType.getRawType();
+    return new SingleTypeFactory(typeAdapter, exactType, matchRawType, null);
+  }
+
+  /**
+   * Returns a new factory that will match each type's raw type for assignability
+   * to {@code hierarchyType}.
+   */
+  public static TypeAdapterFactory newTypeHierarchyFactory(
+      Class<?> hierarchyType, Object typeAdapter) {
+    return new SingleTypeFactory(typeAdapter, null, false, hierarchyType);
+  }
+
+  private static final class SingleTypeFactory implements TypeAdapterFactory {
+    private final TypeToken<?> exactType;
+    private final boolean matchRawType;
+    private final Class<?> hierarchyType;
+    private final JsonSerializer<?> serializer;
+    private final JsonDeserializer<?> deserializer;
+
+    SingleTypeFactory(Object typeAdapter, TypeToken<?> exactType, boolean matchRawType,
+        Class<?> hierarchyType) {
+      serializer = typeAdapter instanceof JsonSerializer
+          ? (JsonSerializer<?>) typeAdapter
+          : null;
+      deserializer = typeAdapter instanceof JsonDeserializer
+          ? (JsonDeserializer<?>) typeAdapter
+          : null;
+      $Gson$Preconditions.checkArgument(serializer != null || deserializer != null);
+      this.exactType = exactType;
+      this.matchRawType = matchRawType;
+      this.hierarchyType = hierarchyType;
+    }
+
+    @SuppressWarnings("unchecked") // guarded by typeToken.equals() call
+    @Override
+    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
+      boolean matches = exactType != null
+          ? exactType.equals(type) || matchRawType && exactType.getType() == type.getRawType()
+          : hierarchyType.isAssignableFrom(type.getRawType());
+      return matches
+          ? new TreeTypeAdapter<>((JsonSerializer<T>) serializer,
+              (JsonDeserializer<T>) deserializer, gson, type, this)
+          : null;
+    }
+  }
+
+  private final class GsonContextImpl implements JsonSerializationContext, JsonDeserializationContext {
+    @Override public JsonElement serialize(Object src) {
+      return gson.toJsonTree(src);
+    }
+    @Override public JsonElement serialize(Object src, Type typeOfSrc) {
+      return gson.toJsonTree(src, typeOfSrc);
+    }
+    @SuppressWarnings("unchecked")
+    @Override public <R> R deserialize(JsonElement json, Type typeOfT) throws JsonParseException {
+      return (R) gson.fromJson(json, typeOfT);
+    }
+  };
+}
diff --git a/gson/src/main/java/com/google/gson/internal/bind/TypeAdapterRuntimeTypeWrapper.java b/gson/src/main/java/com/google/gson/internal/bind/TypeAdapterRuntimeTypeWrapper.java
new file mode 100644
index 0000000..2bf37ad
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/internal/bind/TypeAdapterRuntimeTypeWrapper.java
@@ -0,0 +1,82 @@
+/*

+ * Copyright (C) 2011 Google Inc.

+ *

+ * Licensed under the Apache License, Version 2.0 (the "License");

+ * you may not use this file except in compliance with the License.

+ * You may obtain a copy of the License at

+ *

+ *      http://www.apache.org/licenses/LICENSE-2.0

+ *

+ * Unless required by applicable law or agreed to in writing, software

+ * distributed under the License is distributed on an "AS IS" BASIS,

+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

+ * See the License for the specific language governing permissions and

+ * limitations under the License.

+ */

+package com.google.gson.internal.bind;

+

+import java.io.IOException;

+import java.lang.reflect.Type;

+import java.lang.reflect.TypeVariable;

+

+import com.google.gson.Gson;

+import com.google.gson.TypeAdapter;

+import com.google.gson.reflect.TypeToken;

+import com.google.gson.stream.JsonReader;

+import com.google.gson.stream.JsonWriter;

+

+final class TypeAdapterRuntimeTypeWrapper<T> extends TypeAdapter<T> {

+  private final Gson context;

+  private final TypeAdapter<T> delegate;

+  private final Type type;

+

+  TypeAdapterRuntimeTypeWrapper(Gson context, TypeAdapter<T> delegate, Type type) {

+    this.context = context;

+    this.delegate = delegate;

+    this.type = type;

+  }

+

+  @Override

+  public T read(JsonReader in) throws IOException {

+    return delegate.read(in);

+  }

+

+  @SuppressWarnings({"rawtypes", "unchecked"})

+  @Override

+  public void write(JsonWriter out, T value) throws IOException {

+    // Order of preference for choosing type adapters

+    // First preference: a type adapter registered for the runtime type

+    // Second preference: a type adapter registered for the declared type

+    // Third preference: reflective type adapter for the runtime type (if it is a sub class of the declared type)

+    // Fourth preference: reflective type adapter for the declared type

+

+    TypeAdapter chosen = delegate;

+    Type runtimeType = getRuntimeTypeIfMoreSpecific(type, value);

+    if (runtimeType != type) {

+      TypeAdapter runtimeTypeAdapter = context.getAdapter(TypeToken.get(runtimeType));

+      if (!(runtimeTypeAdapter instanceof ReflectiveTypeAdapterFactory.Adapter)) {

+        // The user registered a type adapter for the runtime type, so we will use that

+        chosen = runtimeTypeAdapter;

+      } else if (!(delegate instanceof ReflectiveTypeAdapterFactory.Adapter)) {

+        // The user registered a type adapter for Base class, so we prefer it over the

+        // reflective type adapter for the runtime type

+        chosen = delegate;

+      } else {

+        // Use the type adapter for runtime type

+        chosen = runtimeTypeAdapter;

+      }

+    }

+    chosen.write(out, value);

+  }

+

+  /**

+   * Finds a compatible runtime type if it is more specific

+   */

+  private Type getRuntimeTypeIfMoreSpecific(Type type, Object value) {

+    if (value != null

+        && (type == Object.class || type instanceof TypeVariable<?> || type instanceof Class<?>)) {

+      type = value.getClass();

+    }

+    return type;

+  }

+}

diff --git a/gson/src/main/java/com/google/gson/internal/bind/TypeAdapters.java b/gson/src/main/java/com/google/gson/internal/bind/TypeAdapters.java
new file mode 100644
index 0000000..9ba1363
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/internal/bind/TypeAdapters.java
@@ -0,0 +1,993 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.internal.bind;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonIOException;
+import com.google.gson.JsonNull;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonPrimitive;
+import com.google.gson.JsonSyntaxException;
+import com.google.gson.TypeAdapter;
+import com.google.gson.TypeAdapterFactory;
+import com.google.gson.annotations.SerializedName;
+import com.google.gson.internal.LazilyParsedNumber;
+import com.google.gson.reflect.TypeToken;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonToken;
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
+import java.lang.reflect.AccessibleObject;
+import java.lang.reflect.Field;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.net.InetAddress;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.BitSet;
+import java.util.Calendar;
+import java.util.Currency;
+import java.util.Deque;
+import java.util.GregorianCalendar;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.StringTokenizer;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicIntegerArray;
+
+/**
+ * Type adapters for basic types.
+ */
+public final class TypeAdapters {
+  private TypeAdapters() {
+    throw new UnsupportedOperationException();
+  }
+
+  @SuppressWarnings("rawtypes")
+  public static final TypeAdapter<Class> CLASS = new TypeAdapter<Class>() {
+    @Override
+    public void write(JsonWriter out, Class value) throws IOException {
+      throw new UnsupportedOperationException("Attempted to serialize java.lang.Class: "
+              + value.getName() + ". Forgot to register a type adapter?");
+    }
+    @Override
+    public Class read(JsonReader in) throws IOException {
+      throw new UnsupportedOperationException(
+              "Attempted to deserialize a java.lang.Class. Forgot to register a type adapter?");
+    }
+  }.nullSafe();
+
+  public static final TypeAdapterFactory CLASS_FACTORY = newFactory(Class.class, CLASS);
+
+  public static final TypeAdapter<BitSet> BIT_SET = new TypeAdapter<BitSet>() {
+    @Override public BitSet read(JsonReader in) throws IOException {
+      BitSet bitset = new BitSet();
+      in.beginArray();
+      int i = 0;
+      JsonToken tokenType = in.peek();
+      while (tokenType != JsonToken.END_ARRAY) {
+        boolean set;
+        switch (tokenType) {
+        case NUMBER:
+        case STRING:
+          int intValue = in.nextInt();
+          if (intValue == 0) {
+            set = false;
+          } else if (intValue == 1) {
+            set = true;
+          } else {
+            throw new JsonSyntaxException("Invalid bitset value " + intValue + ", expected 0 or 1; at path " + in.getPreviousPath());
+          }
+          break;
+        case BOOLEAN:
+          set = in.nextBoolean();
+          break;
+        default:
+          throw new JsonSyntaxException("Invalid bitset value type: " + tokenType + "; at path " + in.getPath());
+        }
+        if (set) {
+          bitset.set(i);
+        }
+        ++i;
+        tokenType = in.peek();
+      }
+      in.endArray();
+      return bitset;
+    }
+
+    @Override public void write(JsonWriter out, BitSet src) throws IOException {
+      out.beginArray();
+      for (int i = 0, length = src.length(); i < length; i++) {
+        int value = (src.get(i)) ? 1 : 0;
+        out.value(value);
+      }
+      out.endArray();
+    }
+  }.nullSafe();
+
+  public static final TypeAdapterFactory BIT_SET_FACTORY = newFactory(BitSet.class, BIT_SET);
+
+  public static final TypeAdapter<Boolean> BOOLEAN = new TypeAdapter<Boolean>() {
+    @Override
+    public Boolean read(JsonReader in) throws IOException {
+      JsonToken peek = in.peek();
+      if (peek == JsonToken.NULL) {
+        in.nextNull();
+        return null;
+      } else if (peek == JsonToken.STRING) {
+        // support strings for compatibility with GSON 1.7
+        return Boolean.parseBoolean(in.nextString());
+      }
+      return in.nextBoolean();
+    }
+    @Override
+    public void write(JsonWriter out, Boolean value) throws IOException {
+      out.value(value);
+    }
+  };
+
+  /**
+   * Writes a boolean as a string. Useful for map keys, where booleans aren't
+   * otherwise permitted.
+   */
+  public static final TypeAdapter<Boolean> BOOLEAN_AS_STRING = new TypeAdapter<Boolean>() {
+    @Override public Boolean read(JsonReader in) throws IOException {
+      if (in.peek() == JsonToken.NULL) {
+        in.nextNull();
+        return null;
+      }
+      return Boolean.valueOf(in.nextString());
+    }
+
+    @Override public void write(JsonWriter out, Boolean value) throws IOException {
+      out.value(value == null ? "null" : value.toString());
+    }
+  };
+
+  public static final TypeAdapterFactory BOOLEAN_FACTORY
+      = newFactory(boolean.class, Boolean.class, BOOLEAN);
+
+  public static final TypeAdapter<Number> BYTE = new TypeAdapter<Number>() {
+    @Override
+    public Number read(JsonReader in) throws IOException {
+      if (in.peek() == JsonToken.NULL) {
+        in.nextNull();
+        return null;
+      }
+
+      int intValue;
+      try {
+        intValue = in.nextInt();
+      } catch (NumberFormatException e) {
+        throw new JsonSyntaxException(e);
+      }
+      // Allow up to 255 to support unsigned values
+      if (intValue > 255 || intValue < Byte.MIN_VALUE) {
+        throw new JsonSyntaxException("Lossy conversion from " + intValue + " to byte; at path " + in.getPreviousPath());
+      }
+      return (byte) intValue;
+    }
+    @Override
+    public void write(JsonWriter out, Number value) throws IOException {
+      out.value(value);
+    }
+  };
+
+  public static final TypeAdapterFactory BYTE_FACTORY
+      = newFactory(byte.class, Byte.class, BYTE);
+
+  public static final TypeAdapter<Number> SHORT = new TypeAdapter<Number>() {
+    @Override
+    public Number read(JsonReader in) throws IOException {
+      if (in.peek() == JsonToken.NULL) {
+        in.nextNull();
+        return null;
+      }
+
+      int intValue;
+      try {
+        intValue = in.nextInt();
+      } catch (NumberFormatException e) {
+        throw new JsonSyntaxException(e);
+      }
+      // Allow up to 65535 to support unsigned values
+      if (intValue > 65535 || intValue < Short.MIN_VALUE) {
+        throw new JsonSyntaxException("Lossy conversion from " + intValue + " to short; at path " + in.getPreviousPath());
+      }
+      return (short) intValue;
+    }
+    @Override
+    public void write(JsonWriter out, Number value) throws IOException {
+      out.value(value);
+    }
+  };
+
+  public static final TypeAdapterFactory SHORT_FACTORY
+      = newFactory(short.class, Short.class, SHORT);
+
+  public static final TypeAdapter<Number> INTEGER = new TypeAdapter<Number>() {
+    @Override
+    public Number read(JsonReader in) throws IOException {
+      if (in.peek() == JsonToken.NULL) {
+        in.nextNull();
+        return null;
+      }
+      try {
+        return in.nextInt();
+      } catch (NumberFormatException e) {
+        throw new JsonSyntaxException(e);
+      }
+    }
+    @Override
+    public void write(JsonWriter out, Number value) throws IOException {
+      out.value(value);
+    }
+  };
+  public static final TypeAdapterFactory INTEGER_FACTORY
+      = newFactory(int.class, Integer.class, INTEGER);
+
+  public static final TypeAdapter<AtomicInteger> ATOMIC_INTEGER = new TypeAdapter<AtomicInteger>() {
+    @Override public AtomicInteger read(JsonReader in) throws IOException {
+      try {
+        return new AtomicInteger(in.nextInt());
+      } catch (NumberFormatException e) {
+        throw new JsonSyntaxException(e);
+      }
+    }
+    @Override public void write(JsonWriter out, AtomicInteger value) throws IOException {
+      out.value(value.get());
+    }
+  }.nullSafe();
+  public static final TypeAdapterFactory ATOMIC_INTEGER_FACTORY =
+      newFactory(AtomicInteger.class, TypeAdapters.ATOMIC_INTEGER);
+
+  public static final TypeAdapter<AtomicBoolean> ATOMIC_BOOLEAN = new TypeAdapter<AtomicBoolean>() {
+    @Override public AtomicBoolean read(JsonReader in) throws IOException {
+      return new AtomicBoolean(in.nextBoolean());
+    }
+    @Override public void write(JsonWriter out, AtomicBoolean value) throws IOException {
+      out.value(value.get());
+    }
+  }.nullSafe();
+  public static final TypeAdapterFactory ATOMIC_BOOLEAN_FACTORY =
+      newFactory(AtomicBoolean.class, TypeAdapters.ATOMIC_BOOLEAN);
+
+  public static final TypeAdapter<AtomicIntegerArray> ATOMIC_INTEGER_ARRAY = new TypeAdapter<AtomicIntegerArray>() {
+    @Override public AtomicIntegerArray read(JsonReader in) throws IOException {
+        List<Integer> list = new ArrayList<>();
+        in.beginArray();
+        while (in.hasNext()) {
+          try {
+            int integer = in.nextInt();
+            list.add(integer);
+          } catch (NumberFormatException e) {
+            throw new JsonSyntaxException(e);
+          }
+        }
+        in.endArray();
+        int length = list.size();
+        AtomicIntegerArray array = new AtomicIntegerArray(length);
+        for (int i = 0; i < length; ++i) {
+          array.set(i, list.get(i));
+        }
+        return array;
+    }
+    @Override public void write(JsonWriter out, AtomicIntegerArray value) throws IOException {
+      out.beginArray();
+      for (int i = 0, length = value.length(); i < length; i++) {
+        out.value(value.get(i));
+      }
+      out.endArray();
+    }
+  }.nullSafe();
+  public static final TypeAdapterFactory ATOMIC_INTEGER_ARRAY_FACTORY =
+      newFactory(AtomicIntegerArray.class, TypeAdapters.ATOMIC_INTEGER_ARRAY);
+
+  public static final TypeAdapter<Number> LONG = new TypeAdapter<Number>() {
+    @Override
+    public Number read(JsonReader in) throws IOException {
+      if (in.peek() == JsonToken.NULL) {
+        in.nextNull();
+        return null;
+      }
+      try {
+        return in.nextLong();
+      } catch (NumberFormatException e) {
+        throw new JsonSyntaxException(e);
+      }
+    }
+    @Override
+    public void write(JsonWriter out, Number value) throws IOException {
+      out.value(value);
+    }
+  };
+
+  public static final TypeAdapter<Number> FLOAT = new TypeAdapter<Number>() {
+    @Override
+    public Number read(JsonReader in) throws IOException {
+      if (in.peek() == JsonToken.NULL) {
+        in.nextNull();
+        return null;
+      }
+      return (float) in.nextDouble();
+    }
+    @Override
+    public void write(JsonWriter out, Number value) throws IOException {
+      out.value(value);
+    }
+  };
+
+  public static final TypeAdapter<Number> DOUBLE = new TypeAdapter<Number>() {
+    @Override
+    public Number read(JsonReader in) throws IOException {
+      if (in.peek() == JsonToken.NULL) {
+        in.nextNull();
+        return null;
+      }
+      return in.nextDouble();
+    }
+    @Override
+    public void write(JsonWriter out, Number value) throws IOException {
+      out.value(value);
+    }
+  };
+
+  public static final TypeAdapter<Character> CHARACTER = new TypeAdapter<Character>() {
+    @Override
+    public Character read(JsonReader in) throws IOException {
+      if (in.peek() == JsonToken.NULL) {
+        in.nextNull();
+        return null;
+      }
+      String str = in.nextString();
+      if (str.length() != 1) {
+        throw new JsonSyntaxException("Expecting character, got: " + str + "; at " + in.getPreviousPath());
+      }
+      return str.charAt(0);
+    }
+    @Override
+    public void write(JsonWriter out, Character value) throws IOException {
+      out.value(value == null ? null : String.valueOf(value));
+    }
+  };
+
+  public static final TypeAdapterFactory CHARACTER_FACTORY
+      = newFactory(char.class, Character.class, CHARACTER);
+
+  public static final TypeAdapter<String> STRING = new TypeAdapter<String>() {
+    @Override
+    public String read(JsonReader in) throws IOException {
+      JsonToken peek = in.peek();
+      if (peek == JsonToken.NULL) {
+        in.nextNull();
+        return null;
+      }
+      /* coerce booleans to strings for backwards compatibility */
+      if (peek == JsonToken.BOOLEAN) {
+        return Boolean.toString(in.nextBoolean());
+      }
+      return in.nextString();
+    }
+    @Override
+    public void write(JsonWriter out, String value) throws IOException {
+      out.value(value);
+    }
+  };
+
+  public static final TypeAdapter<BigDecimal> BIG_DECIMAL = new TypeAdapter<BigDecimal>() {
+    @Override public BigDecimal read(JsonReader in) throws IOException {
+      if (in.peek() == JsonToken.NULL) {
+        in.nextNull();
+        return null;
+      }
+      String s = in.nextString();
+      try {
+        return new BigDecimal(s);
+      } catch (NumberFormatException e) {
+        throw new JsonSyntaxException("Failed parsing '" + s + "' as BigDecimal; at path " + in.getPreviousPath(), e);
+      }
+    }
+
+    @Override public void write(JsonWriter out, BigDecimal value) throws IOException {
+      out.value(value);
+    }
+  };
+
+  public static final TypeAdapter<BigInteger> BIG_INTEGER = new TypeAdapter<BigInteger>() {
+    @Override public BigInteger read(JsonReader in) throws IOException {
+      if (in.peek() == JsonToken.NULL) {
+        in.nextNull();
+        return null;
+      }
+      String s = in.nextString();
+      try {
+        return new BigInteger(s);
+      } catch (NumberFormatException e) {
+        throw new JsonSyntaxException("Failed parsing '" + s + "' as BigInteger; at path " + in.getPreviousPath(), e);
+      }
+    }
+
+    @Override public void write(JsonWriter out, BigInteger value) throws IOException {
+      out.value(value);
+    }
+  };
+
+  public static final TypeAdapter<LazilyParsedNumber> LAZILY_PARSED_NUMBER = new TypeAdapter<LazilyParsedNumber>() {
+    // Normally users should not be able to access and deserialize LazilyParsedNumber because
+    // it is an internal type, but implement this nonetheless in case there are legit corner
+    // cases where this is possible
+    @Override public LazilyParsedNumber read(JsonReader in) throws IOException {
+      if (in.peek() == JsonToken.NULL) {
+        in.nextNull();
+        return null;
+      }
+      return new LazilyParsedNumber(in.nextString());
+    }
+
+    @Override public void write(JsonWriter out, LazilyParsedNumber value) throws IOException {
+      out.value(value);
+    }
+  };
+
+  public static final TypeAdapterFactory STRING_FACTORY = newFactory(String.class, STRING);
+
+  public static final TypeAdapter<StringBuilder> STRING_BUILDER = new TypeAdapter<StringBuilder>() {
+    @Override
+    public StringBuilder read(JsonReader in) throws IOException {
+      if (in.peek() == JsonToken.NULL) {
+        in.nextNull();
+        return null;
+      }
+      return new StringBuilder(in.nextString());
+    }
+    @Override
+    public void write(JsonWriter out, StringBuilder value) throws IOException {
+      out.value(value == null ? null : value.toString());
+    }
+  };
+
+  public static final TypeAdapterFactory STRING_BUILDER_FACTORY =
+    newFactory(StringBuilder.class, STRING_BUILDER);
+
+  public static final TypeAdapter<StringBuffer> STRING_BUFFER = new TypeAdapter<StringBuffer>() {
+    @Override
+    public StringBuffer read(JsonReader in) throws IOException {
+      if (in.peek() == JsonToken.NULL) {
+        in.nextNull();
+        return null;
+      }
+      return new StringBuffer(in.nextString());
+    }
+    @Override
+    public void write(JsonWriter out, StringBuffer value) throws IOException {
+      out.value(value == null ? null : value.toString());
+    }
+  };
+
+  public static final TypeAdapterFactory STRING_BUFFER_FACTORY =
+    newFactory(StringBuffer.class, STRING_BUFFER);
+
+  public static final TypeAdapter<URL> URL = new TypeAdapter<URL>() {
+    @Override
+    public URL read(JsonReader in) throws IOException {
+      if (in.peek() == JsonToken.NULL) {
+        in.nextNull();
+        return null;
+      }
+      String nextString = in.nextString();
+      return "null".equals(nextString) ? null : new URL(nextString);
+    }
+    @Override
+    public void write(JsonWriter out, URL value) throws IOException {
+      out.value(value == null ? null : value.toExternalForm());
+    }
+  };
+
+  public static final TypeAdapterFactory URL_FACTORY = newFactory(URL.class, URL);
+
+  public static final TypeAdapter<URI> URI = new TypeAdapter<URI>() {
+    @Override
+    public URI read(JsonReader in) throws IOException {
+      if (in.peek() == JsonToken.NULL) {
+        in.nextNull();
+        return null;
+      }
+      try {
+        String nextString = in.nextString();
+        return "null".equals(nextString) ? null : new URI(nextString);
+      } catch (URISyntaxException e) {
+        throw new JsonIOException(e);
+      }
+    }
+    @Override
+    public void write(JsonWriter out, URI value) throws IOException {
+      out.value(value == null ? null : value.toASCIIString());
+    }
+  };
+
+  public static final TypeAdapterFactory URI_FACTORY = newFactory(URI.class, URI);
+
+  public static final TypeAdapter<InetAddress> INET_ADDRESS = new TypeAdapter<InetAddress>() {
+    @Override
+    public InetAddress read(JsonReader in) throws IOException {
+      if (in.peek() == JsonToken.NULL) {
+        in.nextNull();
+        return null;
+      }
+      // regrettably, this should have included both the host name and the host address
+      return InetAddress.getByName(in.nextString());
+    }
+    @Override
+    public void write(JsonWriter out, InetAddress value) throws IOException {
+      out.value(value == null ? null : value.getHostAddress());
+    }
+  };
+
+  public static final TypeAdapterFactory INET_ADDRESS_FACTORY =
+    newTypeHierarchyFactory(InetAddress.class, INET_ADDRESS);
+
+  public static final TypeAdapter<UUID> UUID = new TypeAdapter<UUID>() {
+    @Override
+    public UUID read(JsonReader in) throws IOException {
+      if (in.peek() == JsonToken.NULL) {
+        in.nextNull();
+        return null;
+      }
+      String s = in.nextString();
+      try {
+        return java.util.UUID.fromString(s);
+      } catch (IllegalArgumentException e) {
+        throw new JsonSyntaxException("Failed parsing '" + s + "' as UUID; at path " + in.getPreviousPath(), e);
+      }
+    }
+    @Override
+    public void write(JsonWriter out, UUID value) throws IOException {
+      out.value(value == null ? null : value.toString());
+    }
+  };
+
+  public static final TypeAdapterFactory UUID_FACTORY = newFactory(UUID.class, UUID);
+
+  public static final TypeAdapter<Currency> CURRENCY = new TypeAdapter<Currency>() {
+    @Override
+    public Currency read(JsonReader in) throws IOException {
+      String s = in.nextString();
+      try {
+        return Currency.getInstance(s);
+      } catch (IllegalArgumentException e) {
+        throw new JsonSyntaxException("Failed parsing '" + s + "' as Currency; at path " + in.getPreviousPath(), e);
+      }
+    }
+    @Override
+    public void write(JsonWriter out, Currency value) throws IOException {
+      out.value(value.getCurrencyCode());
+    }
+  }.nullSafe();
+  public static final TypeAdapterFactory CURRENCY_FACTORY = newFactory(Currency.class, CURRENCY);
+
+  public static final TypeAdapter<Calendar> CALENDAR = new TypeAdapter<Calendar>() {
+    private static final String YEAR = "year";
+    private static final String MONTH = "month";
+    private static final String DAY_OF_MONTH = "dayOfMonth";
+    private static final String HOUR_OF_DAY = "hourOfDay";
+    private static final String MINUTE = "minute";
+    private static final String SECOND = "second";
+
+    @Override
+    public Calendar read(JsonReader in) throws IOException {
+      if (in.peek() == JsonToken.NULL) {
+        in.nextNull();
+        return  null;
+      }
+      in.beginObject();
+      int year = 0;
+      int month = 0;
+      int dayOfMonth = 0;
+      int hourOfDay = 0;
+      int minute = 0;
+      int second = 0;
+      while (in.peek() != JsonToken.END_OBJECT) {
+        String name = in.nextName();
+        int value = in.nextInt();
+        if (YEAR.equals(name)) {
+          year = value;
+        } else if (MONTH.equals(name)) {
+          month = value;
+        } else if (DAY_OF_MONTH.equals(name)) {
+          dayOfMonth = value;
+        } else if (HOUR_OF_DAY.equals(name)) {
+          hourOfDay = value;
+        } else if (MINUTE.equals(name)) {
+          minute = value;
+        } else if (SECOND.equals(name)) {
+          second = value;
+        }
+      }
+      in.endObject();
+      return new GregorianCalendar(year, month, dayOfMonth, hourOfDay, minute, second);
+    }
+
+    @Override
+    public void write(JsonWriter out, Calendar value) throws IOException {
+      if (value == null) {
+        out.nullValue();
+        return;
+      }
+      out.beginObject();
+      out.name(YEAR);
+      out.value(value.get(Calendar.YEAR));
+      out.name(MONTH);
+      out.value(value.get(Calendar.MONTH));
+      out.name(DAY_OF_MONTH);
+      out.value(value.get(Calendar.DAY_OF_MONTH));
+      out.name(HOUR_OF_DAY);
+      out.value(value.get(Calendar.HOUR_OF_DAY));
+      out.name(MINUTE);
+      out.value(value.get(Calendar.MINUTE));
+      out.name(SECOND);
+      out.value(value.get(Calendar.SECOND));
+      out.endObject();
+    }
+  };
+
+  public static final TypeAdapterFactory CALENDAR_FACTORY =
+    newFactoryForMultipleTypes(Calendar.class, GregorianCalendar.class, CALENDAR);
+
+  public static final TypeAdapter<Locale> LOCALE = new TypeAdapter<Locale>() {
+    @Override
+    public Locale read(JsonReader in) throws IOException {
+      if (in.peek() == JsonToken.NULL) {
+        in.nextNull();
+        return null;
+      }
+      String locale = in.nextString();
+      StringTokenizer tokenizer = new StringTokenizer(locale, "_");
+      String language = null;
+      String country = null;
+      String variant = null;
+      if (tokenizer.hasMoreElements()) {
+        language = tokenizer.nextToken();
+      }
+      if (tokenizer.hasMoreElements()) {
+        country = tokenizer.nextToken();
+      }
+      if (tokenizer.hasMoreElements()) {
+        variant = tokenizer.nextToken();
+      }
+      if (country == null && variant == null) {
+        return new Locale(language);
+      } else if (variant == null) {
+        return new Locale(language, country);
+      } else {
+        return new Locale(language, country, variant);
+      }
+    }
+    @Override
+    public void write(JsonWriter out, Locale value) throws IOException {
+      out.value(value == null ? null : value.toString());
+    }
+  };
+
+  public static final TypeAdapterFactory LOCALE_FACTORY = newFactory(Locale.class, LOCALE);
+
+  public static final TypeAdapter<JsonElement> JSON_ELEMENT = new TypeAdapter<JsonElement>() {
+    /**
+     * Tries to begin reading a JSON array or JSON object, returning {@code null} if
+     * the next element is neither of those.
+     */
+    private JsonElement tryBeginNesting(JsonReader in, JsonToken peeked) throws IOException {
+      switch (peeked) {
+        case BEGIN_ARRAY:
+          in.beginArray();
+          return new JsonArray();
+        case BEGIN_OBJECT:
+          in.beginObject();
+          return new JsonObject();
+        default:
+          return null;
+      }
+    }
+
+    /** Reads a {@link JsonElement} which cannot have any nested elements */
+    private JsonElement readTerminal(JsonReader in, JsonToken peeked) throws IOException {
+      switch (peeked) {
+        case STRING:
+          return new JsonPrimitive(in.nextString());
+        case NUMBER:
+          String number = in.nextString();
+          return new JsonPrimitive(new LazilyParsedNumber(number));
+        case BOOLEAN:
+          return new JsonPrimitive(in.nextBoolean());
+        case NULL:
+          in.nextNull();
+          return JsonNull.INSTANCE;
+        default:
+          // When read(JsonReader) is called with JsonReader in invalid state
+          throw new IllegalStateException("Unexpected token: " + peeked);
+      }
+    }
+
+    @Override public JsonElement read(JsonReader in) throws IOException {
+      if (in instanceof JsonTreeReader) {
+        return ((JsonTreeReader) in).nextJsonElement();
+      }
+
+      // Either JsonArray or JsonObject
+      JsonElement current;
+      JsonToken peeked = in.peek();
+
+      current = tryBeginNesting(in, peeked);
+      if (current == null) {
+        return readTerminal(in, peeked);
+      }
+
+      Deque<JsonElement> stack = new ArrayDeque<>();
+
+      while (true) {
+        while (in.hasNext()) {
+          String name = null;
+          // Name is only used for JSON object members
+          if (current instanceof JsonObject) {
+            name = in.nextName();
+          }
+
+          peeked = in.peek();
+          JsonElement value = tryBeginNesting(in, peeked);
+          boolean isNesting = value != null;
+
+          if (value == null) {
+            value = readTerminal(in, peeked);
+          }
+
+          if (current instanceof JsonArray) {
+            ((JsonArray) current).add(value);
+          } else {
+            ((JsonObject) current).add(name, value);
+          }
+
+          if (isNesting) {
+            stack.addLast(current);
+            current = value;
+          }
+        }
+
+        // End current element
+        if (current instanceof JsonArray) {
+          in.endArray();
+        } else {
+          in.endObject();
+        }
+
+        if (stack.isEmpty()) {
+          return current;
+        } else {
+          // Continue with enclosing element
+          current = stack.removeLast();
+        }
+      }
+    }
+
+    @Override public void write(JsonWriter out, JsonElement value) throws IOException {
+      if (value == null || value.isJsonNull()) {
+        out.nullValue();
+      } else if (value.isJsonPrimitive()) {
+        JsonPrimitive primitive = value.getAsJsonPrimitive();
+        if (primitive.isNumber()) {
+          out.value(primitive.getAsNumber());
+        } else if (primitive.isBoolean()) {
+          out.value(primitive.getAsBoolean());
+        } else {
+          out.value(primitive.getAsString());
+        }
+
+      } else if (value.isJsonArray()) {
+        out.beginArray();
+        for (JsonElement e : value.getAsJsonArray()) {
+          write(out, e);
+        }
+        out.endArray();
+
+      } else if (value.isJsonObject()) {
+        out.beginObject();
+        for (Map.Entry<String, JsonElement> e : value.getAsJsonObject().entrySet()) {
+          out.name(e.getKey());
+          write(out, e.getValue());
+        }
+        out.endObject();
+
+      } else {
+        throw new IllegalArgumentException("Couldn't write " + value.getClass());
+      }
+    }
+  };
+
+  public static final TypeAdapterFactory JSON_ELEMENT_FACTORY
+      = newTypeHierarchyFactory(JsonElement.class, JSON_ELEMENT);
+
+  private static final class EnumTypeAdapter<T extends Enum<T>> extends TypeAdapter<T> {
+    private final Map<String, T> nameToConstant = new HashMap<>();
+    private final Map<String, T> stringToConstant = new HashMap<>();
+    private final Map<T, String> constantToName = new HashMap<>();
+
+    public EnumTypeAdapter(final Class<T> classOfT) {
+      try {
+        // Uses reflection to find enum constants to work around name mismatches for obfuscated classes
+        // Reflection access might throw SecurityException, therefore run this in privileged context;
+        // should be acceptable because this only retrieves enum constants, but does not expose anything else
+        Field[] constantFields = AccessController.doPrivileged(new PrivilegedAction<Field[]>() {
+          @Override public Field[] run() {
+            Field[] fields = classOfT.getDeclaredFields();
+            ArrayList<Field> constantFieldsList = new ArrayList<>(fields.length);
+            for (Field f : fields) {
+              if (f.isEnumConstant()) {
+                constantFieldsList.add(f);
+              }
+            }
+
+            Field[] constantFields = constantFieldsList.toArray(new Field[0]);
+            AccessibleObject.setAccessible(constantFields, true);
+            return constantFields;
+          }
+        });
+        for (Field constantField : constantFields) {
+          @SuppressWarnings("unchecked")
+          T constant = (T)(constantField.get(null));
+          String name = constant.name();
+          String toStringVal = constant.toString();
+
+          SerializedName annotation = constantField.getAnnotation(SerializedName.class);
+          if (annotation != null) {
+            name = annotation.value();
+            for (String alternate : annotation.alternate()) {
+              nameToConstant.put(alternate, constant);
+            }
+          }
+          nameToConstant.put(name, constant);
+          stringToConstant.put(toStringVal, constant);
+          constantToName.put(constant, name);
+        }
+      } catch (IllegalAccessException e) {
+        throw new AssertionError(e);
+      }
+    }
+    @Override public T read(JsonReader in) throws IOException {
+      if (in.peek() == JsonToken.NULL) {
+        in.nextNull();
+        return null;
+      }
+      String key = in.nextString();
+      T constant = nameToConstant.get(key);
+      return (constant == null) ? stringToConstant.get(key) : constant;
+    }
+
+    @Override public void write(JsonWriter out, T value) throws IOException {
+      out.value(value == null ? null : constantToName.get(value));
+    }
+  }
+
+  public static final TypeAdapterFactory ENUM_FACTORY = new TypeAdapterFactory() {
+    @SuppressWarnings({"rawtypes", "unchecked"})
+    @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
+      Class<? super T> rawType = typeToken.getRawType();
+      if (!Enum.class.isAssignableFrom(rawType) || rawType == Enum.class) {
+        return null;
+      }
+      if (!rawType.isEnum()) {
+        rawType = rawType.getSuperclass(); // handle anonymous subclasses
+      }
+      return (TypeAdapter<T>) new EnumTypeAdapter(rawType);
+    }
+  };
+
+  public static <TT> TypeAdapterFactory newFactory(
+      final TypeToken<TT> type, final TypeAdapter<TT> typeAdapter) {
+    return new TypeAdapterFactory() {
+      @SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal
+      @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
+        return typeToken.equals(type) ? (TypeAdapter<T>) typeAdapter : null;
+      }
+    };
+  }
+
+  public static <TT> TypeAdapterFactory newFactory(
+      final Class<TT> type, final TypeAdapter<TT> typeAdapter) {
+    return new TypeAdapterFactory() {
+      @SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal
+      @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
+        return typeToken.getRawType() == type ? (TypeAdapter<T>) typeAdapter : null;
+      }
+      @Override public String toString() {
+        return "Factory[type=" + type.getName() + ",adapter=" + typeAdapter + "]";
+      }
+    };
+  }
+
+  public static <TT> TypeAdapterFactory newFactory(
+      final Class<TT> unboxed, final Class<TT> boxed, final TypeAdapter<? super TT> typeAdapter) {
+    return new TypeAdapterFactory() {
+      @SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal
+      @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
+        Class<? super T> rawType = typeToken.getRawType();
+        return (rawType == unboxed || rawType == boxed) ? (TypeAdapter<T>) typeAdapter : null;
+      }
+      @Override public String toString() {
+        return "Factory[type=" + boxed.getName()
+            + "+" + unboxed.getName() + ",adapter=" + typeAdapter + "]";
+      }
+    };
+  }
+
+  public static <TT> TypeAdapterFactory newFactoryForMultipleTypes(final Class<TT> base,
+      final Class<? extends TT> sub, final TypeAdapter<? super TT> typeAdapter) {
+    return new TypeAdapterFactory() {
+      @SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal
+      @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
+        Class<? super T> rawType = typeToken.getRawType();
+        return (rawType == base || rawType == sub) ? (TypeAdapter<T>) typeAdapter : null;
+      }
+      @Override public String toString() {
+        return "Factory[type=" + base.getName()
+            + "+" + sub.getName() + ",adapter=" + typeAdapter + "]";
+      }
+    };
+  }
+
+  /**
+   * Returns a factory for all subtypes of {@code typeAdapter}. We do a runtime check to confirm
+   * that the deserialized type matches the type requested.
+   */
+  public static <T1> TypeAdapterFactory newTypeHierarchyFactory(
+      final Class<T1> clazz, final TypeAdapter<T1> typeAdapter) {
+    return new TypeAdapterFactory() {
+      @SuppressWarnings("unchecked")
+      @Override public <T2> TypeAdapter<T2> create(Gson gson, TypeToken<T2> typeToken) {
+        final Class<? super T2> requestedType = typeToken.getRawType();
+        if (!clazz.isAssignableFrom(requestedType)) {
+          return null;
+        }
+        return (TypeAdapter<T2>) new TypeAdapter<T1>() {
+          @Override public void write(JsonWriter out, T1 value) throws IOException {
+            typeAdapter.write(out, value);
+          }
+
+          @Override public T1 read(JsonReader in) throws IOException {
+            T1 result = typeAdapter.read(in);
+            if (result != null && !requestedType.isInstance(result)) {
+              throw new JsonSyntaxException("Expected a " + requestedType.getName()
+                  + " but was " + result.getClass().getName() + "; at path " + in.getPreviousPath());
+            }
+            return result;
+          }
+        };
+      }
+      @Override public String toString() {
+        return "Factory[typeHierarchy=" + clazz.getName() + ",adapter=" + typeAdapter + "]";
+      }
+    };
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/internal/bind/util/ISO8601Utils.java b/gson/src/main/java/com/google/gson/internal/bind/util/ISO8601Utils.java
new file mode 100644
index 0000000..02454fe
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/internal/bind/util/ISO8601Utils.java
@@ -0,0 +1,357 @@
+package com.google.gson.internal.bind.util;
+
+import java.text.ParseException;
+import java.text.ParsePosition;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.Locale;
+import java.util.TimeZone;
+
+/**
+ * Utilities methods for manipulating dates in iso8601 format. This is much much faster and GC friendly than using SimpleDateFormat so
+ * highly suitable if you (un)serialize lots of date objects.
+ * 
+ * Supported parse format: [yyyy-MM-dd|yyyyMMdd][T(hh:mm[:ss[.sss]]|hhmm[ss[.sss]])]?[Z|[+-]hh[:]mm]]
+ * 
+ * @see <a href="http://www.w3.org/TR/NOTE-datetime">this specification</a>
+ */
+//Date parsing code from Jackson databind ISO8601Utils.java
+// https://github.com/FasterXML/jackson-databind/blob/master/src/main/java/com/fasterxml/jackson/databind/util/ISO8601Utils.java
+public class ISO8601Utils
+{
+    /**
+     * ID to represent the 'UTC' string, default timezone since Jackson 2.7
+     * 
+     * @since 2.7
+     */
+    private static final String UTC_ID = "UTC";
+    /**
+     * The UTC timezone, prefetched to avoid more lookups.
+     * 
+     * @since 2.7
+     */
+    private static final TimeZone TIMEZONE_UTC = TimeZone.getTimeZone(UTC_ID);
+
+    /*
+    /**********************************************************
+    /* Formatting
+    /**********************************************************
+     */
+
+    /**
+     * Format a date into 'yyyy-MM-ddThh:mm:ssZ' (default timezone, no milliseconds precision)
+     * 
+     * @param date the date to format
+     * @return the date formatted as 'yyyy-MM-ddThh:mm:ssZ'
+     */
+    public static String format(Date date) {
+        return format(date, false, TIMEZONE_UTC);
+    }
+
+    /**
+     * Format a date into 'yyyy-MM-ddThh:mm:ss[.sss]Z' (GMT timezone)
+     * 
+     * @param date the date to format
+     * @param millis true to include millis precision otherwise false
+     * @return the date formatted as 'yyyy-MM-ddThh:mm:ss[.sss]Z'
+     */
+    public static String format(Date date, boolean millis) {
+        return format(date, millis, TIMEZONE_UTC);
+    }
+
+    /**
+     * Format date into yyyy-MM-ddThh:mm:ss[.sss][Z|[+-]hh:mm]
+     * 
+     * @param date the date to format
+     * @param millis true to include millis precision otherwise false
+     * @param tz timezone to use for the formatting (UTC will produce 'Z')
+     * @return the date formatted as yyyy-MM-ddThh:mm:ss[.sss][Z|[+-]hh:mm]
+     */
+    public static String format(Date date, boolean millis, TimeZone tz) {
+        Calendar calendar = new GregorianCalendar(tz, Locale.US);
+        calendar.setTime(date);
+
+        // estimate capacity of buffer as close as we can (yeah, that's pedantic ;)
+        int capacity = "yyyy-MM-ddThh:mm:ss".length();
+        capacity += millis ? ".sss".length() : 0;
+        capacity += tz.getRawOffset() == 0 ? "Z".length() : "+hh:mm".length();
+        StringBuilder formatted = new StringBuilder(capacity);
+
+        padInt(formatted, calendar.get(Calendar.YEAR), "yyyy".length());
+        formatted.append('-');
+        padInt(formatted, calendar.get(Calendar.MONTH) + 1, "MM".length());
+        formatted.append('-');
+        padInt(formatted, calendar.get(Calendar.DAY_OF_MONTH), "dd".length());
+        formatted.append('T');
+        padInt(formatted, calendar.get(Calendar.HOUR_OF_DAY), "hh".length());
+        formatted.append(':');
+        padInt(formatted, calendar.get(Calendar.MINUTE), "mm".length());
+        formatted.append(':');
+        padInt(formatted, calendar.get(Calendar.SECOND), "ss".length());
+        if (millis) {
+            formatted.append('.');
+            padInt(formatted, calendar.get(Calendar.MILLISECOND), "sss".length());
+        }
+
+        int offset = tz.getOffset(calendar.getTimeInMillis());
+        if (offset != 0) {
+            int hours = Math.abs((offset / (60 * 1000)) / 60);
+            int minutes = Math.abs((offset / (60 * 1000)) % 60);
+            formatted.append(offset < 0 ? '-' : '+');
+            padInt(formatted, hours, "hh".length());
+            formatted.append(':');
+            padInt(formatted, minutes, "mm".length());
+        } else {
+            formatted.append('Z');
+        }
+
+        return formatted.toString();
+    }
+
+    /*
+    /**********************************************************
+    /* Parsing
+    /**********************************************************
+     */
+
+    /**
+     * Parse a date from ISO-8601 formatted string. It expects a format
+     * [yyyy-MM-dd|yyyyMMdd][T(hh:mm[:ss[.sss]]|hhmm[ss[.sss]])]?[Z|[+-]hh[:mm]]]
+     * 
+     * @param date ISO string to parse in the appropriate format.
+     * @param pos The position to start parsing from, updated to where parsing stopped.
+     * @return the parsed date
+     * @throws ParseException if the date is not in the appropriate format
+     */
+    public static Date parse(String date, ParsePosition pos) throws ParseException {
+        Exception fail = null;
+        try {
+            int offset = pos.getIndex();
+
+            // extract year
+            int year = parseInt(date, offset, offset += 4);
+            if (checkOffset(date, offset, '-')) {
+                offset += 1;
+            }
+
+            // extract month
+            int month = parseInt(date, offset, offset += 2);
+            if (checkOffset(date, offset, '-')) {
+                offset += 1;
+            }
+
+            // extract day
+            int day = parseInt(date, offset, offset += 2);
+            // default time value
+            int hour = 0;
+            int minutes = 0;
+            int seconds = 0;
+            int milliseconds = 0; // always use 0 otherwise returned date will include millis of current time
+
+            // if the value has no time component (and no time zone), we are done
+            boolean hasT = checkOffset(date, offset, 'T');
+
+            if (!hasT && (date.length() <= offset)) {
+                Calendar calendar = new GregorianCalendar(year, month - 1, day);
+                calendar.setLenient(false);
+
+                pos.setIndex(offset);
+                return calendar.getTime();
+            }
+
+            if (hasT) {
+
+                // extract hours, minutes, seconds and milliseconds
+                hour = parseInt(date, offset += 1, offset += 2);
+                if (checkOffset(date, offset, ':')) {
+                    offset += 1;
+                }
+
+                minutes = parseInt(date, offset, offset += 2);
+                if (checkOffset(date, offset, ':')) {
+                    offset += 1;
+                }
+                // second and milliseconds can be optional
+                if (date.length() > offset) {
+                    char c = date.charAt(offset);
+                    if (c != 'Z' && c != '+' && c != '-') {
+                        seconds = parseInt(date, offset, offset += 2);
+                        if (seconds > 59 && seconds < 63) seconds = 59; // truncate up to 3 leap seconds
+                        // milliseconds can be optional in the format
+                        if (checkOffset(date, offset, '.')) {
+                            offset += 1;
+                            int endOffset = indexOfNonDigit(date, offset + 1); // assume at least one digit
+                            int parseEndOffset = Math.min(endOffset, offset + 3); // parse up to 3 digits
+                            int fraction = parseInt(date, offset, parseEndOffset);
+                            // compensate for "missing" digits
+                            switch (parseEndOffset - offset) { // number of digits parsed
+                            case 2:
+                                milliseconds = fraction * 10;
+                                break;
+                            case 1:
+                                milliseconds = fraction * 100;
+                                break;
+                            default:
+                                milliseconds = fraction;
+                            }
+                            offset = endOffset;
+                        }
+                    }
+                }
+            }
+
+            // extract timezone
+            if (date.length() <= offset) {
+                throw new IllegalArgumentException("No time zone indicator");
+            }
+
+            TimeZone timezone = null;
+            char timezoneIndicator = date.charAt(offset);
+
+            if (timezoneIndicator == 'Z') {
+                timezone = TIMEZONE_UTC;
+                offset += 1;
+            } else if (timezoneIndicator == '+' || timezoneIndicator == '-') {
+                String timezoneOffset = date.substring(offset);
+
+                // When timezone has no minutes, we should append it, valid timezones are, for example: +00:00, +0000 and +00
+                timezoneOffset = timezoneOffset.length() >= 5 ? timezoneOffset : timezoneOffset + "00";
+
+                offset += timezoneOffset.length();
+                // 18-Jun-2015, tatu: Minor simplification, skip offset of "+0000"/"+00:00"
+                if ("+0000".equals(timezoneOffset) || "+00:00".equals(timezoneOffset)) {
+                    timezone = TIMEZONE_UTC;
+                } else {
+                    // 18-Jun-2015, tatu: Looks like offsets only work from GMT, not UTC...
+                    //    not sure why, but that's the way it looks. Further, Javadocs for
+                    //    `java.util.TimeZone` specifically instruct use of GMT as base for
+                    //    custom timezones... odd.
+                    String timezoneId = "GMT" + timezoneOffset;
+//                    String timezoneId = "UTC" + timezoneOffset;
+
+                    timezone = TimeZone.getTimeZone(timezoneId);
+
+                    String act = timezone.getID();
+                    if (!act.equals(timezoneId)) {
+                        /* 22-Jan-2015, tatu: Looks like canonical version has colons, but we may be given
+                         *    one without. If so, don't sweat.
+                         *   Yes, very inefficient. Hopefully not hit often.
+                         *   If it becomes a perf problem, add 'loose' comparison instead.
+                         */
+                        String cleaned = act.replace(":", "");
+                        if (!cleaned.equals(timezoneId)) {
+                            throw new IndexOutOfBoundsException("Mismatching time zone indicator: "+timezoneId+" given, resolves to "
+                                    +timezone.getID());
+                        }
+                    }
+                }
+            } else {
+                throw new IndexOutOfBoundsException("Invalid time zone indicator '" + timezoneIndicator+"'");
+            }
+
+            Calendar calendar = new GregorianCalendar(timezone);
+            calendar.setLenient(false);
+            calendar.set(Calendar.YEAR, year);
+            calendar.set(Calendar.MONTH, month - 1);
+            calendar.set(Calendar.DAY_OF_MONTH, day);
+            calendar.set(Calendar.HOUR_OF_DAY, hour);
+            calendar.set(Calendar.MINUTE, minutes);
+            calendar.set(Calendar.SECOND, seconds);
+            calendar.set(Calendar.MILLISECOND, milliseconds);
+
+            pos.setIndex(offset);
+            return calendar.getTime();
+            // If we get a ParseException it'll already have the right message/offset.
+            // Other exception types can convert here.
+        } catch (IndexOutOfBoundsException e) {
+            fail = e;
+        } catch (NumberFormatException e) {
+            fail = e;
+        } catch (IllegalArgumentException e) {
+            fail = e;
+        }
+        String input = (date == null) ? null : ('"' + date + '"');
+        String msg = fail.getMessage();
+        if (msg == null || msg.isEmpty()) {
+            msg = "("+fail.getClass().getName()+")";
+        }
+        ParseException ex = new ParseException("Failed to parse date [" + input + "]: " + msg, pos.getIndex());
+        ex.initCause(fail);
+        throw ex;
+    }
+
+    /**
+     * Check if the expected character exist at the given offset in the value.
+     * 
+     * @param value the string to check at the specified offset
+     * @param offset the offset to look for the expected character
+     * @param expected the expected character
+     * @return true if the expected character exist at the given offset
+     */
+    private static boolean checkOffset(String value, int offset, char expected) {
+        return (offset < value.length()) && (value.charAt(offset) == expected);
+    }
+
+    /**
+     * Parse an integer located between 2 given offsets in a string
+     * 
+     * @param value the string to parse
+     * @param beginIndex the start index for the integer in the string
+     * @param endIndex the end index for the integer in the string
+     * @return the int
+     * @throws NumberFormatException if the value is not a number
+     */
+    private static int parseInt(String value, int beginIndex, int endIndex) throws NumberFormatException {
+        if (beginIndex < 0 || endIndex > value.length() || beginIndex > endIndex) {
+            throw new NumberFormatException(value);
+        }
+        // use same logic as in Integer.parseInt() but less generic we're not supporting negative values
+        int i = beginIndex;
+        int result = 0;
+        int digit;
+        if (i < endIndex) {
+            digit = Character.digit(value.charAt(i++), 10);
+            if (digit < 0) {
+                throw new NumberFormatException("Invalid number: " + value.substring(beginIndex, endIndex));
+            }
+            result = -digit;
+        }
+        while (i < endIndex) {
+            digit = Character.digit(value.charAt(i++), 10);
+            if (digit < 0) {
+                throw new NumberFormatException("Invalid number: " + value.substring(beginIndex, endIndex));
+            }
+            result *= 10;
+            result -= digit;
+        }
+        return -result;
+    }
+
+    /**
+     * Zero pad a number to a specified length
+     * 
+     * @param buffer buffer to use for padding
+     * @param value the integer value to pad if necessary.
+     * @param length the length of the string we should zero pad
+     */
+    private static void padInt(StringBuilder buffer, int value, int length) {
+        String strValue = Integer.toString(value);
+        for (int i = length - strValue.length(); i > 0; i--) {
+            buffer.append('0');
+        }
+        buffer.append(strValue);
+    }
+
+    /**
+     * Returns the index of the first character in the string that is not a digit, starting at offset.
+     */
+    private static int indexOfNonDigit(String string, int offset) {
+        for (int i = offset; i < string.length(); i++) {
+            char c = string.charAt(i);
+            if (c < '0' || c > '9') return i;
+        }
+        return string.length();
+    }
+
+}
diff --git a/gson/src/main/java/com/google/gson/internal/package-info.java b/gson/src/main/java/com/google/gson/internal/package-info.java
new file mode 100644
index 0000000..b5139b6
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/internal/package-info.java
@@ -0,0 +1,7 @@
+/**
+ * Do NOT use any class in this package as they are meant for internal use in Gson.
+ * These classes will very likely change incompatibly in future versions. You have been warned.
+ *
+ * @author Inderjeet Singh, Joel Leitch, Jesse Wilson
+ */
+package com.google.gson.internal;
\ No newline at end of file
diff --git a/gson/src/main/java/com/google/gson/internal/reflect/ReflectionHelper.java b/gson/src/main/java/com/google/gson/internal/reflect/ReflectionHelper.java
new file mode 100644
index 0000000..97230ff
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/internal/reflect/ReflectionHelper.java
@@ -0,0 +1,74 @@
+package com.google.gson.internal.reflect;
+
+import com.google.gson.JsonIOException;
+import com.google.gson.internal.GsonBuildConfig;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Field;
+
+public class ReflectionHelper {
+  private ReflectionHelper() { }
+
+  /**
+   * Tries making the field accessible, wrapping any thrown exception in a
+   * {@link JsonIOException} with descriptive message.
+   *
+   * @param field field to make accessible
+   * @throws JsonIOException if making the field accessible fails
+   */
+  public static void makeAccessible(Field field) throws JsonIOException {
+    try {
+      field.setAccessible(true);
+    } catch (Exception exception) {
+      throw new JsonIOException("Failed making field '" + field.getDeclaringClass().getName() + "#"
+          + field.getName() + "' accessible; either change its visibility or write a custom "
+          + "TypeAdapter for its declaring type", exception);
+    }
+  }
+
+  /**
+   * Creates a string representation for a constructor.
+   * E.g.: {@code java.lang.String#String(char[], int, int)}
+   */
+  private static String constructorToString(Constructor<?> constructor) {
+    StringBuilder stringBuilder = new StringBuilder(constructor.getDeclaringClass().getName())
+      .append('#')
+      .append(constructor.getDeclaringClass().getSimpleName())
+      .append('(');
+    Class<?>[] parameters = constructor.getParameterTypes();
+    for (int i = 0; i < parameters.length; i++) {
+      if (i > 0) {
+        stringBuilder.append(", ");
+      }
+      stringBuilder.append(parameters[i].getSimpleName());
+    }
+
+    return stringBuilder.append(')').toString();
+  }
+
+  /**
+   * Tries making the constructor accessible, returning an exception message
+   * if this fails.
+   *
+   * @param constructor constructor to make accessible
+   * @return exception message; {@code null} if successful, non-{@code null} if
+   *    unsuccessful
+   */
+  public static String tryMakeAccessible(Constructor<?> constructor) {
+    try {
+      constructor.setAccessible(true);
+      return null;
+    } catch (Exception exception) {
+      return "Failed making constructor '" + constructorToString(constructor) + "' accessible; "
+          + "either change its visibility or write a custom InstanceCreator or TypeAdapter for its declaring type: "
+          // Include the message since it might contain more detailed information
+          + exception.getMessage();
+    }
+  }
+
+  public static RuntimeException createExceptionForUnexpectedIllegalAccess(IllegalAccessException exception) {
+    throw new RuntimeException("Unexpected IllegalAccessException occurred (Gson " + GsonBuildConfig.VERSION + "). "
+        + "Certain ReflectionAccessFilter features require Java >= 9 to work correctly. If you are not using "
+        + "ReflectionAccessFilter, report this to the Gson maintainers.",
+        exception);
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/internal/sql/SqlDateTypeAdapter.java b/gson/src/main/java/com/google/gson/internal/sql/SqlDateTypeAdapter.java
new file mode 100644
index 0000000..6ae4c3e
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/internal/sql/SqlDateTypeAdapter.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.internal.sql;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonSyntaxException;
+import com.google.gson.TypeAdapter;
+import com.google.gson.TypeAdapterFactory;
+import com.google.gson.reflect.TypeToken;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonToken;
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
+import java.text.DateFormat;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+/**
+ * Adapter for java.sql.Date. Although this class appears stateless, it is not.
+ * DateFormat captures its time zone and locale when it is created, which gives
+ * this class state. DateFormat isn't thread safe either, so this class has
+ * to synchronize its read and write methods.
+ */
+final class SqlDateTypeAdapter extends TypeAdapter<java.sql.Date> {
+  static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() {
+    @SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal
+    @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
+      return typeToken.getRawType() == java.sql.Date.class
+          ? (TypeAdapter<T>) new SqlDateTypeAdapter() : null;
+    }
+  };
+
+  private final DateFormat format = new SimpleDateFormat("MMM d, yyyy");
+
+  private SqlDateTypeAdapter() {
+  }
+
+  @Override
+  public java.sql.Date read(JsonReader in) throws IOException {
+    if (in.peek() == JsonToken.NULL) {
+      in.nextNull();
+      return null;
+    }
+    String s = in.nextString();
+    try {
+      Date utilDate;
+      synchronized (this) {
+        utilDate = format.parse(s);
+      }
+      return new java.sql.Date(utilDate.getTime());
+    } catch (ParseException e) {
+      throw new JsonSyntaxException("Failed parsing '" + s + "' as SQL Date; at path " + in.getPreviousPath(), e);
+    }
+  }
+
+  @Override
+  public void write(JsonWriter out, java.sql.Date value) throws IOException {
+    if (value == null) {
+      out.nullValue();
+      return;
+    }
+    String dateString;
+    synchronized (this) {
+      dateString = format.format(value);
+    }
+    out.value(dateString);
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/internal/sql/SqlTimeTypeAdapter.java b/gson/src/main/java/com/google/gson/internal/sql/SqlTimeTypeAdapter.java
new file mode 100644
index 0000000..c2a3707
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/internal/sql/SqlTimeTypeAdapter.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.internal.sql;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonSyntaxException;
+import com.google.gson.TypeAdapter;
+import com.google.gson.TypeAdapterFactory;
+import com.google.gson.reflect.TypeToken;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonToken;
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
+import java.sql.Time;
+import java.text.DateFormat;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+/**
+ * Adapter for java.sql.Time. Although this class appears stateless, it is not.
+ * DateFormat captures its time zone and locale when it is created, which gives
+ * this class state. DateFormat isn't thread safe either, so this class has
+ * to synchronize its read and write methods.
+ */
+final class SqlTimeTypeAdapter extends TypeAdapter<Time> {
+  static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() {
+    @SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal
+    @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
+      return typeToken.getRawType() == Time.class ? (TypeAdapter<T>) new SqlTimeTypeAdapter() : null;
+    }
+  };
+
+  private final DateFormat format = new SimpleDateFormat("hh:mm:ss a");
+
+  private SqlTimeTypeAdapter() {
+  }
+
+  @Override public Time read(JsonReader in) throws IOException {
+    if (in.peek() == JsonToken.NULL) {
+      in.nextNull();
+      return null;
+    }
+    String s = in.nextString();
+    try {
+      synchronized (this) {
+        Date date = format.parse(s);
+        return new Time(date.getTime());
+      }
+    } catch (ParseException e) {
+      throw new JsonSyntaxException("Failed parsing '" + s + "' as SQL Time; at path " + in.getPreviousPath(), e);
+    }
+  }
+
+  @Override public void write(JsonWriter out, Time value) throws IOException {
+    if (value == null) {
+      out.nullValue();
+      return;
+    }
+    String timeString;
+    synchronized (this) {
+      timeString = format.format(value);
+    }
+    out.value(timeString);
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/internal/sql/SqlTimestampTypeAdapter.java b/gson/src/main/java/com/google/gson/internal/sql/SqlTimestampTypeAdapter.java
new file mode 100644
index 0000000..06688c5
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/internal/sql/SqlTimestampTypeAdapter.java
@@ -0,0 +1,43 @@
+package com.google.gson.internal.sql;
+
+import com.google.gson.Gson;
+import com.google.gson.TypeAdapter;
+import com.google.gson.TypeAdapterFactory;
+import com.google.gson.reflect.TypeToken;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonWriter;
+
+import java.io.IOException;
+import java.sql.Timestamp;
+import java.util.Date;
+
+class SqlTimestampTypeAdapter extends TypeAdapter<Timestamp> {
+  static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() {
+    @SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal
+    @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
+      if (typeToken.getRawType() == Timestamp.class) {
+        final TypeAdapter<Date> dateTypeAdapter = gson.getAdapter(Date.class);
+        return (TypeAdapter<T>) new SqlTimestampTypeAdapter(dateTypeAdapter);
+      } else {
+        return null;
+      }
+    }
+  };
+
+  private final TypeAdapter<Date> dateTypeAdapter;
+
+  private SqlTimestampTypeAdapter(TypeAdapter<Date> dateTypeAdapter) {
+    this.dateTypeAdapter = dateTypeAdapter;
+  }
+
+  @Override
+  public Timestamp read(JsonReader in) throws IOException {
+    Date date = dateTypeAdapter.read(in);
+    return date != null ? new Timestamp(date.getTime()) : null;
+  }
+
+  @Override
+  public void write(JsonWriter out, Timestamp value) throws IOException {
+    dateTypeAdapter.write(out, value);
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/internal/sql/SqlTypesSupport.java b/gson/src/main/java/com/google/gson/internal/sql/SqlTypesSupport.java
new file mode 100644
index 0000000..92bdfd3
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/internal/sql/SqlTypesSupport.java
@@ -0,0 +1,71 @@
+package com.google.gson.internal.sql;
+
+import java.sql.Timestamp;
+import java.util.Date;
+
+import com.google.gson.TypeAdapterFactory;
+import com.google.gson.internal.bind.DefaultDateTypeAdapter.DateType;
+
+/**
+ * Encapsulates access to {@code java.sql} types, to allow Gson to
+ * work without the {@code java.sql} module being present.
+ * No {@link ClassNotFoundException}s will be thrown in case
+ * the {@code java.sql} module is not present.
+ *
+ * <p>If {@link #SUPPORTS_SQL_TYPES} is {@code true}, all other
+ * constants of this class will be non-{@code null}. However, if
+ * it is {@code false} all other constants will be {@code null} and
+ * there will be no support for {@code java.sql} types.
+ */
+public final class SqlTypesSupport {
+  /**
+   * {@code true} if {@code java.sql} types are supported,
+   * {@code false} otherwise
+   */
+  public static final boolean SUPPORTS_SQL_TYPES;
+
+  public static final DateType<? extends Date> DATE_DATE_TYPE;
+  public static final DateType<? extends Date> TIMESTAMP_DATE_TYPE;
+
+  public static final TypeAdapterFactory DATE_FACTORY;
+  public static final TypeAdapterFactory TIME_FACTORY;
+  public static final TypeAdapterFactory TIMESTAMP_FACTORY;
+
+  static {
+    boolean sqlTypesSupport;
+    try {
+      Class.forName("java.sql.Date");
+      sqlTypesSupport = true;
+    } catch (ClassNotFoundException classNotFoundException) {
+      sqlTypesSupport = false;
+    }
+    SUPPORTS_SQL_TYPES = sqlTypesSupport;
+
+    if (SUPPORTS_SQL_TYPES) {
+      DATE_DATE_TYPE = new DateType<java.sql.Date>(java.sql.Date.class) {
+        @Override protected java.sql.Date deserialize(Date date) {
+          return new java.sql.Date(date.getTime());
+        }
+      };
+      TIMESTAMP_DATE_TYPE = new DateType<Timestamp>(Timestamp.class) {
+        @Override protected Timestamp deserialize(Date date) {
+          return new Timestamp(date.getTime());
+        }
+      };
+
+      DATE_FACTORY = SqlDateTypeAdapter.FACTORY;
+      TIME_FACTORY = SqlTimeTypeAdapter.FACTORY;
+      TIMESTAMP_FACTORY = SqlTimestampTypeAdapter.FACTORY;
+    } else {
+      DATE_DATE_TYPE = null;
+      TIMESTAMP_DATE_TYPE = null;
+
+      DATE_FACTORY = null;
+      TIME_FACTORY = null;
+      TIMESTAMP_FACTORY = null;
+    }
+  }
+
+  private SqlTypesSupport() {
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/package-info.java b/gson/src/main/java/com/google/gson/package-info.java
new file mode 100644
index 0000000..428e280
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/package-info.java
@@ -0,0 +1,11 @@
+/**
+ * This package provides the {@link com.google.gson.Gson} class to convert Json to Java and
+ * vice-versa.
+ *
+ * <p>The primary class to use is {@link com.google.gson.Gson} which can be constructed with
+ * {@code new Gson()} (using default settings) or by using {@link com.google.gson.GsonBuilder}
+ * (to configure various options such as using versioning and so on).</p>
+ *
+ * @author Inderjeet Singh, Joel Leitch
+ */
+package com.google.gson;
\ No newline at end of file
diff --git a/gson/src/main/java/com/google/gson/reflect/TypeToken.java b/gson/src/main/java/com/google/gson/reflect/TypeToken.java
new file mode 100644
index 0000000..b12d201
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/reflect/TypeToken.java
@@ -0,0 +1,333 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.reflect;
+
+import com.google.gson.internal.$Gson$Types;
+import com.google.gson.internal.$Gson$Preconditions;
+import java.lang.reflect.GenericArrayType;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.lang.reflect.TypeVariable;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Represents a generic type {@code T}. Java doesn't yet provide a way to
+ * represent generic types, so this class does. Forces clients to create a
+ * subclass of this class which enables retrieval the type information even at
+ * runtime.
+ *
+ * <p>For example, to create a type literal for {@code List<String>}, you can
+ * create an empty anonymous inner class:
+ *
+ * <p>
+ * {@code TypeToken<List<String>> list = new TypeToken<List<String>>() {};}
+ *
+ * <p>Capturing a type variable as type argument of a {@code TypeToken} should
+ * be avoided. Due to type erasure the runtime type of a type variable is not
+ * available to Gson and therefore it cannot provide the functionality one
+ * might expect, which gives a false sense of type-safety at compilation time
+ * and can lead to an unexpected {@code ClassCastException} at runtime.
+ *
+ * @author Bob Lee
+ * @author Sven Mawson
+ * @author Jesse Wilson
+ */
+public class TypeToken<T> {
+  private final Class<? super T> rawType;
+  private final Type type;
+  private final int hashCode;
+
+  /**
+   * Constructs a new type literal. Derives represented class from type
+   * parameter.
+   *
+   * <p>Clients create an empty anonymous subclass. Doing so embeds the type
+   * parameter in the anonymous class's type hierarchy so we can reconstitute it
+   * at runtime despite erasure.
+   */
+  @SuppressWarnings("unchecked")
+  protected TypeToken() {
+    this.type = getTypeTokenTypeArgument();
+    this.rawType = (Class<? super T>) $Gson$Types.getRawType(type);
+    this.hashCode = type.hashCode();
+  }
+
+  /**
+   * Unsafe. Constructs a type literal manually.
+   */
+  @SuppressWarnings("unchecked")
+  private TypeToken(Type type) {
+    this.type = $Gson$Types.canonicalize($Gson$Preconditions.checkNotNull(type));
+    this.rawType = (Class<? super T>) $Gson$Types.getRawType(this.type);
+    this.hashCode = this.type.hashCode();
+  }
+
+  /**
+   * Verifies that {@code this} is an instance of a direct subclass of TypeToken and
+   * returns the type argument for {@code T} in {@link $Gson$Types#canonicalize
+   * canonical form}.
+   */
+  private Type getTypeTokenTypeArgument() {
+    Type superclass = getClass().getGenericSuperclass();
+    if (superclass instanceof ParameterizedType) {
+      ParameterizedType parameterized = (ParameterizedType) superclass;
+      if (parameterized.getRawType() == TypeToken.class) {
+        return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]);
+      }
+    }
+    // Check for raw TypeToken as superclass
+    else if (superclass == TypeToken.class) {
+      throw new IllegalStateException("TypeToken must be created with a type argument: new TypeToken<...>() {}; "
+          + "When using code shrinkers (ProGuard, R8, ...) make sure that generic signatures are preserved.");
+    }
+
+    // User created subclass of subclass of TypeToken
+    throw new IllegalStateException("Must only create direct subclasses of TypeToken");
+  }
+
+  /**
+   * Returns the raw (non-generic) type for this type.
+   */
+  public final Class<? super T> getRawType() {
+    return rawType;
+  }
+
+  /**
+   * Gets underlying {@code Type} instance.
+   */
+  public final Type getType() {
+    return type;
+  }
+
+  /**
+   * Check if this type is assignable from the given class object.
+   *
+   * @deprecated this implementation may be inconsistent with javac for types
+   *     with wildcards.
+   */
+  @Deprecated
+  public boolean isAssignableFrom(Class<?> cls) {
+    return isAssignableFrom((Type) cls);
+  }
+
+  /**
+   * Check if this type is assignable from the given Type.
+   *
+   * @deprecated this implementation may be inconsistent with javac for types
+   *     with wildcards.
+   */
+  @Deprecated
+  public boolean isAssignableFrom(Type from) {
+    if (from == null) {
+      return false;
+    }
+
+    if (type.equals(from)) {
+      return true;
+    }
+
+    if (type instanceof Class<?>) {
+      return rawType.isAssignableFrom($Gson$Types.getRawType(from));
+    } else if (type instanceof ParameterizedType) {
+      return isAssignableFrom(from, (ParameterizedType) type,
+          new HashMap<String, Type>());
+    } else if (type instanceof GenericArrayType) {
+      return rawType.isAssignableFrom($Gson$Types.getRawType(from))
+          && isAssignableFrom(from, (GenericArrayType) type);
+    } else {
+      throw buildUnexpectedTypeError(
+          type, Class.class, ParameterizedType.class, GenericArrayType.class);
+    }
+  }
+
+  /**
+   * Check if this type is assignable from the given type token.
+   *
+   * @deprecated this implementation may be inconsistent with javac for types
+   *     with wildcards.
+   */
+  @Deprecated
+  public boolean isAssignableFrom(TypeToken<?> token) {
+    return isAssignableFrom(token.getType());
+  }
+
+  /**
+   * Private helper function that performs some assignability checks for
+   * the provided GenericArrayType.
+   */
+  private static boolean isAssignableFrom(Type from, GenericArrayType to) {
+    Type toGenericComponentType = to.getGenericComponentType();
+    if (toGenericComponentType instanceof ParameterizedType) {
+      Type t = from;
+      if (from instanceof GenericArrayType) {
+        t = ((GenericArrayType) from).getGenericComponentType();
+      } else if (from instanceof Class<?>) {
+        Class<?> classType = (Class<?>) from;
+        while (classType.isArray()) {
+          classType = classType.getComponentType();
+        }
+        t = classType;
+      }
+      return isAssignableFrom(t, (ParameterizedType) toGenericComponentType,
+          new HashMap<String, Type>());
+    }
+    // No generic defined on "to"; therefore, return true and let other
+    // checks determine assignability
+    return true;
+  }
+
+  /**
+   * Private recursive helper function to actually do the type-safe checking
+   * of assignability.
+   */
+  private static boolean isAssignableFrom(Type from, ParameterizedType to,
+      Map<String, Type> typeVarMap) {
+
+    if (from == null) {
+      return false;
+    }
+
+    if (to.equals(from)) {
+      return true;
+    }
+
+    // First figure out the class and any type information.
+    Class<?> clazz = $Gson$Types.getRawType(from);
+    ParameterizedType ptype = null;
+    if (from instanceof ParameterizedType) {
+      ptype = (ParameterizedType) from;
+    }
+
+    // Load up parameterized variable info if it was parameterized.
+    if (ptype != null) {
+      Type[] tArgs = ptype.getActualTypeArguments();
+      TypeVariable<?>[] tParams = clazz.getTypeParameters();
+      for (int i = 0; i < tArgs.length; i++) {
+        Type arg = tArgs[i];
+        TypeVariable<?> var = tParams[i];
+        while (arg instanceof TypeVariable<?>) {
+          TypeVariable<?> v = (TypeVariable<?>) arg;
+          arg = typeVarMap.get(v.getName());
+        }
+        typeVarMap.put(var.getName(), arg);
+      }
+
+      // check if they are equivalent under our current mapping.
+      if (typeEquals(ptype, to, typeVarMap)) {
+        return true;
+      }
+    }
+
+    for (Type itype : clazz.getGenericInterfaces()) {
+      if (isAssignableFrom(itype, to, new HashMap<>(typeVarMap))) {
+        return true;
+      }
+    }
+
+    // Interfaces didn't work, try the superclass.
+    Type sType = clazz.getGenericSuperclass();
+    return isAssignableFrom(sType, to, new HashMap<>(typeVarMap));
+  }
+
+  /**
+   * Checks if two parameterized types are exactly equal, under the variable
+   * replacement described in the typeVarMap.
+   */
+  private static boolean typeEquals(ParameterizedType from,
+      ParameterizedType to, Map<String, Type> typeVarMap) {
+    if (from.getRawType().equals(to.getRawType())) {
+      Type[] fromArgs = from.getActualTypeArguments();
+      Type[] toArgs = to.getActualTypeArguments();
+      for (int i = 0; i < fromArgs.length; i++) {
+        if (!matches(fromArgs[i], toArgs[i], typeVarMap)) {
+          return false;
+        }
+      }
+      return true;
+    }
+    return false;
+  }
+
+  private static AssertionError buildUnexpectedTypeError(
+      Type token, Class<?>... expected) {
+
+    // Build exception message
+    StringBuilder exceptionMessage =
+        new StringBuilder("Unexpected type. Expected one of: ");
+    for (Class<?> clazz : expected) {
+      exceptionMessage.append(clazz.getName()).append(", ");
+    }
+    exceptionMessage.append("but got: ").append(token.getClass().getName())
+        .append(", for type token: ").append(token.toString()).append('.');
+
+    return new AssertionError(exceptionMessage.toString());
+  }
+
+  /**
+   * Checks if two types are the same or are equivalent under a variable mapping
+   * given in the type map that was provided.
+   */
+  private static boolean matches(Type from, Type to, Map<String, Type> typeMap) {
+    return to.equals(from)
+        || (from instanceof TypeVariable
+        && to.equals(typeMap.get(((TypeVariable<?>) from).getName())));
+
+  }
+
+  @Override public final int hashCode() {
+    return this.hashCode;
+  }
+
+  @Override public final boolean equals(Object o) {
+    return o instanceof TypeToken<?>
+        && $Gson$Types.equals(type, ((TypeToken<?>) o).type);
+  }
+
+  @Override public final String toString() {
+    return $Gson$Types.typeToString(type);
+  }
+
+  /**
+   * Gets type literal for the given {@code Type} instance.
+   */
+  public static TypeToken<?> get(Type type) {
+    return new TypeToken<>(type);
+  }
+
+  /**
+   * Gets type literal for the given {@code Class} instance.
+   */
+  public static <T> TypeToken<T> get(Class<T> type) {
+    return new TypeToken<>(type);
+  }
+
+  /**
+   * Gets type literal for the parameterized type represented by applying {@code typeArguments} to
+   * {@code rawType}.
+   */
+  public static TypeToken<?> getParameterized(Type rawType, Type... typeArguments) {
+    return new TypeToken<>($Gson$Types.newParameterizedTypeWithOwner(null, rawType, typeArguments));
+  }
+
+  /**
+   * Gets type literal for the array type whose elements are all instances of {@code componentType}.
+   */
+  public static TypeToken<?> getArray(Type componentType) {
+    return new TypeToken<>($Gson$Types.arrayOf(componentType));
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/reflect/package-info.java b/gson/src/main/java/com/google/gson/reflect/package-info.java
new file mode 100644
index 0000000..5e43ee9
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/reflect/package-info.java
@@ -0,0 +1,6 @@
+/**
+ * This package provides utility classes for finding type information for generic types.
+ *
+ * @author Inderjeet Singh, Joel Leitch
+ */
+package com.google.gson.reflect;
\ No newline at end of file
diff --git a/gson/src/main/java/com/google/gson/stream/JsonReader.java b/gson/src/main/java/com/google/gson/stream/JsonReader.java
new file mode 100644
index 0000000..6cb820b
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/stream/JsonReader.java
@@ -0,0 +1,1656 @@
+/*
+ * Copyright (C) 2010 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.stream;
+
+import com.google.gson.internal.JsonReaderInternalAccess;
+import com.google.gson.internal.bind.JsonTreeReader;
+import java.io.Closeable;
+import java.io.EOFException;
+import java.io.IOException;
+import java.io.Reader;
+import java.util.Arrays;
+
+/**
+ * Reads a JSON (<a href="http://www.ietf.org/rfc/rfc7159.txt">RFC 7159</a>)
+ * encoded value as a stream of tokens. This stream includes both literal
+ * values (strings, numbers, booleans, and nulls) as well as the begin and
+ * end delimiters of objects and arrays. The tokens are traversed in
+ * depth-first order, the same order that they appear in the JSON document.
+ * Within JSON objects, name/value pairs are represented by a single token.
+ *
+ * <h3>Parsing JSON</h3>
+ * To create a recursive descent parser for your own JSON streams, first create
+ * an entry point method that creates a {@code JsonReader}.
+ *
+ * <p>Next, create handler methods for each structure in your JSON text. You'll
+ * need a method for each object type and for each array type.
+ * <ul>
+ *   <li>Within <strong>array handling</strong> methods, first call {@link
+ *       #beginArray} to consume the array's opening bracket. Then create a
+ *       while loop that accumulates values, terminating when {@link #hasNext}
+ *       is false. Finally, read the array's closing bracket by calling {@link
+ *       #endArray}.
+ *   <li>Within <strong>object handling</strong> methods, first call {@link
+ *       #beginObject} to consume the object's opening brace. Then create a
+ *       while loop that assigns values to local variables based on their name.
+ *       This loop should terminate when {@link #hasNext} is false. Finally,
+ *       read the object's closing brace by calling {@link #endObject}.
+ * </ul>
+ * <p>When a nested object or array is encountered, delegate to the
+ * corresponding handler method.
+ *
+ * <p>When an unknown name is encountered, strict parsers should fail with an
+ * exception. Lenient parsers should call {@link #skipValue()} to recursively
+ * skip the value's nested tokens, which may otherwise conflict.
+ *
+ * <p>If a value may be null, you should first check using {@link #peek()}.
+ * Null literals can be consumed using either {@link #nextNull()} or {@link
+ * #skipValue()}.
+ *
+ * <h3>Example</h3>
+ * Suppose we'd like to parse a stream of messages such as the following: <pre> {@code
+ * [
+ *   {
+ *     "id": 912345678901,
+ *     "text": "How do I read a JSON stream in Java?",
+ *     "geo": null,
+ *     "user": {
+ *       "name": "json_newb",
+ *       "followers_count": 41
+ *      }
+ *   },
+ *   {
+ *     "id": 912345678902,
+ *     "text": "@json_newb just use JsonReader!",
+ *     "geo": [50.454722, -104.606667],
+ *     "user": {
+ *       "name": "jesse",
+ *       "followers_count": 2
+ *     }
+ *   }
+ * ]}</pre>
+ * This code implements the parser for the above structure: <pre>   {@code
+ *
+ *   public List<Message> readJsonStream(InputStream in) throws IOException {
+ *     JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
+ *     try {
+ *       return readMessagesArray(reader);
+ *     } finally {
+ *       reader.close();
+ *     }
+ *   }
+ *
+ *   public List<Message> readMessagesArray(JsonReader reader) throws IOException {
+ *     List<Message> messages = new ArrayList<>();
+ *
+ *     reader.beginArray();
+ *     while (reader.hasNext()) {
+ *       messages.add(readMessage(reader));
+ *     }
+ *     reader.endArray();
+ *     return messages;
+ *   }
+ *
+ *   public Message readMessage(JsonReader reader) throws IOException {
+ *     long id = -1;
+ *     String text = null;
+ *     User user = null;
+ *     List<Double> geo = null;
+ *
+ *     reader.beginObject();
+ *     while (reader.hasNext()) {
+ *       String name = reader.nextName();
+ *       if (name.equals("id")) {
+ *         id = reader.nextLong();
+ *       } else if (name.equals("text")) {
+ *         text = reader.nextString();
+ *       } else if (name.equals("geo") && reader.peek() != JsonToken.NULL) {
+ *         geo = readDoublesArray(reader);
+ *       } else if (name.equals("user")) {
+ *         user = readUser(reader);
+ *       } else {
+ *         reader.skipValue();
+ *       }
+ *     }
+ *     reader.endObject();
+ *     return new Message(id, text, user, geo);
+ *   }
+ *
+ *   public List<Double> readDoublesArray(JsonReader reader) throws IOException {
+ *     List<Double> doubles = new ArrayList<>();
+ *
+ *     reader.beginArray();
+ *     while (reader.hasNext()) {
+ *       doubles.add(reader.nextDouble());
+ *     }
+ *     reader.endArray();
+ *     return doubles;
+ *   }
+ *
+ *   public User readUser(JsonReader reader) throws IOException {
+ *     String username = null;
+ *     int followersCount = -1;
+ *
+ *     reader.beginObject();
+ *     while (reader.hasNext()) {
+ *       String name = reader.nextName();
+ *       if (name.equals("name")) {
+ *         username = reader.nextString();
+ *       } else if (name.equals("followers_count")) {
+ *         followersCount = reader.nextInt();
+ *       } else {
+ *         reader.skipValue();
+ *       }
+ *     }
+ *     reader.endObject();
+ *     return new User(username, followersCount);
+ *   }}</pre>
+ *
+ * <h3>Number Handling</h3>
+ * This reader permits numeric values to be read as strings and string values to
+ * be read as numbers. For example, both elements of the JSON array {@code
+ * [1, "1"]} may be read using either {@link #nextInt} or {@link #nextString}.
+ * This behavior is intended to prevent lossy numeric conversions: double is
+ * JavaScript's only numeric type and very large values like {@code
+ * 9007199254740993} cannot be represented exactly on that platform. To minimize
+ * precision loss, extremely large values should be written and read as strings
+ * in JSON.
+ *
+ * <h3 id="nonexecuteprefix">Non-Execute Prefix</h3>
+ * Web servers that serve private data using JSON may be vulnerable to <a
+ * href="http://en.wikipedia.org/wiki/JSON#Cross-site_request_forgery">Cross-site
+ * request forgery</a> attacks. In such an attack, a malicious site gains access
+ * to a private JSON file by executing it with an HTML {@code <script>} tag.
+ *
+ * <p>Prefixing JSON files with <code>")]}'\n"</code> makes them non-executable
+ * by {@code <script>} tags, disarming the attack. Since the prefix is malformed
+ * JSON, strict parsing fails when it is encountered. This class permits the
+ * non-execute prefix when {@link #setLenient(boolean) lenient parsing} is
+ * enabled.
+ *
+ * <p>Each {@code JsonReader} may be used to read a single JSON stream. Instances
+ * of this class are not thread safe.
+ *
+ * @author Jesse Wilson
+ * @since 1.6
+ */
+public class JsonReader implements Closeable {
+  private static final long MIN_INCOMPLETE_INTEGER = Long.MIN_VALUE / 10;
+
+  private static final int PEEKED_NONE = 0;
+  private static final int PEEKED_BEGIN_OBJECT = 1;
+  private static final int PEEKED_END_OBJECT = 2;
+  private static final int PEEKED_BEGIN_ARRAY = 3;
+  private static final int PEEKED_END_ARRAY = 4;
+  private static final int PEEKED_TRUE = 5;
+  private static final int PEEKED_FALSE = 6;
+  private static final int PEEKED_NULL = 7;
+  private static final int PEEKED_SINGLE_QUOTED = 8;
+  private static final int PEEKED_DOUBLE_QUOTED = 9;
+  private static final int PEEKED_UNQUOTED = 10;
+  /** When this is returned, the string value is stored in peekedString. */
+  private static final int PEEKED_BUFFERED = 11;
+  private static final int PEEKED_SINGLE_QUOTED_NAME = 12;
+  private static final int PEEKED_DOUBLE_QUOTED_NAME = 13;
+  private static final int PEEKED_UNQUOTED_NAME = 14;
+  /** When this is returned, the integer value is stored in peekedLong. */
+  private static final int PEEKED_LONG = 15;
+  private static final int PEEKED_NUMBER = 16;
+  private static final int PEEKED_EOF = 17;
+
+  /* State machine when parsing numbers */
+  private static final int NUMBER_CHAR_NONE = 0;
+  private static final int NUMBER_CHAR_SIGN = 1;
+  private static final int NUMBER_CHAR_DIGIT = 2;
+  private static final int NUMBER_CHAR_DECIMAL = 3;
+  private static final int NUMBER_CHAR_FRACTION_DIGIT = 4;
+  private static final int NUMBER_CHAR_EXP_E = 5;
+  private static final int NUMBER_CHAR_EXP_SIGN = 6;
+  private static final int NUMBER_CHAR_EXP_DIGIT = 7;
+
+  /** The input JSON. */
+  private final Reader in;
+
+  /** True to accept non-spec compliant JSON */
+  private boolean lenient = false;
+
+  static final int BUFFER_SIZE = 1024;
+  /**
+   * Use a manual buffer to easily read and unread upcoming characters, and
+   * also so we can create strings without an intermediate StringBuilder.
+   * We decode literals directly out of this buffer, so it must be at least as
+   * long as the longest token that can be reported as a number.
+   */
+  private final char[] buffer = new char[BUFFER_SIZE];
+  private int pos = 0;
+  private int limit = 0;
+
+  private int lineNumber = 0;
+  private int lineStart = 0;
+
+  int peeked = PEEKED_NONE;
+
+  /**
+   * A peeked value that was composed entirely of digits with an optional
+   * leading dash. Positive values may not have a leading 0.
+   */
+  private long peekedLong;
+
+  /**
+   * The number of characters in a peeked number literal. Increment 'pos' by
+   * this after reading a number.
+   */
+  private int peekedNumberLength;
+
+  /**
+   * A peeked string that should be parsed on the next double, long or string.
+   * This is populated before a numeric value is parsed and used if that parsing
+   * fails.
+   */
+  private String peekedString;
+
+  /*
+   * The nesting stack. Using a manual array rather than an ArrayList saves 20%.
+   */
+  private int[] stack = new int[32];
+  private int stackSize = 0;
+  {
+    stack[stackSize++] = JsonScope.EMPTY_DOCUMENT;
+  }
+
+  /*
+   * The path members. It corresponds directly to stack: At indices where the
+   * stack contains an object (EMPTY_OBJECT, DANGLING_NAME or NONEMPTY_OBJECT),
+   * pathNames contains the name at this scope. Where it contains an array
+   * (EMPTY_ARRAY, NONEMPTY_ARRAY) pathIndices contains the current index in
+   * that array. Otherwise the value is undefined, and we take advantage of that
+   * by incrementing pathIndices when doing so isn't useful.
+   */
+  private String[] pathNames = new String[32];
+  private int[] pathIndices = new int[32];
+
+  /**
+   * Creates a new instance that reads a JSON-encoded stream from {@code in}.
+   */
+  public JsonReader(Reader in) {
+    if (in == null) {
+      throw new NullPointerException("in == null");
+    }
+    this.in = in;
+  }
+
+  /**
+   * Configure this parser to be liberal in what it accepts. By default,
+   * this parser is strict and only accepts JSON as specified by <a
+   * href="http://www.ietf.org/rfc/rfc4627.txt">RFC 4627</a>. Setting the
+   * parser to lenient causes it to ignore the following syntax errors:
+   *
+   * <ul>
+   *   <li>Streams that start with the <a href="#nonexecuteprefix">non-execute
+   *       prefix</a>, <code>")]}'\n"</code>.
+   *   <li>Streams that include multiple top-level values. With strict parsing,
+   *       each stream must contain exactly one top-level value.
+   *   <li>Numbers may be {@link Double#isNaN() NaNs} or {@link
+   *       Double#isInfinite() infinities}.
+   *   <li>End of line comments starting with {@code //} or {@code #} and
+   *       ending with a newline character.
+   *   <li>C-style comments starting with {@code /*} and ending with
+   *       {@code *}{@code /}. Such comments may not be nested.
+   *   <li>Names that are unquoted or {@code 'single quoted'}.
+   *   <li>Strings that are unquoted or {@code 'single quoted'}.
+   *   <li>Array elements separated by {@code ;} instead of {@code ,}.
+   *   <li>Unnecessary array separators. These are interpreted as if null
+   *       was the omitted value.
+   *   <li>Names and values separated by {@code =} or {@code =>} instead of
+   *       {@code :}.
+   *   <li>Name/value pairs separated by {@code ;} instead of {@code ,}.
+   * </ul>
+   *
+   * <p>Note: Even in strict mode there are slight derivations from the JSON
+   * specification:
+   * <ul>
+   *   <li>JsonReader allows the literals {@code true}, {@code false} and {@code null}
+   *       to have any capitalization, for example {@code fAlSe}
+   *   <li>JsonReader supports the escape sequence {@code \'}, representing a {@code '}
+   *   <li>JsonReader supports the escape sequence <code>\<i>LF</i></code> (with {@code LF}
+   *       being the Unicode character U+000A), resulting in a {@code LF} within the
+   *       read JSON string
+   *   <li>JsonReader allows unescaped control characters (U+0000 through U+001F)
+   * </ul>
+   */
+  public final void setLenient(boolean lenient) {
+    this.lenient = lenient;
+  }
+
+  /**
+   * Returns true if this parser is liberal in what it accepts.
+   */
+  public final boolean isLenient() {
+    return lenient;
+  }
+
+  /**
+   * Consumes the next token from the JSON stream and asserts that it is the
+   * beginning of a new array.
+   */
+  public void beginArray() throws IOException {
+    int p = peeked;
+    if (p == PEEKED_NONE) {
+      p = doPeek();
+    }
+    if (p == PEEKED_BEGIN_ARRAY) {
+      push(JsonScope.EMPTY_ARRAY);
+      pathIndices[stackSize - 1] = 0;
+      peeked = PEEKED_NONE;
+    } else {
+      throw new IllegalStateException("Expected BEGIN_ARRAY but was " + peek() + locationString());
+    }
+  }
+
+  /**
+   * Consumes the next token from the JSON stream and asserts that it is the
+   * end of the current array.
+   */
+  public void endArray() throws IOException {
+    int p = peeked;
+    if (p == PEEKED_NONE) {
+      p = doPeek();
+    }
+    if (p == PEEKED_END_ARRAY) {
+      stackSize--;
+      pathIndices[stackSize - 1]++;
+      peeked = PEEKED_NONE;
+    } else {
+      throw new IllegalStateException("Expected END_ARRAY but was " + peek() + locationString());
+    }
+  }
+
+  /**
+   * Consumes the next token from the JSON stream and asserts that it is the
+   * beginning of a new object.
+   */
+  public void beginObject() throws IOException {
+    int p = peeked;
+    if (p == PEEKED_NONE) {
+      p = doPeek();
+    }
+    if (p == PEEKED_BEGIN_OBJECT) {
+      push(JsonScope.EMPTY_OBJECT);
+      peeked = PEEKED_NONE;
+    } else {
+      throw new IllegalStateException("Expected BEGIN_OBJECT but was " + peek() + locationString());
+    }
+  }
+
+  /**
+   * Consumes the next token from the JSON stream and asserts that it is the
+   * end of the current object.
+   */
+  public void endObject() throws IOException {
+    int p = peeked;
+    if (p == PEEKED_NONE) {
+      p = doPeek();
+    }
+    if (p == PEEKED_END_OBJECT) {
+      stackSize--;
+      pathNames[stackSize] = null; // Free the last path name so that it can be garbage collected!
+      pathIndices[stackSize - 1]++;
+      peeked = PEEKED_NONE;
+    } else {
+      throw new IllegalStateException("Expected END_OBJECT but was " + peek() + locationString());
+    }
+  }
+
+  /**
+   * Returns true if the current array or object has another element.
+   */
+  public boolean hasNext() throws IOException {
+    int p = peeked;
+    if (p == PEEKED_NONE) {
+      p = doPeek();
+    }
+    return p != PEEKED_END_OBJECT && p != PEEKED_END_ARRAY && p != PEEKED_EOF;
+  }
+
+  /**
+   * Returns the type of the next token without consuming it.
+   */
+  public JsonToken peek() throws IOException {
+    int p = peeked;
+    if (p == PEEKED_NONE) {
+      p = doPeek();
+    }
+
+    switch (p) {
+    case PEEKED_BEGIN_OBJECT:
+      return JsonToken.BEGIN_OBJECT;
+    case PEEKED_END_OBJECT:
+      return JsonToken.END_OBJECT;
+    case PEEKED_BEGIN_ARRAY:
+      return JsonToken.BEGIN_ARRAY;
+    case PEEKED_END_ARRAY:
+      return JsonToken.END_ARRAY;
+    case PEEKED_SINGLE_QUOTED_NAME:
+    case PEEKED_DOUBLE_QUOTED_NAME:
+    case PEEKED_UNQUOTED_NAME:
+      return JsonToken.NAME;
+    case PEEKED_TRUE:
+    case PEEKED_FALSE:
+      return JsonToken.BOOLEAN;
+    case PEEKED_NULL:
+      return JsonToken.NULL;
+    case PEEKED_SINGLE_QUOTED:
+    case PEEKED_DOUBLE_QUOTED:
+    case PEEKED_UNQUOTED:
+    case PEEKED_BUFFERED:
+      return JsonToken.STRING;
+    case PEEKED_LONG:
+    case PEEKED_NUMBER:
+      return JsonToken.NUMBER;
+    case PEEKED_EOF:
+      return JsonToken.END_DOCUMENT;
+    default:
+      throw new AssertionError();
+    }
+  }
+
+  int doPeek() throws IOException {
+    int peekStack = stack[stackSize - 1];
+    if (peekStack == JsonScope.EMPTY_ARRAY) {
+      stack[stackSize - 1] = JsonScope.NONEMPTY_ARRAY;
+    } else if (peekStack == JsonScope.NONEMPTY_ARRAY) {
+      // Look for a comma before the next element.
+      int c = nextNonWhitespace(true);
+      switch (c) {
+      case ']':
+        return peeked = PEEKED_END_ARRAY;
+      case ';':
+        checkLenient(); // fall-through
+      case ',':
+        break;
+      default:
+        throw syntaxError("Unterminated array");
+      }
+    } else if (peekStack == JsonScope.EMPTY_OBJECT || peekStack == JsonScope.NONEMPTY_OBJECT) {
+      stack[stackSize - 1] = JsonScope.DANGLING_NAME;
+      // Look for a comma before the next element.
+      if (peekStack == JsonScope.NONEMPTY_OBJECT) {
+        int c = nextNonWhitespace(true);
+        switch (c) {
+        case '}':
+          return peeked = PEEKED_END_OBJECT;
+        case ';':
+          checkLenient(); // fall-through
+        case ',':
+          break;
+        default:
+          throw syntaxError("Unterminated object");
+        }
+      }
+      int c = nextNonWhitespace(true);
+      switch (c) {
+      case '"':
+        return peeked = PEEKED_DOUBLE_QUOTED_NAME;
+      case '\'':
+        checkLenient();
+        return peeked = PEEKED_SINGLE_QUOTED_NAME;
+      case '}':
+        if (peekStack != JsonScope.NONEMPTY_OBJECT) {
+          return peeked = PEEKED_END_OBJECT;
+        } else {
+          throw syntaxError("Expected name");
+        }
+      default:
+        checkLenient();
+        pos--; // Don't consume the first character in an unquoted string.
+        if (isLiteral((char) c)) {
+          return peeked = PEEKED_UNQUOTED_NAME;
+        } else {
+          throw syntaxError("Expected name");
+        }
+      }
+    } else if (peekStack == JsonScope.DANGLING_NAME) {
+      stack[stackSize - 1] = JsonScope.NONEMPTY_OBJECT;
+      // Look for a colon before the value.
+      int c = nextNonWhitespace(true);
+      switch (c) {
+      case ':':
+        break;
+      case '=':
+        checkLenient();
+        if ((pos < limit || fillBuffer(1)) && buffer[pos] == '>') {
+          pos++;
+        }
+        break;
+      default:
+        throw syntaxError("Expected ':'");
+      }
+    } else if (peekStack == JsonScope.EMPTY_DOCUMENT) {
+      if (lenient) {
+        consumeNonExecutePrefix();
+      }
+      stack[stackSize - 1] = JsonScope.NONEMPTY_DOCUMENT;
+    } else if (peekStack == JsonScope.NONEMPTY_DOCUMENT) {
+      int c = nextNonWhitespace(false);
+      if (c == -1) {
+        return peeked = PEEKED_EOF;
+      } else {
+        checkLenient();
+        pos--;
+      }
+    } else if (peekStack == JsonScope.CLOSED) {
+      throw new IllegalStateException("JsonReader is closed");
+    }
+
+    int c = nextNonWhitespace(true);
+    switch (c) {
+    case ']':
+      if (peekStack == JsonScope.EMPTY_ARRAY) {
+        return peeked = PEEKED_END_ARRAY;
+      }
+      // fall-through to handle ",]"
+    case ';':
+    case ',':
+      // In lenient mode, a 0-length literal in an array means 'null'.
+      if (peekStack == JsonScope.EMPTY_ARRAY || peekStack == JsonScope.NONEMPTY_ARRAY) {
+        checkLenient();
+        pos--;
+        return peeked = PEEKED_NULL;
+      } else {
+        throw syntaxError("Unexpected value");
+      }
+    case '\'':
+      checkLenient();
+      return peeked = PEEKED_SINGLE_QUOTED;
+    case '"':
+      return peeked = PEEKED_DOUBLE_QUOTED;
+    case '[':
+      return peeked = PEEKED_BEGIN_ARRAY;
+    case '{':
+      return peeked = PEEKED_BEGIN_OBJECT;
+    default:
+      pos--; // Don't consume the first character in a literal value.
+    }
+
+    int result = peekKeyword();
+    if (result != PEEKED_NONE) {
+      return result;
+    }
+
+    result = peekNumber();
+    if (result != PEEKED_NONE) {
+      return result;
+    }
+
+    if (!isLiteral(buffer[pos])) {
+      throw syntaxError("Expected value");
+    }
+
+    checkLenient();
+    return peeked = PEEKED_UNQUOTED;
+  }
+
+  private int peekKeyword() throws IOException {
+    // Figure out which keyword we're matching against by its first character.
+    char c = buffer[pos];
+    String keyword;
+    String keywordUpper;
+    int peeking;
+    if (c == 't' || c == 'T') {
+      keyword = "true";
+      keywordUpper = "TRUE";
+      peeking = PEEKED_TRUE;
+    } else if (c == 'f' || c == 'F') {
+      keyword = "false";
+      keywordUpper = "FALSE";
+      peeking = PEEKED_FALSE;
+    } else if (c == 'n' || c == 'N') {
+      keyword = "null";
+      keywordUpper = "NULL";
+      peeking = PEEKED_NULL;
+    } else {
+      return PEEKED_NONE;
+    }
+
+    // Confirm that chars [1..length) match the keyword.
+    int length = keyword.length();
+    for (int i = 1; i < length; i++) {
+      if (pos + i >= limit && !fillBuffer(i + 1)) {
+        return PEEKED_NONE;
+      }
+      c = buffer[pos + i];
+      if (c != keyword.charAt(i) && c != keywordUpper.charAt(i)) {
+        return PEEKED_NONE;
+      }
+    }
+
+    if ((pos + length < limit || fillBuffer(length + 1))
+        && isLiteral(buffer[pos + length])) {
+      return PEEKED_NONE; // Don't match trues, falsey or nullsoft!
+    }
+
+    // We've found the keyword followed either by EOF or by a non-literal character.
+    pos += length;
+    return peeked = peeking;
+  }
+
+  private int peekNumber() throws IOException {
+    // Like nextNonWhitespace, this uses locals 'p' and 'l' to save inner-loop field access.
+    char[] buffer = this.buffer;
+    int p = pos;
+    int l = limit;
+
+    long value = 0; // Negative to accommodate Long.MIN_VALUE more easily.
+    boolean negative = false;
+    boolean fitsInLong = true;
+    int last = NUMBER_CHAR_NONE;
+
+    int i = 0;
+
+    charactersOfNumber:
+    for (; true; i++) {
+      if (p + i == l) {
+        if (i == buffer.length) {
+          // Though this looks like a well-formed number, it's too long to continue reading. Give up
+          // and let the application handle this as an unquoted literal.
+          return PEEKED_NONE;
+        }
+        if (!fillBuffer(i + 1)) {
+          break;
+        }
+        p = pos;
+        l = limit;
+      }
+
+      char c = buffer[p + i];
+      switch (c) {
+      case '-':
+        if (last == NUMBER_CHAR_NONE) {
+          negative = true;
+          last = NUMBER_CHAR_SIGN;
+          continue;
+        } else if (last == NUMBER_CHAR_EXP_E) {
+          last = NUMBER_CHAR_EXP_SIGN;
+          continue;
+        }
+        return PEEKED_NONE;
+
+      case '+':
+        if (last == NUMBER_CHAR_EXP_E) {
+          last = NUMBER_CHAR_EXP_SIGN;
+          continue;
+        }
+        return PEEKED_NONE;
+
+      case 'e':
+      case 'E':
+        if (last == NUMBER_CHAR_DIGIT || last == NUMBER_CHAR_FRACTION_DIGIT) {
+          last = NUMBER_CHAR_EXP_E;
+          continue;
+        }
+        return PEEKED_NONE;
+
+      case '.':
+        if (last == NUMBER_CHAR_DIGIT) {
+          last = NUMBER_CHAR_DECIMAL;
+          continue;
+        }
+        return PEEKED_NONE;
+
+      default:
+        if (c < '0' || c > '9') {
+          if (!isLiteral(c)) {
+            break charactersOfNumber;
+          }
+          return PEEKED_NONE;
+        }
+        if (last == NUMBER_CHAR_SIGN || last == NUMBER_CHAR_NONE) {
+          value = -(c - '0');
+          last = NUMBER_CHAR_DIGIT;
+        } else if (last == NUMBER_CHAR_DIGIT) {
+          if (value == 0) {
+            return PEEKED_NONE; // Leading '0' prefix is not allowed (since it could be octal).
+          }
+          long newValue = value * 10 - (c - '0');
+          fitsInLong &= value > MIN_INCOMPLETE_INTEGER
+              || (value == MIN_INCOMPLETE_INTEGER && newValue < value);
+          value = newValue;
+        } else if (last == NUMBER_CHAR_DECIMAL) {
+          last = NUMBER_CHAR_FRACTION_DIGIT;
+        } else if (last == NUMBER_CHAR_EXP_E || last == NUMBER_CHAR_EXP_SIGN) {
+          last = NUMBER_CHAR_EXP_DIGIT;
+        }
+      }
+    }
+
+    // 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)) {
+      peekedLong = negative ? value : -value;
+      pos += i;
+      return peeked = PEEKED_LONG;
+    } else if (last == NUMBER_CHAR_DIGIT || last == NUMBER_CHAR_FRACTION_DIGIT
+        || last == NUMBER_CHAR_EXP_DIGIT) {
+      peekedNumberLength = i;
+      return peeked = PEEKED_NUMBER;
+    } else {
+      return PEEKED_NONE;
+    }
+  }
+
+  private boolean isLiteral(char c) throws IOException {
+    switch (c) {
+    case '/':
+    case '\\':
+    case ';':
+    case '#':
+    case '=':
+      checkLenient(); // fall-through
+    case '{':
+    case '}':
+    case '[':
+    case ']':
+    case ':':
+    case ',':
+    case ' ':
+    case '\t':
+    case '\f':
+    case '\r':
+    case '\n':
+      return false;
+    default:
+      return true;
+    }
+  }
+
+  /**
+   * Returns the next token, a {@link com.google.gson.stream.JsonToken#NAME property name}, and
+   * consumes it.
+   *
+   * @throws java.io.IOException if the next token in the stream is not a property
+   *     name.
+   */
+  public String nextName() throws IOException {
+    int p = peeked;
+    if (p == PEEKED_NONE) {
+      p = doPeek();
+    }
+    String result;
+    if (p == PEEKED_UNQUOTED_NAME) {
+      result = nextUnquotedValue();
+    } else if (p == PEEKED_SINGLE_QUOTED_NAME) {
+      result = nextQuotedValue('\'');
+    } else if (p == PEEKED_DOUBLE_QUOTED_NAME) {
+      result = nextQuotedValue('"');
+    } else {
+      throw new IllegalStateException("Expected a name but was " + peek() + locationString());
+    }
+    peeked = PEEKED_NONE;
+    pathNames[stackSize - 1] = result;
+    return result;
+  }
+
+  /**
+   * Returns the {@link com.google.gson.stream.JsonToken#STRING string} value of the next token,
+   * consuming it. If the next token is a number, this method will return its
+   * string form.
+   *
+   * @throws IllegalStateException if the next token is not a string or if
+   *     this reader is closed.
+   */
+  public String nextString() throws IOException {
+    int p = peeked;
+    if (p == PEEKED_NONE) {
+      p = doPeek();
+    }
+    String result;
+    if (p == PEEKED_UNQUOTED) {
+      result = nextUnquotedValue();
+    } else if (p == PEEKED_SINGLE_QUOTED) {
+      result = nextQuotedValue('\'');
+    } else if (p == PEEKED_DOUBLE_QUOTED) {
+      result = nextQuotedValue('"');
+    } else if (p == PEEKED_BUFFERED) {
+      result = peekedString;
+      peekedString = null;
+    } else if (p == PEEKED_LONG) {
+      result = Long.toString(peekedLong);
+    } else if (p == PEEKED_NUMBER) {
+      result = new String(buffer, pos, peekedNumberLength);
+      pos += peekedNumberLength;
+    } else {
+      throw new IllegalStateException("Expected a string but was " + peek() + locationString());
+    }
+    peeked = PEEKED_NONE;
+    pathIndices[stackSize - 1]++;
+    return result;
+  }
+
+  /**
+   * Returns the {@link com.google.gson.stream.JsonToken#BOOLEAN boolean} value of the next token,
+   * consuming it.
+   *
+   * @throws IllegalStateException if the next token is not a boolean or if
+   *     this reader is closed.
+   */
+  public boolean nextBoolean() throws IOException {
+    int p = peeked;
+    if (p == PEEKED_NONE) {
+      p = doPeek();
+    }
+    if (p == PEEKED_TRUE) {
+      peeked = PEEKED_NONE;
+      pathIndices[stackSize - 1]++;
+      return true;
+    } else if (p == PEEKED_FALSE) {
+      peeked = PEEKED_NONE;
+      pathIndices[stackSize - 1]++;
+      return false;
+    }
+    throw new IllegalStateException("Expected a boolean but was " + peek() + locationString());
+  }
+
+  /**
+   * Consumes the next token from the JSON stream and asserts that it is a
+   * literal null.
+   *
+   * @throws IllegalStateException if the next token is not null or if this
+   *     reader is closed.
+   */
+  public void nextNull() throws IOException {
+    int p = peeked;
+    if (p == PEEKED_NONE) {
+      p = doPeek();
+    }
+    if (p == PEEKED_NULL) {
+      peeked = PEEKED_NONE;
+      pathIndices[stackSize - 1]++;
+    } else {
+      throw new IllegalStateException("Expected null but was " + peek() + locationString());
+    }
+  }
+
+  /**
+   * Returns the {@link com.google.gson.stream.JsonToken#NUMBER double} value of the next token,
+   * consuming it. If the next token is a string, this method will attempt to
+   * parse it as a double using {@link Double#parseDouble(String)}.
+   *
+   * @throws IllegalStateException if the next token is not a literal value.
+   * @throws NumberFormatException if the next literal value cannot be parsed
+   *     as a double, or is non-finite.
+   */
+  public double nextDouble() throws IOException {
+    int p = peeked;
+    if (p == PEEKED_NONE) {
+      p = doPeek();
+    }
+
+    if (p == PEEKED_LONG) {
+      peeked = PEEKED_NONE;
+      pathIndices[stackSize - 1]++;
+      return (double) peekedLong;
+    }
+
+    if (p == PEEKED_NUMBER) {
+      peekedString = new String(buffer, pos, peekedNumberLength);
+      pos += peekedNumberLength;
+    } else if (p == PEEKED_SINGLE_QUOTED || p == PEEKED_DOUBLE_QUOTED) {
+      peekedString = nextQuotedValue(p == PEEKED_SINGLE_QUOTED ? '\'' : '"');
+    } else if (p == PEEKED_UNQUOTED) {
+      peekedString = nextUnquotedValue();
+    } else if (p != PEEKED_BUFFERED) {
+      throw new IllegalStateException("Expected a double but was " + peek() + locationString());
+    }
+
+    peeked = PEEKED_BUFFERED;
+    double result = Double.parseDouble(peekedString); // don't catch this NumberFormatException.
+    if (!lenient && (Double.isNaN(result) || Double.isInfinite(result))) {
+      throw new MalformedJsonException(
+          "JSON forbids NaN and infinities: " + result + locationString());
+    }
+    peekedString = null;
+    peeked = PEEKED_NONE;
+    pathIndices[stackSize - 1]++;
+    return result;
+  }
+
+  /**
+   * Returns the {@link com.google.gson.stream.JsonToken#NUMBER long} value of the next token,
+   * consuming it. If the next token is a string, this method will attempt to
+   * parse it as a long. If the next token's numeric value cannot be exactly
+   * represented by a Java {@code long}, this method throws.
+   *
+   * @throws IllegalStateException if the next token is not a literal value.
+   * @throws NumberFormatException if the next literal value cannot be parsed
+   *     as a number, or exactly represented as a long.
+   */
+  public long nextLong() throws IOException {
+    int p = peeked;
+    if (p == PEEKED_NONE) {
+      p = doPeek();
+    }
+
+    if (p == PEEKED_LONG) {
+      peeked = PEEKED_NONE;
+      pathIndices[stackSize - 1]++;
+      return peekedLong;
+    }
+
+    if (p == PEEKED_NUMBER) {
+      peekedString = new String(buffer, pos, peekedNumberLength);
+      pos += peekedNumberLength;
+    } else if (p == PEEKED_SINGLE_QUOTED || p == PEEKED_DOUBLE_QUOTED || p == PEEKED_UNQUOTED) {
+      if (p == PEEKED_UNQUOTED) {
+        peekedString = nextUnquotedValue();
+      } else {
+        peekedString = nextQuotedValue(p == PEEKED_SINGLE_QUOTED ? '\'' : '"');
+      }
+      try {
+        long result = Long.parseLong(peekedString);
+        peeked = PEEKED_NONE;
+        pathIndices[stackSize - 1]++;
+        return result;
+      } catch (NumberFormatException ignored) {
+        // Fall back to parse as a double below.
+      }
+    } else {
+      throw new IllegalStateException("Expected a long but was " + peek() + locationString());
+    }
+
+    peeked = PEEKED_BUFFERED;
+    double asDouble = Double.parseDouble(peekedString); // don't catch this NumberFormatException.
+    long result = (long) asDouble;
+    if (result != asDouble) { // Make sure no precision was lost casting to 'long'.
+      throw new NumberFormatException("Expected a long but was " + peekedString + locationString());
+    }
+    peekedString = null;
+    peeked = PEEKED_NONE;
+    pathIndices[stackSize - 1]++;
+    return result;
+  }
+
+  /**
+   * Returns the string up to but not including {@code quote}, unescaping any
+   * character escape sequences encountered along the way. The opening quote
+   * should have already been read. This consumes the closing quote, but does
+   * not include it in the returned string.
+   *
+   * @param quote either ' or ".
+   * @throws NumberFormatException if any unicode escape sequences are
+   *     malformed.
+   */
+  private String nextQuotedValue(char quote) throws IOException {
+    // Like nextNonWhitespace, this uses locals 'p' and 'l' to save inner-loop field access.
+    char[] buffer = this.buffer;
+    StringBuilder builder = null;
+    while (true) {
+      int p = pos;
+      int l = limit;
+      /* the index of the first character not yet appended to the builder. */
+      int start = p;
+      while (p < l) {
+        int c = buffer[p++];
+
+        if (c == quote) {
+          pos = p;
+          int len = p - start - 1;
+          if (builder == null) {
+            return new String(buffer, start, len);
+          } else {
+            builder.append(buffer, start, len);
+            return builder.toString();
+          }
+        } else if (c == '\\') {
+          pos = p;
+          int len = p - start - 1;
+          if (builder == null) {
+            int estimatedLength = (len + 1) * 2;
+            builder = new StringBuilder(Math.max(estimatedLength, 16));
+          }
+          builder.append(buffer, start, len);
+          builder.append(readEscapeCharacter());
+          p = pos;
+          l = limit;
+          start = p;
+        } else if (c == '\n') {
+          lineNumber++;
+          lineStart = p;
+        }
+      }
+
+      if (builder == null) {
+        int estimatedLength = (p - start) * 2;
+        builder = new StringBuilder(Math.max(estimatedLength, 16));
+      }
+      builder.append(buffer, start, p - start);
+      pos = p;
+      if (!fillBuffer(1)) {
+        throw syntaxError("Unterminated string");
+      }
+    }
+  }
+
+  /**
+   * Returns an unquoted value as a string.
+   */
+  @SuppressWarnings("fallthrough")
+  private String nextUnquotedValue() throws IOException {
+    StringBuilder builder = null;
+    int i = 0;
+
+    findNonLiteralCharacter:
+    while (true) {
+      for (; pos + i < limit; i++) {
+        switch (buffer[pos + i]) {
+        case '/':
+        case '\\':
+        case ';':
+        case '#':
+        case '=':
+          checkLenient(); // fall-through
+        case '{':
+        case '}':
+        case '[':
+        case ']':
+        case ':':
+        case ',':
+        case ' ':
+        case '\t':
+        case '\f':
+        case '\r':
+        case '\n':
+          break findNonLiteralCharacter;
+        }
+      }
+
+      // Attempt to load the entire literal into the buffer at once.
+      if (i < buffer.length) {
+        if (fillBuffer(i + 1)) {
+          continue;
+        } else {
+          break;
+        }
+      }
+
+      // use a StringBuilder when the value is too long. This is too long to be a number!
+      if (builder == null) {
+        builder = new StringBuilder(Math.max(i,16));
+      }
+      builder.append(buffer, pos, i);
+      pos += i;
+      i = 0;
+      if (!fillBuffer(1)) {
+        break;
+      }
+    }
+
+    String result = (null == builder) ? new String(buffer, pos, i) : builder.append(buffer, pos, i).toString();
+    pos += i;
+    return result;
+  }
+
+  private void skipQuotedValue(char quote) throws IOException {
+    // Like nextNonWhitespace, this uses locals 'p' and 'l' to save inner-loop field access.
+    char[] buffer = this.buffer;
+    do {
+      int p = pos;
+      int l = limit;
+      /* the index of the first character not yet appended to the builder. */
+      while (p < l) {
+        int c = buffer[p++];
+        if (c == quote) {
+          pos = p;
+          return;
+        } else if (c == '\\') {
+          pos = p;
+          readEscapeCharacter();
+          p = pos;
+          l = limit;
+        } else if (c == '\n') {
+          lineNumber++;
+          lineStart = p;
+        }
+      }
+      pos = p;
+    } while (fillBuffer(1));
+    throw syntaxError("Unterminated string");
+  }
+
+  private void skipUnquotedValue() throws IOException {
+    do {
+      int i = 0;
+      for (; pos + i < limit; i++) {
+        switch (buffer[pos + i]) {
+        case '/':
+        case '\\':
+        case ';':
+        case '#':
+        case '=':
+          checkLenient(); // fall-through
+        case '{':
+        case '}':
+        case '[':
+        case ']':
+        case ':':
+        case ',':
+        case ' ':
+        case '\t':
+        case '\f':
+        case '\r':
+        case '\n':
+          pos += i;
+          return;
+        }
+      }
+      pos += i;
+    } while (fillBuffer(1));
+  }
+
+  /**
+   * Returns the {@link com.google.gson.stream.JsonToken#NUMBER int} value of the next token,
+   * consuming it. If the next token is a string, this method will attempt to
+   * parse it as an int. If the next token's numeric value cannot be exactly
+   * represented by a Java {@code int}, this method throws.
+   *
+   * @throws IllegalStateException if the next token is not a literal value.
+   * @throws NumberFormatException if the next literal value cannot be parsed
+   *     as a number, or exactly represented as an int.
+   */
+  public int nextInt() throws IOException {
+    int p = peeked;
+    if (p == PEEKED_NONE) {
+      p = doPeek();
+    }
+
+    int result;
+    if (p == PEEKED_LONG) {
+      result = (int) peekedLong;
+      if (peekedLong != result) { // Make sure no precision was lost casting to 'int'.
+        throw new NumberFormatException("Expected an int but was " + peekedLong + locationString());
+      }
+      peeked = PEEKED_NONE;
+      pathIndices[stackSize - 1]++;
+      return result;
+    }
+
+    if (p == PEEKED_NUMBER) {
+      peekedString = new String(buffer, pos, peekedNumberLength);
+      pos += peekedNumberLength;
+    } else if (p == PEEKED_SINGLE_QUOTED || p == PEEKED_DOUBLE_QUOTED || p == PEEKED_UNQUOTED) {
+      if (p == PEEKED_UNQUOTED) {
+        peekedString = nextUnquotedValue();
+      } else {
+        peekedString = nextQuotedValue(p == PEEKED_SINGLE_QUOTED ? '\'' : '"');
+      }
+      try {
+        result = Integer.parseInt(peekedString);
+        peeked = PEEKED_NONE;
+        pathIndices[stackSize - 1]++;
+        return result;
+      } catch (NumberFormatException ignored) {
+        // Fall back to parse as a double below.
+      }
+    } else {
+      throw new IllegalStateException("Expected an int but was " + peek() + locationString());
+    }
+
+    peeked = PEEKED_BUFFERED;
+    double asDouble = Double.parseDouble(peekedString); // don't catch this NumberFormatException.
+    result = (int) asDouble;
+    if (result != asDouble) { // Make sure no precision was lost casting to 'int'.
+      throw new NumberFormatException("Expected an int but was " + peekedString + locationString());
+    }
+    peekedString = null;
+    peeked = PEEKED_NONE;
+    pathIndices[stackSize - 1]++;
+    return result;
+  }
+
+  /**
+   * Closes this JSON reader and the underlying {@link java.io.Reader}.
+   */
+  @Override public void close() throws IOException {
+    peeked = PEEKED_NONE;
+    stack[0] = JsonScope.CLOSED;
+    stackSize = 1;
+    in.close();
+  }
+
+  /**
+   * Skips the next value recursively. If it is an object or array, all nested
+   * elements are skipped. This method is intended for use when the JSON token
+   * stream contains unrecognized or unhandled values.
+   */
+  public void skipValue() throws IOException {
+    int count = 0;
+    do {
+      int p = peeked;
+      if (p == PEEKED_NONE) {
+        p = doPeek();
+      }
+
+      if (p == PEEKED_BEGIN_ARRAY) {
+        push(JsonScope.EMPTY_ARRAY);
+        count++;
+      } else if (p == PEEKED_BEGIN_OBJECT) {
+        push(JsonScope.EMPTY_OBJECT);
+        count++;
+      } else if (p == PEEKED_END_ARRAY) {
+        stackSize--;
+        count--;
+      } else if (p == PEEKED_END_OBJECT) {
+        stackSize--;
+        count--;
+      } else if (p == PEEKED_UNQUOTED_NAME || p == PEEKED_UNQUOTED) {
+        skipUnquotedValue();
+      } else if (p == PEEKED_SINGLE_QUOTED || p == PEEKED_SINGLE_QUOTED_NAME) {
+        skipQuotedValue('\'');
+      } else if (p == PEEKED_DOUBLE_QUOTED || p == PEEKED_DOUBLE_QUOTED_NAME) {
+        skipQuotedValue('"');
+      } else if (p == PEEKED_NUMBER) {
+        pos += peekedNumberLength;
+      }
+      peeked = PEEKED_NONE;
+    } while (count != 0);
+
+    pathIndices[stackSize - 1]++;
+    pathNames[stackSize - 1] = "null";
+  }
+
+  private void push(int newTop) {
+    if (stackSize == stack.length) {
+      int newLength = stackSize * 2;
+      stack = Arrays.copyOf(stack, newLength);
+      pathIndices = Arrays.copyOf(pathIndices, newLength);
+      pathNames = Arrays.copyOf(pathNames, newLength);
+    }
+    stack[stackSize++] = newTop;
+  }
+
+  /**
+   * Returns true once {@code limit - pos >= minimum}. If the data is
+   * exhausted before that many characters are available, this returns
+   * false.
+   */
+  private boolean fillBuffer(int minimum) throws IOException {
+    char[] buffer = this.buffer;
+    lineStart -= pos;
+    if (limit != pos) {
+      limit -= pos;
+      System.arraycopy(buffer, pos, buffer, 0, limit);
+    } else {
+      limit = 0;
+    }
+
+    pos = 0;
+    int total;
+    while ((total = in.read(buffer, limit, buffer.length - limit)) != -1) {
+      limit += total;
+
+      // if this is the first read, consume an optional byte order mark (BOM) if it exists
+      if (lineNumber == 0 && lineStart == 0 && limit > 0 && buffer[0] == '\ufeff') {
+        pos++;
+        lineStart++;
+        minimum++;
+      }
+
+      if (limit >= minimum) {
+        return true;
+      }
+    }
+    return false;
+  }
+
+  /**
+   * Returns the next character in the stream that is neither whitespace nor a
+   * part of a comment. When this returns, the returned character is always at
+   * {@code buffer[pos-1]}; this means the caller can always push back the
+   * returned character by decrementing {@code pos}.
+   */
+  private int nextNonWhitespace(boolean throwOnEof) throws IOException {
+    /*
+     * This code uses ugly local variables 'p' and 'l' representing the 'pos'
+     * and 'limit' fields respectively. Using locals rather than fields saves
+     * a few field reads for each whitespace character in a pretty-printed
+     * document, resulting in a 5% speedup. We need to flush 'p' to its field
+     * before any (potentially indirect) call to fillBuffer() and reread both
+     * 'p' and 'l' after any (potentially indirect) call to the same method.
+     */
+    char[] buffer = this.buffer;
+    int p = pos;
+    int l = limit;
+    while (true) {
+      if (p == l) {
+        pos = p;
+        if (!fillBuffer(1)) {
+          break;
+        }
+        p = pos;
+        l = limit;
+      }
+
+      int c = buffer[p++];
+      if (c == '\n') {
+        lineNumber++;
+        lineStart = p;
+        continue;
+      } else if (c == ' ' || c == '\r' || c == '\t') {
+        continue;
+      }
+
+      if (c == '/') {
+        pos = p;
+        if (p == l) {
+          pos--; // push back '/' so it's still in the buffer when this method returns
+          boolean charsLoaded = fillBuffer(2);
+          pos++; // consume the '/' again
+          if (!charsLoaded) {
+            return c;
+          }
+        }
+
+        checkLenient();
+        char peek = buffer[pos];
+        switch (peek) {
+        case '*':
+          // skip a /* c-style comment */
+          pos++;
+          if (!skipTo("*/")) {
+            throw syntaxError("Unterminated comment");
+          }
+          p = pos + 2;
+          l = limit;
+          continue;
+
+        case '/':
+          // skip a // end-of-line comment
+          pos++;
+          skipToEndOfLine();
+          p = pos;
+          l = limit;
+          continue;
+
+        default:
+          return c;
+        }
+      } else if (c == '#') {
+        pos = p;
+        /*
+         * Skip a # hash end-of-line comment. The JSON RFC doesn't
+         * specify this behaviour, but it's required to parse
+         * existing documents. See http://b/2571423.
+         */
+        checkLenient();
+        skipToEndOfLine();
+        p = pos;
+        l = limit;
+      } else {
+        pos = p;
+        return c;
+      }
+    }
+    if (throwOnEof) {
+      throw new EOFException("End of input" + locationString());
+    } else {
+      return -1;
+    }
+  }
+
+  private void checkLenient() throws IOException {
+    if (!lenient) {
+      throw syntaxError("Use JsonReader.setLenient(true) to accept malformed JSON");
+    }
+  }
+
+  /**
+   * Advances the position until after the next newline character. If the line
+   * is terminated by "\r\n", the '\n' must be consumed as whitespace by the
+   * caller.
+   */
+  private void skipToEndOfLine() throws IOException {
+    while (pos < limit || fillBuffer(1)) {
+      char c = buffer[pos++];
+      if (c == '\n') {
+        lineNumber++;
+        lineStart = pos;
+        break;
+      } else if (c == '\r') {
+        break;
+      }
+    }
+  }
+
+  /**
+   * @param toFind a string to search for. Must not contain a newline.
+   */
+  private boolean skipTo(String toFind) throws IOException {
+    int length = toFind.length();
+    outer:
+    for (; pos + length <= limit || fillBuffer(length); pos++) {
+      if (buffer[pos] == '\n') {
+        lineNumber++;
+        lineStart = pos + 1;
+        continue;
+      }
+      for (int c = 0; c < length; c++) {
+        if (buffer[pos + c] != toFind.charAt(c)) {
+          continue outer;
+        }
+      }
+      return true;
+    }
+    return false;
+  }
+
+  @Override public String toString() {
+    return getClass().getSimpleName() + locationString();
+  }
+
+  String locationString() {
+    int line = lineNumber + 1;
+    int column = pos - lineStart + 1;
+    return " at line " + line + " column " + column + " path " + getPath();
+  }
+
+  private String getPath(boolean usePreviousPath) {
+    StringBuilder result = new StringBuilder().append('$');
+    for (int i = 0; i < stackSize; i++) {
+      switch (stack[i]) {
+        case JsonScope.EMPTY_ARRAY:
+        case JsonScope.NONEMPTY_ARRAY:
+          int pathIndex = pathIndices[i];
+          // If index is last path element it points to next array element; have to decrement
+          if (usePreviousPath && pathIndex > 0 && i == stackSize - 1) {
+            pathIndex--;
+          }
+          result.append('[').append(pathIndex).append(']');
+          break;
+        case JsonScope.EMPTY_OBJECT:
+        case JsonScope.DANGLING_NAME:
+        case JsonScope.NONEMPTY_OBJECT:
+          result.append('.');
+          if (pathNames[i] != null) {
+            result.append(pathNames[i]);
+          }
+          break;
+        case JsonScope.NONEMPTY_DOCUMENT:
+        case JsonScope.EMPTY_DOCUMENT:
+        case JsonScope.CLOSED:
+          break;
+      }
+    }
+    return result.toString();
+  }
+
+  /**
+   * 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:
+   * <ul>
+   *   <li>For JSON arrays the path points to the index of the previous element.<br>
+   *   If no element has been consumed yet it uses the index 0 (even if there are no elements).</li>
+   *   <li>For JSON objects the path points to the last property, or to the current
+   *   property if its value has not been consumed yet.</li>
+   * </ul>
+   *
+   * <p>This method can be useful to add additional context to exception messages
+   * <i>after</i> a value has been consumed.
+   */
+  public String getPreviousPath() {
+    return getPath(true);
+  }
+
+  /**
+   * 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:
+   * <ul>
+   *   <li>For JSON arrays the path points to the index of the next element (even
+   *   if there are no further elements).</li>
+   *   <li>For JSON objects the path points to the last property, or to the current
+   *   property if its value has not been consumed yet.</li>
+   * </ul>
+   *
+   * <p>This method can be useful to add additional context to exception messages
+   * <i>before</i> a value is consumed, for example when the {@linkplain #peek() peeked}
+   * token is unexpected.
+   */
+  public String getPath() {
+    return getPath(false);
+  }
+
+  /**
+   * Unescapes the character identified by the character or characters that
+   * immediately follow a backslash. The backslash '\' should have already
+   * been read. This supports both unicode escapes "u000A" and two-character
+   * escapes "\n".
+   *
+   * @throws NumberFormatException if any unicode escape sequences are
+   *     malformed.
+   */
+  private char readEscapeCharacter() throws IOException {
+    if (pos == limit && !fillBuffer(1)) {
+      throw syntaxError("Unterminated escape sequence");
+    }
+
+    char escaped = buffer[pos++];
+    switch (escaped) {
+    case 'u':
+      if (pos + 4 > limit && !fillBuffer(4)) {
+        throw syntaxError("Unterminated escape sequence");
+      }
+      // Equivalent to Integer.parseInt(stringPool.get(buffer, pos, 4), 16);
+      char result = 0;
+      for (int i = pos, end = i + 4; i < end; i++) {
+        char c = buffer[i];
+        result <<= 4;
+        if (c >= '0' && c <= '9') {
+          result += (c - '0');
+        } else if (c >= 'a' && c <= 'f') {
+          result += (c - 'a' + 10);
+        } else if (c >= 'A' && c <= 'F') {
+          result += (c - 'A' + 10);
+        } else {
+          throw new NumberFormatException("\\u" + new String(buffer, pos, 4));
+        }
+      }
+      pos += 4;
+      return result;
+
+    case 't':
+      return '\t';
+
+    case 'b':
+      return '\b';
+
+    case 'n':
+      return '\n';
+
+    case 'r':
+      return '\r';
+
+    case 'f':
+      return '\f';
+
+    case '\n':
+      lineNumber++;
+      lineStart = pos;
+      // fall-through
+
+    case '\'':
+    case '"':
+    case '\\':
+    case '/':
+      return escaped;
+    default:
+      // throw error when none of the above cases are matched
+      throw syntaxError("Invalid escape sequence");
+    }
+  }
+
+  /**
+   * Throws a new IO exception with the given message and a context snippet
+   * with this reader's content.
+   */
+  private IOException syntaxError(String message) throws IOException {
+    throw new MalformedJsonException(message + locationString());
+  }
+
+  /**
+   * Consumes the non-execute prefix if it exists.
+   */
+  private void consumeNonExecutePrefix() throws IOException {
+    // fast forward through the leading whitespace
+    nextNonWhitespace(true);
+    pos--;
+
+    if (pos + 5 > limit && !fillBuffer(5)) {
+      return;
+    }
+
+    int p = pos;
+    char[] buf = buffer;
+    if(buf[p] != ')' || buf[p + 1] != ']' || buf[p + 2] != '}' || buf[p + 3] != '\'' || buf[p + 4] != '\n') {
+      return; // not a security token!
+    }
+
+    // we consumed a security token!
+    pos += 5;
+  }
+
+  static {
+    JsonReaderInternalAccess.INSTANCE = new JsonReaderInternalAccess() {
+      @Override public void promoteNameToValue(JsonReader reader) throws IOException {
+        if (reader instanceof JsonTreeReader) {
+          ((JsonTreeReader)reader).promoteNameToValue();
+          return;
+        }
+        int p = reader.peeked;
+        if (p == PEEKED_NONE) {
+          p = reader.doPeek();
+        }
+        if (p == PEEKED_DOUBLE_QUOTED_NAME) {
+          reader.peeked = PEEKED_DOUBLE_QUOTED;
+        } else if (p == PEEKED_SINGLE_QUOTED_NAME) {
+          reader.peeked = PEEKED_SINGLE_QUOTED;
+        } else if (p == PEEKED_UNQUOTED_NAME) {
+          reader.peeked = PEEKED_UNQUOTED;
+        } else {
+          throw new IllegalStateException(
+              "Expected a name but was " + reader.peek() + reader.locationString());
+        }
+      }
+    };
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/stream/JsonScope.java b/gson/src/main/java/com/google/gson/stream/JsonScope.java
new file mode 100644
index 0000000..da69137
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/stream/JsonScope.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2010 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.stream;
+
+/**
+ * Lexical scoping elements within a JSON reader or writer.
+ *
+ * @author Jesse Wilson
+ * @since 1.6
+ */
+final class JsonScope {
+
+    /**
+     * An array with no elements requires no separators or newlines before
+     * it is closed.
+     */
+    static final int EMPTY_ARRAY = 1;
+
+    /**
+     * A array with at least one value requires a comma and newline before
+     * the next element.
+     */
+    static final int NONEMPTY_ARRAY = 2;
+
+    /**
+     * An object with no name/value pairs requires no separators or newlines
+     * before it is closed.
+     */
+    static final int EMPTY_OBJECT = 3;
+
+    /**
+     * An object whose most recent element is a key. The next element must
+     * be a value.
+     */
+    static final int DANGLING_NAME = 4;
+
+    /**
+     * An object with at least one name/value pair requires a comma and
+     * newline before the next element.
+     */
+    static final int NONEMPTY_OBJECT = 5;
+
+    /**
+     * No object or array has been started.
+     */
+    static final int EMPTY_DOCUMENT = 6;
+
+    /**
+     * A document with at an array or object.
+     */
+    static final int NONEMPTY_DOCUMENT = 7;
+
+    /**
+     * A document that's been closed and cannot be accessed.
+     */
+    static final int CLOSED = 8;
+}
diff --git a/gson/src/main/java/com/google/gson/stream/JsonToken.java b/gson/src/main/java/com/google/gson/stream/JsonToken.java
new file mode 100644
index 0000000..f1025b3
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/stream/JsonToken.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright (C) 2010 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.stream;
+
+/**
+ * A structure, name or value type in a JSON-encoded string.
+ *
+ * @author Jesse Wilson
+ * @since 1.6
+ */
+public enum JsonToken {
+
+  /**
+   * The opening of a JSON array. Written using {@link JsonWriter#beginArray}
+   * and read using {@link JsonReader#beginArray}.
+   */
+  BEGIN_ARRAY,
+
+  /**
+   * The closing of a JSON array. Written using {@link JsonWriter#endArray}
+   * and read using {@link JsonReader#endArray}.
+   */
+  END_ARRAY,
+
+  /**
+   * The opening of a JSON object. Written using {@link JsonWriter#beginObject}
+   * and read using {@link JsonReader#beginObject}.
+   */
+  BEGIN_OBJECT,
+
+  /**
+   * The closing of a JSON object. Written using {@link JsonWriter#endObject}
+   * and read using {@link JsonReader#endObject}.
+   */
+  END_OBJECT,
+
+  /**
+   * A JSON property name. Within objects, tokens alternate between names and
+   * their values. Written using {@link JsonWriter#name} and read using {@link
+   * JsonReader#nextName}
+   */
+  NAME,
+
+  /**
+   * A JSON string.
+   */
+  STRING,
+
+  /**
+   * A JSON number represented in this API by a Java {@code double}, {@code
+   * long}, or {@code int}.
+   */
+  NUMBER,
+
+  /**
+   * A JSON {@code true} or {@code false}.
+   */
+  BOOLEAN,
+
+  /**
+   * A JSON {@code null}.
+   */
+  NULL,
+
+  /**
+   * The end of the JSON stream. This sentinel value is returned by {@link
+   * JsonReader#peek()} to signal that the JSON-encoded value has no more
+   * tokens.
+   */
+  END_DOCUMENT
+}
diff --git a/gson/src/main/java/com/google/gson/stream/JsonWriter.java b/gson/src/main/java/com/google/gson/stream/JsonWriter.java
new file mode 100644
index 0000000..c281009
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/stream/JsonWriter.java
@@ -0,0 +1,711 @@
+/*
+ * Copyright (C) 2010 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.stream;
+
+import java.io.Closeable;
+import java.io.Flushable;
+import java.io.IOException;
+import java.io.Writer;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.util.Arrays;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.regex.Pattern;
+
+import static com.google.gson.stream.JsonScope.DANGLING_NAME;
+import static com.google.gson.stream.JsonScope.EMPTY_ARRAY;
+import static com.google.gson.stream.JsonScope.EMPTY_DOCUMENT;
+import static com.google.gson.stream.JsonScope.EMPTY_OBJECT;
+import static com.google.gson.stream.JsonScope.NONEMPTY_ARRAY;
+import static com.google.gson.stream.JsonScope.NONEMPTY_DOCUMENT;
+import static com.google.gson.stream.JsonScope.NONEMPTY_OBJECT;
+
+/**
+ * Writes a JSON (<a href="http://www.ietf.org/rfc/rfc7159.txt">RFC 7159</a>)
+ * encoded value to a stream, one token at a time. The stream includes both
+ * literal values (strings, numbers, booleans and nulls) as well as the begin
+ * and end delimiters of objects and arrays.
+ *
+ * <h3>Encoding JSON</h3>
+ * To encode your data as JSON, create a new {@code JsonWriter}. Each JSON
+ * document must contain one top-level array or object. Call methods on the
+ * writer as you walk the structure's contents, nesting arrays and objects as
+ * necessary:
+ * <ul>
+ *   <li>To write <strong>arrays</strong>, first call {@link #beginArray()}.
+ *       Write each of the array's elements with the appropriate {@link #value}
+ *       methods or by nesting other arrays and objects. Finally close the array
+ *       using {@link #endArray()}.
+ *   <li>To write <strong>objects</strong>, first call {@link #beginObject()}.
+ *       Write each of the object's properties by alternating calls to
+ *       {@link #name} with the property's value. Write property values with the
+ *       appropriate {@link #value} method or by nesting other objects or arrays.
+ *       Finally close the object using {@link #endObject()}.
+ * </ul>
+ *
+ * <h3>Example</h3>
+ * Suppose we'd like to encode a stream of messages such as the following: <pre> {@code
+ * [
+ *   {
+ *     "id": 912345678901,
+ *     "text": "How do I stream JSON in Java?",
+ *     "geo": null,
+ *     "user": {
+ *       "name": "json_newb",
+ *       "followers_count": 41
+ *      }
+ *   },
+ *   {
+ *     "id": 912345678902,
+ *     "text": "@json_newb just use JsonWriter!",
+ *     "geo": [50.454722, -104.606667],
+ *     "user": {
+ *       "name": "jesse",
+ *       "followers_count": 2
+ *     }
+ *   }
+ * ]}</pre>
+ * This code encodes the above structure: <pre>   {@code
+ *   public void writeJsonStream(OutputStream out, List<Message> messages) throws IOException {
+ *     JsonWriter writer = new JsonWriter(new OutputStreamWriter(out, "UTF-8"));
+ *     writer.setIndent("    ");
+ *     writeMessagesArray(writer, messages);
+ *     writer.close();
+ *   }
+ *
+ *   public void writeMessagesArray(JsonWriter writer, List<Message> messages) throws IOException {
+ *     writer.beginArray();
+ *     for (Message message : messages) {
+ *       writeMessage(writer, message);
+ *     }
+ *     writer.endArray();
+ *   }
+ *
+ *   public void writeMessage(JsonWriter writer, Message message) throws IOException {
+ *     writer.beginObject();
+ *     writer.name("id").value(message.getId());
+ *     writer.name("text").value(message.getText());
+ *     if (message.getGeo() != null) {
+ *       writer.name("geo");
+ *       writeDoublesArray(writer, message.getGeo());
+ *     } else {
+ *       writer.name("geo").nullValue();
+ *     }
+ *     writer.name("user");
+ *     writeUser(writer, message.getUser());
+ *     writer.endObject();
+ *   }
+ *
+ *   public void writeUser(JsonWriter writer, User user) throws IOException {
+ *     writer.beginObject();
+ *     writer.name("name").value(user.getName());
+ *     writer.name("followers_count").value(user.getFollowersCount());
+ *     writer.endObject();
+ *   }
+ *
+ *   public void writeDoublesArray(JsonWriter writer, List<Double> doubles) throws IOException {
+ *     writer.beginArray();
+ *     for (Double value : doubles) {
+ *       writer.value(value);
+ *     }
+ *     writer.endArray();
+ *   }}</pre>
+ *
+ * <p>Each {@code JsonWriter} may be used to write a single JSON stream.
+ * Instances of this class are not thread safe. Calls that would result in a
+ * malformed JSON string will fail with an {@link IllegalStateException}.
+ *
+ * @author Jesse Wilson
+ * @since 1.6
+ */
+public class JsonWriter implements Closeable, Flushable {
+
+  // Syntax as defined by https://datatracker.ietf.org/doc/html/rfc8259#section-6
+  private static final Pattern VALID_JSON_NUMBER_PATTERN = Pattern.compile("-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][-+]?[0-9]+)?");
+
+  /*
+   * From RFC 7159, "All Unicode characters may be placed within the
+   * quotation marks except for the characters that must be escaped:
+   * quotation mark, reverse solidus, and the control characters
+   * (U+0000 through U+001F)."
+   *
+   * We also escape '\u2028' and '\u2029', which JavaScript interprets as
+   * newline characters. This prevents eval() from failing with a syntax
+   * error. http://code.google.com/p/google-gson/issues/detail?id=341
+   */
+  private static final String[] REPLACEMENT_CHARS;
+  private static final String[] HTML_SAFE_REPLACEMENT_CHARS;
+  static {
+    REPLACEMENT_CHARS = new String[128];
+    for (int i = 0; i <= 0x1f; i++) {
+      REPLACEMENT_CHARS[i] = String.format("\\u%04x", (int) i);
+    }
+    REPLACEMENT_CHARS['"'] = "\\\"";
+    REPLACEMENT_CHARS['\\'] = "\\\\";
+    REPLACEMENT_CHARS['\t'] = "\\t";
+    REPLACEMENT_CHARS['\b'] = "\\b";
+    REPLACEMENT_CHARS['\n'] = "\\n";
+    REPLACEMENT_CHARS['\r'] = "\\r";
+    REPLACEMENT_CHARS['\f'] = "\\f";
+    HTML_SAFE_REPLACEMENT_CHARS = REPLACEMENT_CHARS.clone();
+    HTML_SAFE_REPLACEMENT_CHARS['<'] = "\\u003c";
+    HTML_SAFE_REPLACEMENT_CHARS['>'] = "\\u003e";
+    HTML_SAFE_REPLACEMENT_CHARS['&'] = "\\u0026";
+    HTML_SAFE_REPLACEMENT_CHARS['='] = "\\u003d";
+    HTML_SAFE_REPLACEMENT_CHARS['\''] = "\\u0027";
+  }
+
+  /** The output data, containing at most one top-level array or object. */
+  private final Writer out;
+
+  private int[] stack = new int[32];
+  private int stackSize = 0;
+  {
+    push(EMPTY_DOCUMENT);
+  }
+
+  /**
+   * A string containing a full set of spaces for a single level of
+   * indentation, or null for no pretty printing.
+   */
+  private String indent;
+
+  /**
+   * The name/value separator; either ":" or ": ".
+   */
+  private String separator = ":";
+
+  private boolean lenient;
+
+  private boolean htmlSafe;
+
+  private String deferredName;
+
+  private boolean serializeNulls = true;
+
+  /**
+   * Creates a new instance that writes a JSON-encoded stream to {@code out}.
+   * For best performance, ensure {@link Writer} is buffered; wrapping in
+   * {@link java.io.BufferedWriter BufferedWriter} if necessary.
+   */
+  public JsonWriter(Writer out) {
+    if (out == null) {
+      throw new NullPointerException("out == null");
+    }
+    this.out = out;
+  }
+
+  /**
+   * Sets the indentation string to be repeated for each level of indentation
+   * in the encoded document. If {@code indent.isEmpty()} the encoded document
+   * will be compact. Otherwise the encoded document will be more
+   * human-readable.
+   *
+   * @param indent a string containing only whitespace.
+   */
+  public final void setIndent(String indent) {
+    if (indent.length() == 0) {
+      this.indent = null;
+      this.separator = ":";
+    } else {
+      this.indent = indent;
+      this.separator = ": ";
+    }
+  }
+
+  /**
+   * Configure this writer to relax its syntax rules. By default, this writer
+   * only emits well-formed JSON as specified by <a
+   * href="http://www.ietf.org/rfc/rfc7159.txt">RFC 7159</a>. Setting the writer
+   * to lenient permits the following:
+   * <ul>
+   *   <li>Top-level values of any type. With strict writing, the top-level
+   *       value must be an object or an array.
+   *   <li>Numbers may be {@link Double#isNaN() NaNs} or {@link
+   *       Double#isInfinite() infinities}.
+   * </ul>
+   */
+  public final void setLenient(boolean lenient) {
+    this.lenient = lenient;
+  }
+
+  /**
+   * Returns true if this writer has relaxed syntax rules.
+   */
+  public boolean isLenient() {
+    return lenient;
+  }
+
+  /**
+   * Configure this writer to emit JSON that's safe for direct inclusion in HTML
+   * and XML documents. This escapes the HTML characters {@code <}, {@code >},
+   * {@code &} and {@code =} before writing them to the stream. Without this
+   * setting, your XML/HTML encoder should replace these characters with the
+   * corresponding escape sequences.
+   */
+  public final void setHtmlSafe(boolean htmlSafe) {
+    this.htmlSafe = htmlSafe;
+  }
+
+  /**
+   * Returns true if this writer writes JSON that's safe for inclusion in HTML
+   * and XML documents.
+   */
+  public final boolean isHtmlSafe() {
+    return htmlSafe;
+  }
+
+  /**
+   * Sets whether object members are serialized when their value is null.
+   * This has no impact on array elements. The default is true.
+   */
+  public final void setSerializeNulls(boolean serializeNulls) {
+    this.serializeNulls = serializeNulls;
+  }
+
+  /**
+   * Returns true if object members are serialized when their value is null.
+   * This has no impact on array elements. The default is true.
+   */
+  public final boolean getSerializeNulls() {
+    return serializeNulls;
+  }
+
+  /**
+   * Begins encoding a new array. Each call to this method must be paired with
+   * a call to {@link #endArray}.
+   *
+   * @return this writer.
+   */
+  public JsonWriter beginArray() throws IOException {
+    writeDeferredName();
+    return open(EMPTY_ARRAY, '[');
+  }
+
+  /**
+   * Ends encoding the current array.
+   *
+   * @return this writer.
+   */
+  public JsonWriter endArray() throws IOException {
+    return close(EMPTY_ARRAY, NONEMPTY_ARRAY, ']');
+  }
+
+  /**
+   * Begins encoding a new object. Each call to this method must be paired
+   * with a call to {@link #endObject}.
+   *
+   * @return this writer.
+   */
+  public JsonWriter beginObject() throws IOException {
+    writeDeferredName();
+    return open(EMPTY_OBJECT, '{');
+  }
+
+  /**
+   * Ends encoding the current object.
+   *
+   * @return this writer.
+   */
+  public JsonWriter endObject() throws IOException {
+    return close(EMPTY_OBJECT, NONEMPTY_OBJECT, '}');
+  }
+
+  /**
+   * Enters a new scope by appending any necessary whitespace and the given
+   * bracket.
+   */
+  private JsonWriter open(int empty, char openBracket) throws IOException {
+    beforeValue();
+    push(empty);
+    out.write(openBracket);
+    return this;
+  }
+
+  /**
+   * Closes the current scope by appending any necessary whitespace and the
+   * given bracket.
+   */
+  private JsonWriter close(int empty, int nonempty, char closeBracket)
+      throws IOException {
+    int context = peek();
+    if (context != nonempty && context != empty) {
+      throw new IllegalStateException("Nesting problem.");
+    }
+    if (deferredName != null) {
+      throw new IllegalStateException("Dangling name: " + deferredName);
+    }
+
+    stackSize--;
+    if (context == nonempty) {
+      newline();
+    }
+    out.write(closeBracket);
+    return this;
+  }
+
+  private void push(int newTop) {
+    if (stackSize == stack.length) {
+      stack = Arrays.copyOf(stack, stackSize * 2);
+    }
+    stack[stackSize++] = newTop;
+  }
+
+  /**
+   * Returns the value on the top of the stack.
+   */
+  private int peek() {
+    if (stackSize == 0) {
+      throw new IllegalStateException("JsonWriter is closed.");
+    }
+    return stack[stackSize - 1];
+  }
+
+  /**
+   * Replace the value on the top of the stack with the given value.
+   */
+  private void replaceTop(int topOfStack) {
+    stack[stackSize - 1] = topOfStack;
+  }
+
+  /**
+   * Encodes the property name.
+   *
+   * @param name the name of the forthcoming value. May not be null.
+   * @return this writer.
+   */
+  public JsonWriter name(String name) throws IOException {
+    if (name == null) {
+      throw new NullPointerException("name == null");
+    }
+    if (deferredName != null) {
+      throw new IllegalStateException();
+    }
+    if (stackSize == 0) {
+      throw new IllegalStateException("JsonWriter is closed.");
+    }
+    deferredName = name;
+    return this;
+  }
+
+  private void writeDeferredName() throws IOException {
+    if (deferredName != null) {
+      beforeName();
+      string(deferredName);
+      deferredName = null;
+    }
+  }
+
+  /**
+   * Encodes {@code value}.
+   *
+   * @param value the literal string value, or null to encode a null literal.
+   * @return this writer.
+   */
+  public JsonWriter value(String value) throws IOException {
+    if (value == null) {
+      return nullValue();
+    }
+    writeDeferredName();
+    beforeValue();
+    string(value);
+    return this;
+  }
+
+  /**
+   * Writes {@code value} directly to the writer without quoting or
+   * escaping.
+   *
+   * @param value the literal string value, or null to encode a null literal.
+   * @return this writer.
+   */
+  public JsonWriter jsonValue(String value) throws IOException {
+    if (value == null) {
+      return nullValue();
+    }
+    writeDeferredName();
+    beforeValue();
+    out.append(value);
+    return this;
+  }
+
+  /**
+   * Encodes {@code null}.
+   *
+   * @return this writer.
+   */
+  public JsonWriter nullValue() throws IOException {
+    if (deferredName != null) {
+      if (serializeNulls) {
+        writeDeferredName();
+      } else {
+        deferredName = null;
+        return this; // skip the name and the value
+      }
+    }
+    beforeValue();
+    out.write("null");
+    return this;
+  }
+
+  /**
+   * Encodes {@code value}.
+   *
+   * @return this writer.
+   */
+  public JsonWriter value(boolean value) throws IOException {
+    writeDeferredName();
+    beforeValue();
+    out.write(value ? "true" : "false");
+    return this;
+  }
+
+  /**
+   * Encodes {@code value}.
+   *
+   * @return this writer.
+   */
+  public JsonWriter value(Boolean value) throws IOException {
+    if (value == null) {
+      return nullValue();
+    }
+    writeDeferredName();
+    beforeValue();
+    out.write(value ? "true" : "false");
+    return this;
+  }
+
+  /**
+   * Encodes {@code value}.
+   *
+   * @param value a finite value, or if {@link #setLenient(boolean) lenient},
+   *     also {@link Float#isNaN() NaN} or {@link Float#isInfinite()
+   *     infinity}.
+   * @return this writer.
+   * @throws IllegalArgumentException if the value is NaN or Infinity and this writer is not {@link
+   *     #setLenient(boolean) lenient}.
+   */
+  public JsonWriter value(float value) throws IOException {
+    writeDeferredName();
+    if (!lenient && (Float.isNaN(value) || Float.isInfinite(value))) {
+      throw new IllegalArgumentException("Numeric values must be finite, but was " + value);
+    }
+    beforeValue();
+    out.append(Float.toString(value));
+    return this;
+  }
+
+  /**
+   * Encodes {@code value}.
+   *
+   * @param value a finite value, or if {@link #setLenient(boolean) lenient},
+   *     also {@link Double#isNaN() NaN} or {@link Double#isInfinite() infinity}.
+   * @return this writer.
+   * @throws IllegalArgumentException if the value is NaN or Infinity and this writer is
+   *     not {@link #setLenient(boolean) lenient}.
+   */
+  public JsonWriter value(double value) throws IOException {
+    writeDeferredName();
+    if (!lenient && (Double.isNaN(value) || Double.isInfinite(value))) {
+      throw new IllegalArgumentException("Numeric values must be finite, but was " + value);
+    }
+    beforeValue();
+    out.append(Double.toString(value));
+    return this;
+  }
+
+  /**
+   * Encodes {@code value}.
+   *
+   * @return this writer.
+   */
+  public JsonWriter value(long value) throws IOException {
+    writeDeferredName();
+    beforeValue();
+    out.write(Long.toString(value));
+    return this;
+  }
+
+  /**
+   * Returns whether the {@code toString()} of {@code c} can be trusted to return
+   * a valid JSON number.
+   */
+  private static boolean isTrustedNumberType(Class<? extends Number> c) {
+    // Note: Don't consider LazilyParsedNumber trusted because it could contain
+    // an arbitrary malformed string
+    return c == Integer.class || c == Long.class || c == Double.class || c == Float.class || c == Byte.class || c == Short.class
+        || c == BigDecimal.class || c == BigInteger.class || c == AtomicInteger.class || c == AtomicLong.class;
+  }
+
+  /**
+   * Encodes {@code value}. The value is written by directly writing the {@link Number#toString()}
+   * result to JSON. Implementations must make sure that the result represents a valid JSON number.
+   *
+   * @param value a finite value, or if {@link #setLenient(boolean) lenient},
+   *     also {@link Double#isNaN() NaN} or {@link Double#isInfinite() infinity}.
+   * @return this writer.
+   * @throws IllegalArgumentException if the value is NaN or Infinity and this writer is
+   *     not {@link #setLenient(boolean) lenient}; or if the {@code toString()} result is not a
+   *     valid JSON number.
+   */
+  public JsonWriter value(Number value) throws IOException {
+    if (value == null) {
+      return nullValue();
+    }
+
+    writeDeferredName();
+    String string = value.toString();
+    if (string.equals("-Infinity") || string.equals("Infinity") || string.equals("NaN")) {
+      if (!lenient) {
+        throw new IllegalArgumentException("Numeric values must be finite, but was " + string);
+      }
+    } else {
+      Class<? extends Number> numberClass = value.getClass();
+      // Validate that string is valid before writing it directly to JSON output
+      if (!isTrustedNumberType(numberClass) && !VALID_JSON_NUMBER_PATTERN.matcher(string).matches()) {
+        throw new IllegalArgumentException("String created by " + numberClass + " is not a valid JSON number: " + string);
+      }
+    }
+
+    beforeValue();
+    out.append(string);
+    return this;
+  }
+
+  /**
+   * Ensures all buffered data is written to the underlying {@link Writer}
+   * and flushes that writer.
+   */
+  @Override public void flush() throws IOException {
+    if (stackSize == 0) {
+      throw new IllegalStateException("JsonWriter is closed.");
+    }
+    out.flush();
+  }
+
+  /**
+   * Flushes and closes this writer and the underlying {@link Writer}.
+   *
+   * @throws IOException if the JSON document is incomplete.
+   */
+  @Override public void close() throws IOException {
+    out.close();
+
+    int size = stackSize;
+    if (size > 1 || size == 1 && stack[size - 1] != NONEMPTY_DOCUMENT) {
+      throw new IOException("Incomplete document");
+    }
+    stackSize = 0;
+  }
+
+  private void string(String value) throws IOException {
+    String[] replacements = htmlSafe ? HTML_SAFE_REPLACEMENT_CHARS : REPLACEMENT_CHARS;
+    out.write('\"');
+    int last = 0;
+    int length = value.length();
+    for (int i = 0; i < length; i++) {
+      char c = value.charAt(i);
+      String replacement;
+      if (c < 128) {
+        replacement = replacements[c];
+        if (replacement == null) {
+          continue;
+        }
+      } else if (c == '\u2028') {
+        replacement = "\\u2028";
+      } else if (c == '\u2029') {
+        replacement = "\\u2029";
+      } else {
+        continue;
+      }
+      if (last < i) {
+        out.write(value, last, i - last);
+      }
+      out.write(replacement);
+      last = i + 1;
+    }
+    if (last < length) {
+      out.write(value, last, length - last);
+    }
+    out.write('\"');
+  }
+
+  private void newline() throws IOException {
+    if (indent == null) {
+      return;
+    }
+
+    out.write('\n');
+    for (int i = 1, size = stackSize; i < size; i++) {
+      out.write(indent);
+    }
+  }
+
+  /**
+   * Inserts any necessary separators and whitespace before a name. Also
+   * adjusts the stack to expect the name's value.
+   */
+  private void beforeName() throws IOException {
+    int context = peek();
+    if (context == NONEMPTY_OBJECT) { // first in object
+      out.write(',');
+    } else if (context != EMPTY_OBJECT) { // not in an object!
+      throw new IllegalStateException("Nesting problem.");
+    }
+    newline();
+    replaceTop(DANGLING_NAME);
+  }
+
+  /**
+   * Inserts any necessary separators and whitespace before a literal value,
+   * inline array, or inline object. Also adjusts the stack to expect either a
+   * closing bracket or another element.
+   */
+  @SuppressWarnings("fallthrough")
+  private void beforeValue() throws IOException {
+    switch (peek()) {
+    case NONEMPTY_DOCUMENT:
+      if (!lenient) {
+        throw new IllegalStateException(
+            "JSON must have only one top-level value.");
+      }
+      // fall-through
+    case EMPTY_DOCUMENT: // first in document
+      replaceTop(NONEMPTY_DOCUMENT);
+      break;
+
+    case EMPTY_ARRAY: // first in array
+      replaceTop(NONEMPTY_ARRAY);
+      newline();
+      break;
+
+    case NONEMPTY_ARRAY: // another in array
+      out.append(',');
+      newline();
+      break;
+
+    case DANGLING_NAME: // value for name
+      out.append(separator);
+      replaceTop(NONEMPTY_OBJECT);
+      break;
+
+    default:
+      throw new IllegalStateException("Nesting problem.");
+    }
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/stream/MalformedJsonException.java b/gson/src/main/java/com/google/gson/stream/MalformedJsonException.java
new file mode 100644
index 0000000..65b0a77
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/stream/MalformedJsonException.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2010 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.stream;
+
+import java.io.IOException;
+
+/**
+ * Thrown when a reader encounters malformed JSON. Some syntax errors can be
+ * ignored by calling {@link JsonReader#setLenient(boolean)}.
+ */
+public final class MalformedJsonException extends IOException {
+  private static final long serialVersionUID = 1L;
+
+  public MalformedJsonException(String msg) {
+    super(msg);
+  }
+
+  public MalformedJsonException(String msg, Throwable throwable) {
+    super(msg, throwable);
+  }
+
+  public MalformedJsonException(Throwable throwable) {
+    super(throwable);
+  }
+}
diff --git a/gson/src/main/java/com/google/gson/stream/package-info.java b/gson/src/main/java/com/google/gson/stream/package-info.java
new file mode 100644
index 0000000..bed6c62
--- /dev/null
+++ b/gson/src/main/java/com/google/gson/stream/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * This package provides classes for processing JSON in an efficient streaming way.
+ */
+package com.google.gson.stream;
diff --git a/gson/src/main/java/module-info.java b/gson/src/main/java/module-info.java
new file mode 100644
index 0000000..0134c9d
--- /dev/null
+++ b/gson/src/main/java/module-info.java
@@ -0,0 +1,16 @@
+/**
+ * Defines the Gson serialization/deserialization API.
+ * @since 2.8.6
+ */
+module com.google.gson {
+	exports com.google.gson;
+	exports com.google.gson.annotations;
+	exports com.google.gson.reflect;
+	exports com.google.gson.stream;
+
+	// Optional dependency on java.sql
+	requires static java.sql;
+
+	// Optional dependency on jdk.unsupported for JDK's sun.misc.Unsafe
+	requires static jdk.unsupported;
+}
diff --git a/gson/src/test/java/com/google/gson/CommentsTest.java b/gson/src/test/java/com/google/gson/CommentsTest.java
new file mode 100644
index 0000000..306e5af
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/CommentsTest.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2010 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import com.google.gson.reflect.TypeToken;
+import java.util.Arrays;
+import java.util.List;
+import junit.framework.TestCase;
+
+/**
+ * @author Jesse Wilson
+ */
+public final class CommentsTest extends TestCase {
+
+  /**
+   * Test for issue 212.
+   */
+  public void testParseComments() {
+    String json = "[\n"
+        + "  // this is a comment\n"
+        + "  \"a\",\n"
+        + "  /* this is another comment */\n"
+        + "  \"b\",\n"
+        + "  # this is yet another comment\n"
+        + "  \"c\"\n"
+        + "]";
+
+    List<String> abc = new Gson().fromJson(json, new TypeToken<List<String>>() {}.getType());
+    assertEquals(Arrays.asList("a", "b", "c"), abc);
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/DefaultInetAddressTypeAdapterTest.java b/gson/src/test/java/com/google/gson/DefaultInetAddressTypeAdapterTest.java
new file mode 100644
index 0000000..6b853f5
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/DefaultInetAddressTypeAdapterTest.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import java.net.InetAddress;
+
+import junit.framework.TestCase;
+
+/**
+ * Unit tests for the default serializer/deserializer for the {@code InetAddress} type.
+ * 
+ * @author Joel Leitch
+ */
+public class DefaultInetAddressTypeAdapterTest extends TestCase {
+  private Gson gson;
+  
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    gson = new Gson();
+  }
+  
+  public void testInetAddressSerializationAndDeserialization() throws Exception {
+    InetAddress address = InetAddress.getByName("8.8.8.8");
+    String jsonAddress = gson.toJson(address);
+    assertEquals("\"8.8.8.8\"", jsonAddress);
+    
+    InetAddress value = gson.fromJson(jsonAddress, InetAddress.class);
+    assertEquals(value, address);
+  } 
+}
diff --git a/gson/src/test/java/com/google/gson/DefaultMapJsonSerializerTest.java b/gson/src/test/java/com/google/gson/DefaultMapJsonSerializerTest.java
new file mode 100644
index 0000000..624b863
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/DefaultMapJsonSerializerTest.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import com.google.gson.reflect.TypeToken;
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.Map;
+import junit.framework.TestCase;
+
+/**
+ * Unit test for the default JSON map serialization object located in the
+ * {@link DefaultTypeAdapters} class.
+ *
+ * @author Joel Leitch
+ */
+public class DefaultMapJsonSerializerTest extends TestCase {
+  private Gson gson = new Gson();
+
+  public void testEmptyMapNoTypeSerialization() {
+    Map<String, String> emptyMap = new HashMap<>();
+    JsonElement element = gson.toJsonTree(emptyMap, emptyMap.getClass());
+    assertTrue(element instanceof JsonObject);
+    JsonObject emptyMapJsonObject = (JsonObject) element;
+    assertTrue(emptyMapJsonObject.entrySet().isEmpty());
+  }
+
+  public void testEmptyMapSerialization() {
+    Type mapType = new TypeToken<Map<String, String>>() { }.getType();
+    Map<String, String> emptyMap = new HashMap<>();
+    JsonElement element = gson.toJsonTree(emptyMap, mapType);
+
+    assertTrue(element instanceof JsonObject);
+    JsonObject emptyMapJsonObject = (JsonObject) element;
+    assertTrue(emptyMapJsonObject.entrySet().isEmpty());
+  }
+
+  public void testNonEmptyMapSerialization() {
+    Type mapType = new TypeToken<Map<String, String>>() { }.getType();
+    Map<String, String> myMap = new HashMap<>();
+    String key = "key1";
+    myMap.put(key, "value1");
+    Gson gson = new Gson();
+    JsonElement element = gson.toJsonTree(myMap, mapType);
+
+    assertTrue(element.isJsonObject());
+    JsonObject mapJsonObject = element.getAsJsonObject();
+    assertTrue(mapJsonObject.has(key));
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/ExposeAnnotationExclusionStrategyTest.java b/gson/src/test/java/com/google/gson/ExposeAnnotationExclusionStrategyTest.java
new file mode 100644
index 0000000..dd8a7a9
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/ExposeAnnotationExclusionStrategyTest.java
@@ -0,0 +1,89 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import com.google.gson.annotations.Expose;
+
+import com.google.gson.internal.Excluder;
+import junit.framework.TestCase;
+
+import java.lang.reflect.Field;
+
+/**
+ * Unit tests for GsonBuilder.REQUIRE_EXPOSE_DESERIALIZE.
+ *
+ * @author Joel Leitch
+ */
+public class ExposeAnnotationExclusionStrategyTest extends TestCase {
+  private Excluder excluder = Excluder.DEFAULT.excludeFieldsWithoutExposeAnnotation();
+
+  public void testNeverSkipClasses() throws Exception {
+    assertFalse(excluder.excludeClass(MockObject.class, true));
+    assertFalse(excluder.excludeClass(MockObject.class, false));
+  }
+
+  public void testSkipNonAnnotatedFields() throws Exception {
+    Field f = createFieldAttributes("hiddenField");
+    assertTrue(excluder.excludeField(f, true));
+    assertTrue(excluder.excludeField(f, false));
+  }
+
+  public void testSkipExplicitlySkippedFields() throws Exception {
+    Field f = createFieldAttributes("explicitlyHiddenField");
+    assertTrue(excluder.excludeField(f, true));
+    assertTrue(excluder.excludeField(f, false));
+  }
+
+  public void testNeverSkipExposedAnnotatedFields() throws Exception {
+    Field f = createFieldAttributes("exposedField");
+    assertFalse(excluder.excludeField(f, true));
+    assertFalse(excluder.excludeField(f, false));
+  }
+
+  public void testNeverSkipExplicitlyExposedAnnotatedFields() throws Exception {
+    Field f = createFieldAttributes("explicitlyExposedField");
+    assertFalse(excluder.excludeField(f, true));
+    assertFalse(excluder.excludeField(f, false));
+  }
+
+  public void testDifferentSerializeAndDeserializeField() throws Exception {
+    Field f = createFieldAttributes("explicitlyDifferentModeField");
+    assertFalse(excluder.excludeField(f, true));
+    assertTrue(excluder.excludeField(f, false));
+  }
+
+  private static Field createFieldAttributes(String fieldName) throws Exception {
+    return MockObject.class.getField(fieldName);
+  }
+
+  @SuppressWarnings("unused")
+  private static class MockObject {
+    @Expose
+    public final int exposedField = 0;
+
+    @Expose(serialize=true, deserialize=true)
+    public final int explicitlyExposedField = 0;
+
+    @Expose(serialize=false, deserialize=false)
+    public final int explicitlyHiddenField = 0;
+
+    @Expose(serialize=true, deserialize=false)
+    public final int explicitlyDifferentModeField = 0;
+
+    public final int hiddenField = 0;
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/FieldAttributesTest.java b/gson/src/test/java/com/google/gson/FieldAttributesTest.java
new file mode 100644
index 0000000..31be3e2
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/FieldAttributesTest.java
@@ -0,0 +1,77 @@
+/*
+ * Copyright (C) 2009 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import com.google.gson.reflect.TypeToken;
+import java.lang.reflect.Modifier;
+import java.lang.reflect.Type;
+import java.util.List;
+import junit.framework.TestCase;
+
+/**
+ * Unit tests for the {@link FieldAttributes} class.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public class FieldAttributesTest extends TestCase {
+  private FieldAttributes fieldAttributes;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    fieldAttributes = new FieldAttributes(Foo.class.getField("bar"));
+  }
+
+  @SuppressWarnings("unused")
+  public void testNullField() throws Exception {
+    try {
+      new FieldAttributes(null);
+      fail("Field parameter can not be null");
+    } catch (NullPointerException expected) { }
+  }
+
+  public void testDeclaringClass() throws Exception {
+    assertEquals(Foo.class, fieldAttributes.getDeclaringClass());
+  }
+
+  public void testModifiers() throws Exception {
+    assertFalse(fieldAttributes.hasModifier(Modifier.STATIC));
+    assertFalse(fieldAttributes.hasModifier(Modifier.FINAL));
+    assertFalse(fieldAttributes.hasModifier(Modifier.ABSTRACT));
+    assertFalse(fieldAttributes.hasModifier(Modifier.VOLATILE));
+    assertFalse(fieldAttributes.hasModifier(Modifier.PROTECTED));
+
+    assertTrue(fieldAttributes.hasModifier(Modifier.PUBLIC));
+    assertTrue(fieldAttributes.hasModifier(Modifier.TRANSIENT));
+  }
+
+  public void testName() throws Exception {
+    assertEquals("bar", fieldAttributes.getName());
+  }
+
+  public void testDeclaredTypeAndClass() throws Exception {
+    Type expectedType = new TypeToken<List<String>>() {}.getType();
+    assertEquals(expectedType, fieldAttributes.getDeclaredType());
+    assertEquals(List.class, fieldAttributes.getDeclaredClass());
+  }
+
+  private static class Foo {
+    @SuppressWarnings("unused")
+    public transient List<String> bar;
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/FieldNamingPolicyTest.java b/gson/src/test/java/com/google/gson/FieldNamingPolicyTest.java
new file mode 100644
index 0000000..4d4c716
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/FieldNamingPolicyTest.java
@@ -0,0 +1,131 @@
+package com.google.gson;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+import java.lang.reflect.Field;
+import java.util.Locale;
+import org.junit.Test;
+import com.google.gson.functional.FieldNamingTest;
+
+/**
+ * Performs tests directly against {@link FieldNamingPolicy}; for integration tests
+ * see {@link FieldNamingTest}.
+ */
+public class FieldNamingPolicyTest {
+  @Test
+  public void testSeparateCamelCase() {
+    // Map from original -> expected
+    String[][] argumentPairs =  {
+      { "a", "a" },
+      { "ab", "ab" },
+      { "Ab", "Ab" },
+      { "aB", "a_B" },
+      { "AB", "A_B" },
+      { "A_B", "A__B" },
+      { "firstSecondThird", "first_Second_Third" },
+      { "__", "__" },
+      { "_123", "_123" }
+    };
+
+    for (String[] pair : argumentPairs) {
+      assertEquals(pair[1], FieldNamingPolicy.separateCamelCase(pair[0], '_'));
+    }
+  }
+
+  @Test
+  public void testUpperCaseFirstLetter() {
+    // Map from original -> expected
+    String[][] argumentPairs =  {
+      { "a", "A" },
+      { "ab", "Ab" },
+      { "AB", "AB" },
+      { "_a", "_A" },
+      { "_ab", "_Ab" },
+      { "__", "__" },
+      { "_1", "_1" },
+      // Not a letter, but has uppercase variant (should not be uppercased)
+      // See https://github.com/google/gson/issues/1965
+      { "\u2170", "\u2170" },
+      { "_\u2170", "_\u2170" },
+      { "\u2170a", "\u2170A" },
+    };
+
+    for (String[] pair : argumentPairs) {
+      assertEquals(pair[1], FieldNamingPolicy.upperCaseFirstLetter(pair[0]));
+    }
+  }
+
+  /**
+   * Upper casing policies should be unaffected by default Locale.
+   */
+  @Test
+  public void testUpperCasingLocaleIndependent() throws Exception {
+    class Dummy {
+      @SuppressWarnings("unused")
+      int i;
+    }
+
+    FieldNamingPolicy[] policies = {
+      FieldNamingPolicy.UPPER_CAMEL_CASE,
+      FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES,
+      FieldNamingPolicy.UPPER_CASE_WITH_UNDERSCORES,
+    };
+
+    Field field = Dummy.class.getDeclaredField("i");
+    String name = field.getName();
+    String expected = name.toUpperCase(Locale.ROOT);
+
+    Locale oldLocale = Locale.getDefault();
+    // Set Turkish as Locale which has special case conversion rules
+    Locale.setDefault(new Locale("tr"));
+
+    try {
+      // Verify that default Locale has different case conversion rules
+      assertNotEquals("Test setup is broken", expected, name.toUpperCase());
+
+      for (FieldNamingPolicy policy : policies) {
+        // Should ignore default Locale
+        assertEquals("Unexpected conversion for " + policy, expected, policy.translateName(field));
+      }
+    } finally {
+        Locale.setDefault(oldLocale);
+    }
+  }
+
+  /**
+   * Lower casing policies should be unaffected by default Locale.
+   */
+  @Test
+  public void testLowerCasingLocaleIndependent() throws Exception {
+    class Dummy {
+      @SuppressWarnings("unused")
+      int I;
+    }
+
+    FieldNamingPolicy[] policies = {
+      FieldNamingPolicy.LOWER_CASE_WITH_DASHES,
+      FieldNamingPolicy.LOWER_CASE_WITH_DOTS,
+      FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES,
+    };
+
+    Field field = Dummy.class.getDeclaredField("I");
+    String name = field.getName();
+    String expected = name.toLowerCase(Locale.ROOT);
+
+    Locale oldLocale = Locale.getDefault();
+    // Set Turkish as Locale which has special case conversion rules
+    Locale.setDefault(new Locale("tr"));
+
+    try {
+      // Verify that default Locale has different case conversion rules
+      assertNotEquals("Test setup is broken", expected, name.toLowerCase());
+
+      for (FieldNamingPolicy policy : policies) {
+        // Should ignore default Locale
+        assertEquals("Unexpected conversion for " + policy, expected, policy.translateName(field));
+      }
+    } finally {
+        Locale.setDefault(oldLocale);
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/GenericArrayTypeTest.java b/gson/src/test/java/com/google/gson/GenericArrayTypeTest.java
new file mode 100644
index 0000000..42acb8a
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/GenericArrayTypeTest.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import com.google.gson.internal.$Gson$Types;
+import com.google.gson.reflect.TypeToken;
+
+import junit.framework.TestCase;
+
+import java.lang.reflect.GenericArrayType;
+import java.lang.reflect.Type;
+import java.util.List;
+
+/**
+ * Unit tests for the {@code GenericArrayType}s created by the {@link $Gson$Types} class.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public class GenericArrayTypeTest extends TestCase {
+  private GenericArrayType ourType;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    ourType = $Gson$Types.arrayOf($Gson$Types.newParameterizedTypeWithOwner(null, List.class, String.class));
+  }
+
+  public void testOurTypeFunctionality() throws Exception {
+    Type parameterizedType = new TypeToken<List<String>>() {}.getType();
+    Type genericArrayType = new TypeToken<List<String>[]>() {}.getType();
+
+    assertEquals(parameterizedType, ourType.getGenericComponentType());
+    assertEquals(genericArrayType, ourType);
+    assertEquals(genericArrayType.hashCode(), ourType.hashCode());
+  }
+
+  public void testNotEquals() throws Exception {
+    Type differentGenericArrayType = new TypeToken<List<String>[][]>() {}.getType();
+    assertFalse(differentGenericArrayType.equals(ourType));
+    assertFalse(ourType.equals(differentGenericArrayType));
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/GsonBuilderTest.java b/gson/src/test/java/com/google/gson/GsonBuilderTest.java
new file mode 100644
index 0000000..d1fd0d4
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/GsonBuilderTest.java
@@ -0,0 +1,110 @@
+/*

+ * Copyright (C) 2008 Google Inc.

+ *

+ * Licensed under the Apache License, Version 2.0 (the "License");

+ * you may not use this file except in compliance with the License.

+ * You may obtain a copy of the License at

+ *

+ * http://www.apache.org/licenses/LICENSE-2.0

+ *

+ * Unless required by applicable law or agreed to in writing, software

+ * distributed under the License is distributed on an "AS IS" BASIS,

+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

+ * See the License for the specific language governing permissions and

+ * limitations under the License.

+ */

+

+package com.google.gson;

+

+import java.lang.reflect.Modifier;

+import java.lang.reflect.Type;

+

+import junit.framework.TestCase;

+

+import com.google.gson.stream.JsonReader;

+import com.google.gson.stream.JsonWriter;

+

+/**

+ * Unit tests for {@link GsonBuilder}.

+ *

+ * @author Inderjeet Singh

+ */

+public class GsonBuilderTest extends TestCase {

+  private static final TypeAdapter<Object> NULL_TYPE_ADAPTER = new TypeAdapter<Object>() {

+    @Override public void write(JsonWriter out, Object value) {

+      throw new AssertionError();

+    }

+    @Override public Object read(JsonReader in) {

+      throw new AssertionError();

+    }

+  };

+

+  public void testCreatingMoreThanOnce() {

+    GsonBuilder builder = new GsonBuilder();

+    builder.create();

+    builder.create();

+  }

+

+  public void testExcludeFieldsWithModifiers() {

+    Gson gson = new GsonBuilder()

+        .excludeFieldsWithModifiers(Modifier.VOLATILE, Modifier.PRIVATE)

+        .create();

+    assertEquals("{\"d\":\"d\"}", gson.toJson(new HasModifiers()));

+  }

+

+  public void testRegisterTypeAdapterForCoreType() {

+    Type[] types = {

+        byte.class,

+        int.class,

+        double.class,

+        Short.class,

+        Long.class,

+        String.class,

+    };

+    for (Type type : types) {

+      new GsonBuilder().registerTypeAdapter(type, NULL_TYPE_ADAPTER);

+    }

+  }

+

+  @SuppressWarnings("unused")

+  static class HasModifiers {

+    private String a = "a";

+    volatile String b = "b";

+    private volatile String c = "c";

+    String d = "d";

+  }

+

+  public void testTransientFieldExclusion() {

+    Gson gson = new GsonBuilder()

+        .excludeFieldsWithModifiers()

+        .create();

+    assertEquals("{\"a\":\"a\"}", gson.toJson(new HasTransients()));

+  }

+

+  static class HasTransients {

+    transient String a = "a";

+  }

+

+  public void testDisableJdkUnsafe() {

+    Gson gson = new GsonBuilder()

+        .disableJdkUnsafe()

+        .create();

+    try {

+      gson.fromJson("{}", ClassWithoutNoArgsConstructor.class);

+      fail("Expected exception");

+    } catch (JsonIOException expected) {

+      assertEquals(

+        "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, "

+        + "adding a no-args constructor, or enabling usage of JDK Unsafe may fix this problem.",

+        expected.getMessage()

+      );

+    }

+  }

+

+  private static class ClassWithoutNoArgsConstructor {

+    @SuppressWarnings("unused")

+    public ClassWithoutNoArgsConstructor(String s) {

+    }

+  }

+}

diff --git a/gson/src/test/java/com/google/gson/GsonTest.java b/gson/src/test/java/com/google/gson/GsonTest.java
new file mode 100644
index 0000000..abb0de2
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/GsonTest.java
@@ -0,0 +1,158 @@
+/*
+ * Copyright (C) 2016 The Gson Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import com.google.gson.internal.Excluder;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonWriter;
+import com.google.gson.stream.MalformedJsonException;
+import java.io.IOException;
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.lang.reflect.Field;
+import java.lang.reflect.Type;
+import java.text.DateFormat;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import junit.framework.TestCase;
+
+/**
+ * Unit tests for {@link Gson}.
+ *
+ * @author Ryan Harter
+ */
+public final class GsonTest extends TestCase {
+
+  private static final Excluder CUSTOM_EXCLUDER = Excluder.DEFAULT
+      .excludeFieldsWithoutExposeAnnotation()
+      .disableInnerClassSerialization();
+
+  private static final FieldNamingStrategy CUSTOM_FIELD_NAMING_STRATEGY = new FieldNamingStrategy() {
+    @Override public String translateName(Field f) {
+      return "foo";
+    }
+  };
+
+  private static final ToNumberStrategy CUSTOM_OBJECT_TO_NUMBER_STRATEGY = ToNumberPolicy.DOUBLE;
+  private static final ToNumberStrategy CUSTOM_NUMBER_TO_NUMBER_STRATEGY = ToNumberPolicy.LAZILY_PARSED_NUMBER;
+
+  public void testOverridesDefaultExcluder() {
+    Gson gson = new Gson(CUSTOM_EXCLUDER, CUSTOM_FIELD_NAMING_STRATEGY,
+        new HashMap<Type, InstanceCreator<?>>(), true, false, true, false,
+        true, true, false, true, LongSerializationPolicy.DEFAULT, null, DateFormat.DEFAULT,
+        DateFormat.DEFAULT, new ArrayList<TypeAdapterFactory>(),
+        new ArrayList<TypeAdapterFactory>(), new ArrayList<TypeAdapterFactory>(),
+        CUSTOM_OBJECT_TO_NUMBER_STRATEGY, CUSTOM_NUMBER_TO_NUMBER_STRATEGY,
+        Collections.<ReflectionAccessFilter>emptyList());
+
+    assertEquals(CUSTOM_EXCLUDER, gson.excluder);
+    assertEquals(CUSTOM_FIELD_NAMING_STRATEGY, gson.fieldNamingStrategy());
+    assertEquals(true, gson.serializeNulls());
+    assertEquals(false, gson.htmlSafe());
+  }
+
+  public void testClonedTypeAdapterFactoryListsAreIndependent() {
+    Gson original = new Gson(CUSTOM_EXCLUDER, CUSTOM_FIELD_NAMING_STRATEGY,
+        new HashMap<Type, InstanceCreator<?>>(), true, false, true, false,
+        true, true, false, true, LongSerializationPolicy.DEFAULT, null, DateFormat.DEFAULT,
+        DateFormat.DEFAULT, new ArrayList<TypeAdapterFactory>(),
+        new ArrayList<TypeAdapterFactory>(), new ArrayList<TypeAdapterFactory>(),
+        CUSTOM_OBJECT_TO_NUMBER_STRATEGY, CUSTOM_NUMBER_TO_NUMBER_STRATEGY,
+        Collections.<ReflectionAccessFilter>emptyList());
+
+    Gson clone = original.newBuilder()
+        .registerTypeAdapter(Object.class, new TestTypeAdapter())
+        .create();
+
+    assertEquals(original.factories.size() + 1, clone.factories.size());
+  }
+
+  private static final class TestTypeAdapter extends TypeAdapter<Object> {
+    @Override public void write(JsonWriter out, Object value) throws IOException {
+      // Test stub.
+    }
+    @Override public Object read(JsonReader in) throws IOException { return null; }
+  }
+
+  public void testNewJsonWriter_Default() throws IOException {
+    StringWriter writer = new StringWriter();
+    JsonWriter jsonWriter = new Gson().newJsonWriter(writer);
+    jsonWriter.beginObject();
+    jsonWriter.name("test");
+    jsonWriter.nullValue();
+    jsonWriter.name("<test2");
+    jsonWriter.value(true);
+    jsonWriter.endObject();
+
+    try {
+      // Additional top-level value
+      jsonWriter.value(1);
+      fail();
+    } catch (IllegalStateException expected) {
+      assertEquals("JSON must have only one top-level value.", expected.getMessage());
+    }
+
+    jsonWriter.close();
+    assertEquals("{\"\\u003ctest2\":true}", writer.toString());
+  }
+
+  public void testNewJsonWriter_Custom() throws IOException {
+    StringWriter writer = new StringWriter();
+    JsonWriter jsonWriter = new GsonBuilder()
+      .disableHtmlEscaping()
+      .generateNonExecutableJson()
+      .setPrettyPrinting()
+      .serializeNulls()
+      .setLenient()
+      .create()
+      .newJsonWriter(writer);
+    jsonWriter.beginObject();
+    jsonWriter.name("test");
+    jsonWriter.nullValue();
+    jsonWriter.name("<test2");
+    jsonWriter.value(true);
+    jsonWriter.endObject();
+
+    // Additional top-level value
+    jsonWriter.value(1);
+
+    jsonWriter.close();
+    assertEquals(")]}'\n{\n  \"test\": null,\n  \"<test2\": true\n}1", writer.toString());
+  }
+
+  public void testNewJsonReader_Default() throws IOException {
+    String json = "test"; // String without quotes
+    JsonReader jsonReader = new Gson().newJsonReader(new StringReader(json));
+    try {
+      jsonReader.nextString();
+      fail();
+    } catch (MalformedJsonException expected) {
+    }
+    jsonReader.close();
+  }
+
+  public void testNewJsonReader_Custom() throws IOException {
+    String json = "test"; // String without quotes
+    JsonReader jsonReader = new GsonBuilder()
+      .setLenient()
+      .create()
+      .newJsonReader(new StringReader(json));
+    assertEquals("test", jsonReader.nextString());
+    jsonReader.close();
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/GsonTypeAdapterTest.java b/gson/src/test/java/com/google/gson/GsonTypeAdapterTest.java
new file mode 100644
index 0000000..2e00dc9
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/GsonTypeAdapterTest.java
@@ -0,0 +1,148 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import java.lang.reflect.Type;
+import java.math.BigInteger;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
+import junit.framework.TestCase;
+
+/**
+ * Contains numerous tests involving registered type converters with a Gson instance.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public class GsonTypeAdapterTest extends TestCase {
+  private Gson gson;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    gson = new GsonBuilder()
+        .registerTypeAdapter(AtomicLong.class, new ExceptionTypeAdapter())
+        .registerTypeAdapter(AtomicInteger.class, new AtomicIntegerTypeAdapter())
+        .create();
+  }
+
+  public void testDefaultTypeAdapterThrowsParseException() throws Exception {
+    try {
+      gson.fromJson("{\"abc\":123}", BigInteger.class);
+      fail("Should have thrown a JsonParseException");
+    } catch (JsonParseException expected) { }
+  }
+
+  public void testTypeAdapterThrowsException() throws Exception {
+    try {
+      gson.toJson(new AtomicLong(0));
+      fail("Type Adapter should have thrown an exception");
+    } catch (IllegalStateException expected) { }
+
+    try {
+      gson.fromJson("123", AtomicLong.class);
+      fail("Type Adapter should have thrown an exception");
+    } catch (JsonParseException expected) { }
+  }
+
+  public void testTypeAdapterProperlyConvertsTypes() throws Exception {
+    int intialValue = 1;
+    AtomicInteger atomicInt = new AtomicInteger(intialValue);
+    String json = gson.toJson(atomicInt);
+    assertEquals(intialValue + 1, Integer.parseInt(json));
+
+    atomicInt = gson.fromJson(json, AtomicInteger.class);
+    assertEquals(intialValue, atomicInt.get());
+  }
+
+  public void testTypeAdapterDoesNotAffectNonAdaptedTypes() throws Exception {
+    String expected = "blah";
+    String actual = gson.toJson(expected);
+    assertEquals("\"" + expected + "\"", actual);
+
+    actual = gson.fromJson(actual, String.class);
+    assertEquals(expected, actual);
+  }
+
+  private static class ExceptionTypeAdapter
+      implements JsonSerializer<AtomicLong>, JsonDeserializer<AtomicLong> {
+    @Override public JsonElement serialize(
+        AtomicLong src, Type typeOfSrc, JsonSerializationContext context) {
+      throw new IllegalStateException();
+    }
+    @Override public AtomicLong deserialize(
+        JsonElement json, Type typeOfT, JsonDeserializationContext context)
+        throws JsonParseException {
+      throw new IllegalStateException();
+    }
+  }
+
+  private static class AtomicIntegerTypeAdapter
+      implements JsonSerializer<AtomicInteger>, JsonDeserializer<AtomicInteger> {
+    @Override public JsonElement serialize(AtomicInteger src, Type typeOfSrc, JsonSerializationContext context) {
+      return new JsonPrimitive(src.incrementAndGet());
+    }
+
+    @Override public AtomicInteger deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
+        throws JsonParseException {
+      int intValue = json.getAsInt();
+      return new AtomicInteger(--intValue);
+    }
+  }
+
+  static abstract class Abstract {
+    String a;
+  }
+
+  static class Concrete extends Abstract {
+    String b;
+  }
+
+  // https://groups.google.com/d/topic/google-gson/EBmOCa8kJPE/discussion
+  public void testDeserializerForAbstractClass() {
+    Concrete instance = new Concrete();
+    instance.a = "android";
+    instance.b = "beep";
+    assertSerialized("{\"a\":\"android\"}", Abstract.class, true, true, instance);
+    assertSerialized("{\"a\":\"android\"}", Abstract.class, true, false, instance);
+    assertSerialized("{\"a\":\"android\"}", Abstract.class, false, true, instance);
+    assertSerialized("{\"a\":\"android\"}", Abstract.class, false, false, instance);
+    assertSerialized("{\"b\":\"beep\",\"a\":\"android\"}", Concrete.class, true, true, instance);
+    assertSerialized("{\"b\":\"beep\",\"a\":\"android\"}", Concrete.class, true, false, instance);
+    assertSerialized("{\"b\":\"beep\",\"a\":\"android\"}", Concrete.class, false, true, instance);
+    assertSerialized("{\"b\":\"beep\",\"a\":\"android\"}", Concrete.class, false, false, instance);
+  }
+
+  private void assertSerialized(String expected, Class<?> instanceType, boolean registerAbstractDeserializer,
+      boolean registerAbstractHierarchyDeserializer, Object instance) {
+    JsonDeserializer<Abstract> deserializer = new JsonDeserializer<Abstract>() {
+      @Override public Abstract deserialize(JsonElement json, Type typeOfT,
+          JsonDeserializationContext context) throws JsonParseException {
+        throw new AssertionError();
+      }
+    };
+    GsonBuilder builder = new GsonBuilder();
+    if (registerAbstractDeserializer) {
+      builder.registerTypeAdapter(Abstract.class, deserializer);
+    }
+    if (registerAbstractHierarchyDeserializer) {
+      builder.registerTypeHierarchyAdapter(Abstract.class, deserializer);
+    }
+    Gson gson = builder.create();
+    assertEquals(expected, gson.toJson(instance, instanceType));
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/InnerClassExclusionStrategyTest.java b/gson/src/test/java/com/google/gson/InnerClassExclusionStrategyTest.java
new file mode 100644
index 0000000..86f7a62
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/InnerClassExclusionStrategyTest.java
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import com.google.gson.internal.Excluder;
+import java.lang.reflect.Field;
+import junit.framework.TestCase;
+
+/**
+ * Unit test for GsonBuilder.EXCLUDE_INNER_CLASSES.
+ *
+ * @author Joel Leitch
+ */
+public class InnerClassExclusionStrategyTest extends TestCase {
+  public InnerClass innerClass = new InnerClass();
+  public StaticNestedClass staticNestedClass = new StaticNestedClass();
+  private Excluder excluder = Excluder.DEFAULT.disableInnerClassSerialization();
+
+  public void testExcludeInnerClassObject() throws Exception {
+    Class<?> clazz = innerClass.getClass();
+    assertTrue(excluder.excludeClass(clazz, true));
+  }
+
+  public void testExcludeInnerClassField() throws Exception {
+    Field f = getClass().getField("innerClass");
+    assertTrue(excluder.excludeField(f, true));
+  }
+
+  public void testIncludeStaticNestedClassObject() throws Exception {
+    Class<?> clazz = staticNestedClass.getClass();
+    assertFalse(excluder.excludeClass(clazz, true));
+  }
+
+  public void testIncludeStaticNestedClassField() throws Exception {
+    Field f = getClass().getField("staticNestedClass");
+    assertFalse(excluder.excludeField(f, true));
+  }
+
+  class InnerClass {
+  }
+
+  static class StaticNestedClass {
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/JavaSerializationTest.java b/gson/src/test/java/com/google/gson/JavaSerializationTest.java
new file mode 100644
index 0000000..90da3e8
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/JavaSerializationTest.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright (C) 2012 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import com.google.gson.reflect.TypeToken;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import junit.framework.TestCase;
+
+/**
+ * Check that Gson doesn't return non-serializable data types.
+ *
+ * @author Jesse Wilson
+ */
+public final class JavaSerializationTest extends TestCase {
+  private final Gson gson = new Gson();
+
+  public void testMapIsSerializable() throws Exception {
+    Type type = new TypeToken<Map<String, Integer>>() {}.getType();
+    Map<String, Integer> map = gson.fromJson("{\"b\":1,\"c\":2,\"a\":3}", type);
+    Map<String, Integer> serialized = serializedCopy(map);
+    assertEquals(map, serialized);
+    // Also check that the iteration order is retained.
+    assertEquals(Arrays.asList("b", "c", "a"), new ArrayList<>(serialized.keySet()));
+  }
+
+  public void testListIsSerializable() throws Exception {
+    Type type = new TypeToken<List<String>>() {}.getType();
+    List<String> list = gson.fromJson("[\"a\",\"b\",\"c\"]", type);
+    List<String> serialized = serializedCopy(list);
+    assertEquals(list, serialized);
+  }
+
+  public void testNumberIsSerializable() throws Exception {
+    Type type = new TypeToken<List<Number>>() {}.getType();
+    List<Number> list = gson.fromJson("[1,3.14,6.673e-11]", type);
+    List<Number> serialized = serializedCopy(list);
+    assertEquals(1.0, serialized.get(0).doubleValue());
+    assertEquals(3.14, serialized.get(1).doubleValue());
+    assertEquals(6.673e-11, serialized.get(2).doubleValue());
+  }
+
+  @SuppressWarnings("unchecked") // Serialization promises to return the same type.
+  private <T> T serializedCopy(T object) throws IOException, ClassNotFoundException {
+    ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
+    ObjectOutputStream out = new ObjectOutputStream(bytesOut);
+    out.writeObject(object);
+    out.close();
+    ByteArrayInputStream bytesIn = new ByteArrayInputStream(bytesOut.toByteArray());
+    ObjectInputStream in = new ObjectInputStream(bytesIn);
+    return (T) in.readObject();
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/JsonArrayTest.java b/gson/src/test/java/com/google/gson/JsonArrayTest.java
new file mode 100644
index 0000000..3975ce2
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/JsonArrayTest.java
@@ -0,0 +1,165 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import com.google.gson.common.MoreAsserts;
+import junit.framework.TestCase;
+
+/**
+ * @author Jesse Wilson
+ */
+public final class JsonArrayTest extends TestCase {
+
+  public void testEqualsOnEmptyArray() {
+    MoreAsserts.assertEqualsAndHashCode(new JsonArray(), new JsonArray());
+  }
+
+  public void testEqualsNonEmptyArray() {
+    JsonArray a = new JsonArray();
+    JsonArray b = new JsonArray();
+
+    assertEquals(a, a);
+
+    a.add(new JsonObject());
+    assertFalse(a.equals(b));
+    assertFalse(b.equals(a));
+
+    b.add(new JsonObject());
+    MoreAsserts.assertEqualsAndHashCode(a, b);
+
+    a.add(new JsonObject());
+    assertFalse(a.equals(b));
+    assertFalse(b.equals(a));
+
+    b.add(JsonNull.INSTANCE);
+    assertFalse(a.equals(b));
+    assertFalse(b.equals(a));
+  }
+
+  public void testRemove() {
+    JsonArray array = new JsonArray();
+    try {
+      array.remove(0);
+      fail();
+    } catch (IndexOutOfBoundsException expected) {}
+    JsonPrimitive a = new JsonPrimitive("a");
+    array.add(a);
+    assertTrue(array.remove(a));
+    assertFalse(array.contains(a));
+    array.add(a);
+    array.add(new JsonPrimitive("b"));
+    assertEquals("b", array.remove(1).getAsString());
+    assertEquals(1, array.size());
+    assertTrue(array.contains(a));
+  }
+
+  public void testSet() {
+    JsonArray array = new JsonArray();
+    try {
+      array.set(0, new JsonPrimitive(1));
+      fail();
+    } catch (IndexOutOfBoundsException expected) {}
+    JsonPrimitive a = new JsonPrimitive("a");
+    array.add(a);
+    array.set(0, new JsonPrimitive("b"));
+    assertEquals("b", array.get(0).getAsString());
+    array.set(0, null);
+    assertNull(array.get(0));
+    array.set(0, new JsonPrimitive("c"));
+    assertEquals("c", array.get(0).getAsString());
+    assertEquals(1, array.size());
+  }
+
+  public void testDeepCopy() {
+    JsonArray original = new JsonArray();
+    JsonArray firstEntry = new JsonArray();
+    original.add(firstEntry);
+
+    JsonArray copy = original.deepCopy();
+    original.add(new JsonPrimitive("y"));
+
+    assertEquals(1, copy.size());
+    firstEntry.add(new JsonPrimitive("z"));
+
+    assertEquals(1, original.get(0).getAsJsonArray().size());
+    assertEquals(0, copy.get(0).getAsJsonArray().size());
+  }
+
+  public void testFailedGetArrayValues() {
+    JsonArray jsonArray = new JsonArray();
+    jsonArray.add(JsonParser.parseString("{" + "\"key1\":\"value1\"," + "\"key2\":\"value2\"," + "\"key3\":\"value3\"," + "\"key4\":\"value4\"" + "}"));
+    try {
+      jsonArray.getAsBoolean();
+      fail("expected getBoolean to fail");
+    } catch (UnsupportedOperationException e) {
+      assertEquals("Expected an exception message",
+              "JsonObject", e.getMessage());
+    }
+    try {
+      jsonArray.get(-1);
+      fail("expected get to fail");
+    } catch (IndexOutOfBoundsException e) {
+      assertEquals("Expected an exception message",
+              "Index -1 out of bounds for length 1", e.getMessage());
+    }
+    try {
+      jsonArray.getAsString();
+      fail("expected getString to fail");
+    } catch (UnsupportedOperationException e) {
+      assertEquals("Expected an exception message",
+              "JsonObject", e.getMessage());
+    }
+
+    jsonArray.remove(0);
+    jsonArray.add("hello");
+    try {
+      jsonArray.getAsDouble();
+      fail("expected getDouble to fail");
+    } catch (NumberFormatException e) {
+      assertEquals("Expected an exception message",
+              "For input string: \"hello\"", e.getMessage());
+    }
+    try {
+      jsonArray.getAsInt();
+      fail("expected getInt to fail");
+    } catch (NumberFormatException e) {
+      assertEquals("Expected an exception message",
+              "For input string: \"hello\"", e.getMessage());
+    }
+    try {
+      jsonArray.get(0).getAsJsonArray();
+      fail("expected getJSONArray to fail");
+    } catch (IllegalStateException e) {
+      assertEquals("Expected an exception message",
+              "Not a JSON Array: \"hello\"", e.getMessage());
+    }
+    try {
+      jsonArray.getAsJsonObject();
+      fail("expected getJSONObject to fail");
+    } catch (IllegalStateException e) {
+      assertEquals("Expected an exception message",
+              "Not a JSON Object: [\"hello\"]", e.getMessage());
+    }
+    try {
+      jsonArray.getAsLong();
+      fail("expected getLong to fail");
+    } catch (NumberFormatException e) {
+      assertEquals("Expected an exception message",
+              "For input string: \"hello\"", e.getMessage());
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/JsonNullTest.java b/gson/src/test/java/com/google/gson/JsonNullTest.java
new file mode 100644
index 0000000..6157e38
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/JsonNullTest.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import com.google.gson.common.MoreAsserts;
+import junit.framework.TestCase;
+
+/**
+ * @author Jesse Wilson
+ */
+public final class JsonNullTest extends TestCase {
+
+  @SuppressWarnings("deprecation")
+  public void testEqualsAndHashcode() {
+    MoreAsserts.assertEqualsAndHashCode(new JsonNull(), new JsonNull());
+    MoreAsserts.assertEqualsAndHashCode(new JsonNull(), JsonNull.INSTANCE);
+    MoreAsserts.assertEqualsAndHashCode(JsonNull.INSTANCE, JsonNull.INSTANCE);
+  }
+
+  public void testDeepCopy() {
+    @SuppressWarnings("deprecation")
+    JsonNull a = new JsonNull();
+    assertSame(JsonNull.INSTANCE, a.deepCopy());
+    assertSame(JsonNull.INSTANCE, JsonNull.INSTANCE.deepCopy());
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/JsonObjectTest.java b/gson/src/test/java/com/google/gson/JsonObjectTest.java
new file mode 100644
index 0000000..6f5274f
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/JsonObjectTest.java
@@ -0,0 +1,204 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import com.google.gson.common.MoreAsserts;
+
+import junit.framework.TestCase;
+
+/**
+ * Unit test for the {@link JsonObject} class.
+ *
+ * @author Joel Leitch
+ */
+public class JsonObjectTest extends TestCase {
+
+  public void testAddingAndRemovingObjectProperties() throws Exception {
+    JsonObject jsonObj = new JsonObject();
+    String propertyName = "property";
+    assertFalse(jsonObj.has(propertyName));
+    assertNull(jsonObj.get(propertyName));
+
+    JsonPrimitive value = new JsonPrimitive("blah");
+    jsonObj.add(propertyName, value);
+    assertEquals(value, jsonObj.get(propertyName));
+
+    JsonElement removedElement = jsonObj.remove(propertyName);
+    assertEquals(value, removedElement);
+    assertFalse(jsonObj.has(propertyName));
+    assertNull(jsonObj.get(propertyName));
+  }
+
+  public void testAddingNullPropertyValue() throws Exception {
+    String propertyName = "property";
+    JsonObject jsonObj = new JsonObject();
+    jsonObj.add(propertyName, null);
+
+    assertTrue(jsonObj.has(propertyName));
+
+    JsonElement jsonElement = jsonObj.get(propertyName);
+    assertNotNull(jsonElement);
+    assertTrue(jsonElement.isJsonNull());
+  }
+
+  public void testAddingNullOrEmptyPropertyName() throws Exception {
+    JsonObject jsonObj = new JsonObject();
+    try {
+      jsonObj.add(null, JsonNull.INSTANCE);
+      fail("Should not allow null property names.");
+    } catch (NullPointerException expected) { }
+
+    jsonObj.add("", JsonNull.INSTANCE);
+    jsonObj.add("   \t", JsonNull.INSTANCE);
+  }
+
+  public void testAddingBooleanProperties() throws Exception {
+    String propertyName = "property";
+    JsonObject jsonObj = new JsonObject();
+    jsonObj.addProperty(propertyName, true);
+
+    assertTrue(jsonObj.has(propertyName));
+
+    JsonElement jsonElement = jsonObj.get(propertyName);
+    assertNotNull(jsonElement);
+    assertTrue(jsonElement.getAsBoolean());
+  }
+
+  public void testAddingStringProperties() throws Exception {
+    String propertyName = "property";
+    String value = "blah";
+
+    JsonObject jsonObj = new JsonObject();
+    jsonObj.addProperty(propertyName, value);
+
+    assertTrue(jsonObj.has(propertyName));
+
+    JsonElement jsonElement = jsonObj.get(propertyName);
+    assertNotNull(jsonElement);
+    assertEquals(value, jsonElement.getAsString());
+  }
+
+  public void testAddingCharacterProperties() throws Exception {
+    String propertyName = "property";
+    char value = 'a';
+
+    JsonObject jsonObj = new JsonObject();
+    jsonObj.addProperty(propertyName, value);
+
+    assertTrue(jsonObj.has(propertyName));
+
+    JsonElement jsonElement = jsonObj.get(propertyName);
+    assertNotNull(jsonElement);
+    assertEquals(String.valueOf(value), jsonElement.getAsString());
+
+    @SuppressWarnings("deprecation")
+    char character = jsonElement.getAsCharacter();
+    assertEquals(value, character);
+  }
+
+  /**
+   * From bug report http://code.google.com/p/google-gson/issues/detail?id=182
+   */
+  public void testPropertyWithQuotes() {
+    JsonObject jsonObj = new JsonObject();
+    jsonObj.add("a\"b", new JsonPrimitive("c\"d"));
+    String json = new Gson().toJson(jsonObj);
+    assertEquals("{\"a\\\"b\":\"c\\\"d\"}", json);
+  }
+
+  /**
+   * From issue 227.
+   */
+  public void testWritePropertyWithEmptyStringName() {
+    JsonObject jsonObj = new JsonObject();
+    jsonObj.add("", new JsonPrimitive(true));
+    assertEquals("{\"\":true}", new Gson().toJson(jsonObj));
+
+  }
+
+  public void testReadPropertyWithEmptyStringName() {
+    JsonObject jsonObj = JsonParser.parseString("{\"\":true}").getAsJsonObject();
+    assertEquals(true, jsonObj.get("").getAsBoolean());
+  }
+
+  public void testEqualsOnEmptyObject() {
+    MoreAsserts.assertEqualsAndHashCode(new JsonObject(), new JsonObject());
+  }
+
+  public void testEqualsNonEmptyObject() {
+    JsonObject a = new JsonObject();
+    JsonObject b = new JsonObject();
+
+    assertEquals(a, a);
+
+    a.add("foo", new JsonObject());
+    assertFalse(a.equals(b));
+    assertFalse(b.equals(a));
+
+    b.add("foo", new JsonObject());
+    MoreAsserts.assertEqualsAndHashCode(a, b);
+
+    a.add("bar", new JsonObject());
+    assertFalse(a.equals(b));
+    assertFalse(b.equals(a));
+
+    b.add("bar", JsonNull.INSTANCE);
+    assertFalse(a.equals(b));
+    assertFalse(b.equals(a));
+  }
+
+  public void testSize() {
+    JsonObject o = new JsonObject();
+    assertEquals(0, o.size());
+
+    o.add("Hello", new JsonPrimitive(1));
+    assertEquals(1, o.size());
+
+    o.add("Hi", new JsonPrimitive(1));
+    assertEquals(2, o.size());
+
+    o.remove("Hello");
+    assertEquals(1, o.size());
+  }
+
+  public void testDeepCopy() {
+    JsonObject original = new JsonObject();
+    JsonArray firstEntry = new JsonArray();
+    original.add("key", firstEntry);
+
+    JsonObject copy = original.deepCopy();
+    firstEntry.add(new JsonPrimitive("z"));
+
+    assertEquals(1, original.get("key").getAsJsonArray().size());
+    assertEquals(0, copy.get("key").getAsJsonArray().size());
+  }
+
+  /**
+   * From issue 941
+   */
+  public void testKeySet() {
+    JsonObject a = new JsonObject();
+
+    a.add("foo", new JsonArray());
+    a.add("bar", new JsonObject());
+
+    assertEquals(2, a.size());
+    assertEquals(2, a.keySet().size());
+    assertTrue(a.keySet().contains("foo"));
+    assertTrue(a.keySet().contains("bar"));
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/JsonParserParameterizedTest.java b/gson/src/test/java/com/google/gson/JsonParserParameterizedTest.java
new file mode 100644
index 0000000..8671fd8
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/JsonParserParameterizedTest.java
@@ -0,0 +1,41 @@
+package com.google.gson;
+
+import static org.junit.Assert.assertEquals;
+
+import java.io.IOException;
+import java.util.Arrays;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.junit.runners.Parameterized.Parameter;
+import org.junit.runners.Parameterized.Parameters;
+
+@RunWith(Parameterized.class)
+public class JsonParserParameterizedTest {
+  @Parameters
+  public static Iterable<String> data() {
+    return Arrays.asList(
+      "[]",
+      "{}",
+      "null",
+      "1.0",
+      "true",
+      "\"string\"",
+      "[true,1.0,null,{},2.0,{\"a\":[false]},[3.0,\"test\"],4.0]",
+      "{\"\":1.0,\"a\":true,\"b\":null,\"c\":[],\"d\":{\"a1\":2.0,\"b2\":[true,{\"a3\":3.0}]},\"e\":[{\"f\":4.0},\"test\"]}"
+    );
+  }
+
+  private final TypeAdapter<JsonElement> adapter = new Gson().getAdapter(JsonElement.class);
+  @Parameter
+  public String json;
+
+  @Test
+  public void testParse() throws IOException {
+    JsonElement deserialized = JsonParser.parseString(json);
+    String actualSerialized = adapter.toJson(deserialized);
+
+    // Serialized JsonElement should be the same as original JSON
+    assertEquals(json, actualSerialized);
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/JsonParserTest.java b/gson/src/test/java/com/google/gson/JsonParserTest.java
new file mode 100644
index 0000000..a05aa32
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/JsonParserTest.java
@@ -0,0 +1,167 @@
+/*
+ * Copyright (C) 2009 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import java.io.CharArrayReader;
+import java.io.CharArrayWriter;
+import java.io.IOException;
+import java.io.StringReader;
+import junit.framework.TestCase;
+
+import com.google.gson.common.TestTypes.BagOfPrimitives;
+import com.google.gson.internal.Streams;
+import com.google.gson.stream.JsonReader;
+
+/**
+ * Unit test for {@link JsonParser}
+ *
+ * @author Inderjeet Singh
+ */
+public class JsonParserTest extends TestCase {
+
+  public void testParseInvalidJson() {
+    try {
+      JsonParser.parseString("[[]");
+      fail();
+    } catch (JsonSyntaxException expected) { }
+  }
+
+  public void testParseUnquotedStringArrayFails() {
+    JsonElement element = JsonParser.parseString("[a,b,c]");
+    assertEquals("a", element.getAsJsonArray().get(0).getAsString());
+    assertEquals("b", element.getAsJsonArray().get(1).getAsString());
+    assertEquals("c", element.getAsJsonArray().get(2).getAsString());
+    assertEquals(3, element.getAsJsonArray().size());
+  }
+
+  public void testParseString() {
+    String json = "{a:10,b:'c'}";
+    JsonElement e = JsonParser.parseString(json);
+    assertTrue(e.isJsonObject());
+    assertEquals(10, e.getAsJsonObject().get("a").getAsInt());
+    assertEquals("c", e.getAsJsonObject().get("b").getAsString());
+  }
+
+  public void testParseEmptyString() {
+    JsonElement e = JsonParser.parseString("\"   \"");
+    assertTrue(e.isJsonPrimitive());
+    assertEquals("   ", e.getAsString());
+  }
+
+  public void testParseEmptyWhitespaceInput() {
+    JsonElement e = JsonParser.parseString("     ");
+    assertTrue(e.isJsonNull());
+  }
+
+  public void testParseUnquotedSingleWordStringFails() {
+    assertEquals("Test", JsonParser.parseString("Test").getAsString());
+  }
+
+  public void testParseUnquotedMultiWordStringFails() {
+    String unquotedSentence = "Test is a test..blah blah";
+    try {
+      JsonParser.parseString(unquotedSentence);
+      fail();
+    } catch (JsonSyntaxException expected) { }
+  }
+
+  public void testParseMixedArray() {
+    String json = "[{},13,\"stringValue\"]";
+    JsonElement e = JsonParser.parseString(json);
+    assertTrue(e.isJsonArray());
+
+    JsonArray  array = e.getAsJsonArray();
+    assertEquals("{}", array.get(0).toString());
+    assertEquals(13, array.get(1).getAsInt());
+    assertEquals("stringValue", array.get(2).getAsString());
+  }
+
+  private static String repeat(String s, int times) {
+    StringBuilder stringBuilder = new StringBuilder(s.length() * times);
+    for (int i = 0; i < times; i++) {
+      stringBuilder.append(s);
+    }
+    return stringBuilder.toString();
+  }
+
+  /** Deeply nested JSON arrays should not cause {@link StackOverflowError} */
+  public void testParseDeeplyNestedArrays() throws IOException {
+    int times = 10000;
+    // [[[ ... ]]]
+    String json = repeat("[", times) + repeat("]", times);
+
+    int actualTimes = 0;
+    JsonArray current = JsonParser.parseString(json).getAsJsonArray();
+    while (true) {
+      actualTimes++;
+      if (current.isEmpty()) {
+        break;
+      }
+      assertEquals(1, current.size());
+      current = current.get(0).getAsJsonArray();
+    }
+    assertEquals(times, actualTimes);
+  }
+
+  /** Deeply nested JSON objects should not cause {@link StackOverflowError} */
+  public void testParseDeeplyNestedObjects() throws IOException {
+    int times = 10000;
+    // {"a":{"a": ... {"a":null} ... }}
+    String json = repeat("{\"a\":", times) + "null" + repeat("}", times);
+
+    int actualTimes = 0;
+    JsonObject current = JsonParser.parseString(json).getAsJsonObject();
+    while (true) {
+      assertEquals(1, current.size());
+      actualTimes++;
+      JsonElement next = current.get("a");
+      if (next.isJsonNull()) {
+        break;
+      } else {
+        current = next.getAsJsonObject();
+      }
+    }
+    assertEquals(times, actualTimes);
+  }
+
+  public void testParseReader() {
+    StringReader reader = new StringReader("{a:10,b:'c'}");
+    JsonElement e = JsonParser.parseReader(reader);
+    assertTrue(e.isJsonObject());
+    assertEquals(10, e.getAsJsonObject().get("a").getAsInt());
+    assertEquals("c", e.getAsJsonObject().get("b").getAsString());
+  }
+
+  public void testReadWriteTwoObjects() throws Exception {
+    Gson gson = new Gson();
+    CharArrayWriter writer = new CharArrayWriter();
+    BagOfPrimitives expectedOne = new BagOfPrimitives(1, 1, true, "one");
+    writer.write(gson.toJson(expectedOne).toCharArray());
+    BagOfPrimitives expectedTwo = new BagOfPrimitives(2, 2, false, "two");
+    writer.write(gson.toJson(expectedTwo).toCharArray());
+    CharArrayReader reader = new CharArrayReader(writer.toCharArray());
+
+    JsonReader parser = new JsonReader(reader);
+    parser.setLenient(true);
+    JsonElement element1 = Streams.parse(parser);
+    JsonElement element2 = Streams.parse(parser);
+    BagOfPrimitives actualOne = gson.fromJson(element1, BagOfPrimitives.class);
+    assertEquals("one", actualOne.stringValue);
+    BagOfPrimitives actualTwo = gson.fromJson(element2, BagOfPrimitives.class);
+    assertEquals("two", actualTwo.stringValue);
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/JsonPrimitiveTest.java b/gson/src/test/java/com/google/gson/JsonPrimitiveTest.java
new file mode 100644
index 0000000..cdd4fdb
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/JsonPrimitiveTest.java
@@ -0,0 +1,274 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import com.google.gson.common.MoreAsserts;
+
+import junit.framework.TestCase;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+
+/**
+ * Unit test for the {@link JsonPrimitive} class.
+ *
+ * @author Joel Leitch
+ */
+public class JsonPrimitiveTest extends TestCase {
+
+  @SuppressWarnings("unused")
+  public void testNulls() {
+    try {
+      new JsonPrimitive((Boolean) null);
+      fail();
+    } catch (NullPointerException ignored) {
+    }
+    try {
+      new JsonPrimitive((Number) null);
+      fail();
+    } catch (NullPointerException ignored) {
+    }
+    try {
+      new JsonPrimitive((String) null);
+      fail();
+    } catch (NullPointerException ignored) {
+    }
+    try {
+      new JsonPrimitive((Character) null);
+      fail();
+    } catch (NullPointerException ignored) {
+    }
+  }
+
+  public void testBoolean() throws Exception {
+    JsonPrimitive json = new JsonPrimitive(Boolean.TRUE);
+
+    assertTrue(json.isBoolean());
+    assertTrue(json.getAsBoolean());
+
+    // Extra support for booleans
+    json = new JsonPrimitive(1);
+    assertFalse(json.getAsBoolean());
+
+    json = new JsonPrimitive("1");
+    assertFalse(json.getAsBoolean());
+
+    json = new JsonPrimitive("true");
+    assertTrue(json.getAsBoolean());
+
+    json = new JsonPrimitive("TrUe");
+    assertTrue(json.getAsBoolean());
+
+    json = new JsonPrimitive("1.3");
+    assertFalse(json.getAsBoolean());
+  }
+
+  public void testParsingStringAsBoolean() throws Exception {
+    JsonPrimitive json = new JsonPrimitive("true");
+
+    assertFalse(json.isBoolean());
+    assertTrue(json.getAsBoolean());
+  }
+
+  public void testParsingStringAsNumber() throws Exception {
+    JsonPrimitive json = new JsonPrimitive("1");
+
+    assertFalse(json.isNumber());
+    assertEquals(1D, json.getAsDouble(), 0.00001);
+    assertEquals(1F, json.getAsFloat(), 0.00001);
+    assertEquals(1, json.getAsInt());
+    assertEquals(1L, json.getAsLong());
+    assertEquals((short) 1, json.getAsShort());
+    assertEquals((byte) 1, json.getAsByte());
+    assertEquals(new BigInteger("1"), json.getAsBigInteger());
+    assertEquals(new BigDecimal("1"), json.getAsBigDecimal());
+  }
+
+  public void testStringsAndChar() throws Exception {
+    JsonPrimitive json = new JsonPrimitive("abc");
+    assertTrue(json.isString());
+    assertEquals('a', json.getAsCharacter());
+    assertEquals("abc", json.getAsString());
+
+    json = new JsonPrimitive('z');
+    assertTrue(json.isString());
+    assertEquals('z', json.getAsCharacter());
+    assertEquals("z", json.getAsString());
+
+    json = new JsonPrimitive(true);
+    assertEquals("true", json.getAsString());
+  }
+
+  public void testExponential() throws Exception {
+    JsonPrimitive json = new JsonPrimitive("1E+7");
+
+    assertEquals(new BigDecimal("1E+7"), json.getAsBigDecimal());
+    assertEquals(1E+7, json.getAsDouble(), 0.00001);
+    assertEquals(1E+7, json.getAsDouble(), 0.00001);
+
+    try {
+      json.getAsInt();
+      fail("Integers can not handle exponents like this.");
+    } catch (NumberFormatException expected) { }
+  }
+
+  public void testByteEqualsShort() {
+    JsonPrimitive p1 = new JsonPrimitive(Byte.valueOf((byte)10));
+    JsonPrimitive p2 = new JsonPrimitive(Short.valueOf((short)10));
+    assertEquals(p1, p2);
+    assertEquals(p1.hashCode(), p2.hashCode());
+  }
+
+  public void testByteEqualsInteger() {
+    JsonPrimitive p1 = new JsonPrimitive(Byte.valueOf((byte)10));
+    JsonPrimitive p2 = new JsonPrimitive(Integer.valueOf(10));
+    assertEquals(p1, p2);
+    assertEquals(p1.hashCode(), p2.hashCode());
+  }
+
+  public void testByteEqualsLong() {
+    JsonPrimitive p1 = new JsonPrimitive(Byte.valueOf((byte)10));
+    JsonPrimitive p2 = new JsonPrimitive(Long.valueOf(10L));
+    assertEquals(p1, p2);
+    assertEquals(p1.hashCode(), p2.hashCode());
+  }
+
+  public void testByteEqualsBigInteger() {
+    JsonPrimitive p1 = new JsonPrimitive(Byte.valueOf((byte)10));
+    JsonPrimitive p2 = new JsonPrimitive(new BigInteger("10"));
+    assertEquals(p1, p2);
+    assertEquals(p1.hashCode(), p2.hashCode());
+  }
+
+  public void testShortEqualsInteger() {
+    JsonPrimitive p1 = new JsonPrimitive(Short.valueOf((short)10));
+    JsonPrimitive p2 = new JsonPrimitive(Integer.valueOf(10));
+    assertEquals(p1, p2);
+    assertEquals(p1.hashCode(), p2.hashCode());
+  }
+
+  public void testShortEqualsLong() {
+    JsonPrimitive p1 = new JsonPrimitive(Short.valueOf((short)10));
+    JsonPrimitive p2 = new JsonPrimitive(Long.valueOf(10));
+    assertEquals(p1, p2);
+    assertEquals(p1.hashCode(), p2.hashCode());
+  }
+
+  public void testShortEqualsBigInteger() {
+    JsonPrimitive p1 = new JsonPrimitive(Short.valueOf((short)10));
+    JsonPrimitive p2 = new JsonPrimitive(new BigInteger("10"));
+    assertEquals(p1, p2);
+    assertEquals(p1.hashCode(), p2.hashCode());
+  }
+
+  public void testIntegerEqualsLong() {
+    JsonPrimitive p1 = new JsonPrimitive(Integer.valueOf(10));
+    JsonPrimitive p2 = new JsonPrimitive(Long.valueOf(10L));
+    assertEquals(p1, p2);
+    assertEquals(p1.hashCode(), p2.hashCode());
+  }
+
+  public void testIntegerEqualsBigInteger() {
+    JsonPrimitive p1 = new JsonPrimitive(Integer.valueOf(10));
+    JsonPrimitive p2 = new JsonPrimitive(new BigInteger("10"));
+    assertEquals(p1, p2);
+    assertEquals(p1.hashCode(), p2.hashCode());
+  }
+
+  public void testLongEqualsBigInteger() {
+    JsonPrimitive p1 = new JsonPrimitive(Long.valueOf(10L));
+    JsonPrimitive p2 = new JsonPrimitive(new BigInteger("10"));
+    assertEquals(p1, p2);
+    assertEquals(p1.hashCode(), p2.hashCode());
+  }
+
+  public void testFloatEqualsDouble() {
+    JsonPrimitive p1 = new JsonPrimitive(Float.valueOf(10.25F));
+    JsonPrimitive p2 = new JsonPrimitive(Double.valueOf(10.25D));
+    assertEquals(p1, p2);
+    assertEquals(p1.hashCode(), p2.hashCode());
+  }
+
+  public void testFloatEqualsBigDecimal() {
+    JsonPrimitive p1 = new JsonPrimitive(Float.valueOf(10.25F));
+    JsonPrimitive p2 = new JsonPrimitive(new BigDecimal("10.25"));
+    assertEquals(p1, p2);
+    assertEquals(p1.hashCode(), p2.hashCode());
+  }
+
+  public void testDoubleEqualsBigDecimal() {
+    JsonPrimitive p1 = new JsonPrimitive(Double.valueOf(10.25D));
+    JsonPrimitive p2 = new JsonPrimitive(new BigDecimal("10.25"));
+    assertEquals(p1, p2);
+    assertEquals(p1.hashCode(), p2.hashCode());
+  }
+
+  public void testValidJsonOnToString() throws Exception {
+    JsonPrimitive json = new JsonPrimitive("Some\nEscaped\nValue");
+    assertEquals("\"Some\\nEscaped\\nValue\"", json.toString());
+
+    json = new JsonPrimitive(new BigDecimal("1.333"));
+    assertEquals("1.333", json.toString());
+  }
+
+  public void testEquals() {
+    MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive("A"), new JsonPrimitive("A"));
+    MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(true), new JsonPrimitive(true));
+    MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(5L), new JsonPrimitive(5L));
+    MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive('a'), new JsonPrimitive('a'));
+    MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(Float.NaN), new JsonPrimitive(Float.NaN));
+    MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(Float.NEGATIVE_INFINITY),
+        new JsonPrimitive(Float.NEGATIVE_INFINITY));
+    MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(Float.POSITIVE_INFINITY),
+        new JsonPrimitive(Float.POSITIVE_INFINITY));
+    MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(Double.NaN), new JsonPrimitive(Double.NaN));
+    MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(Double.NEGATIVE_INFINITY),
+        new JsonPrimitive(Double.NEGATIVE_INFINITY));
+    MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(Double.POSITIVE_INFINITY),
+        new JsonPrimitive(Double.POSITIVE_INFINITY));
+    assertFalse(new JsonPrimitive("a").equals(new JsonPrimitive("b")));
+    assertFalse(new JsonPrimitive(true).equals(new JsonPrimitive(false)));
+    assertFalse(new JsonPrimitive(0).equals(new JsonPrimitive(1)));
+  }
+
+  public void testEqualsAcrossTypes() {
+    MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive("a"), new JsonPrimitive('a'));
+    MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(new BigInteger("0")), new JsonPrimitive(0));
+    MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(0), new JsonPrimitive(0L));
+    MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(new BigInteger("0")), new JsonPrimitive(0));
+    MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(Float.NaN), new JsonPrimitive(Double.NaN));
+  }
+
+  public void testEqualsIntegerAndBigInteger() {
+    JsonPrimitive a = new JsonPrimitive(5L);
+    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 
+    // assertFalse(a + " equals " + b, a.equals(b));
+    assertTrue(a + " equals " + b, a.equals(b));
+  }
+
+  public void testEqualsDoesNotEquateStringAndNonStringTypes() {
+    assertFalse(new JsonPrimitive("true").equals(new JsonPrimitive(true)));
+    assertFalse(new JsonPrimitive("0").equals(new JsonPrimitive(0)));
+    assertFalse(new JsonPrimitive("NaN").equals(new JsonPrimitive(Float.NaN)));
+  }
+
+  public void testDeepCopy() {
+    JsonPrimitive a = new JsonPrimitive("a");
+    assertSame(a, a.deepCopy()); // Primitives are immutable!
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/JsonStreamParserTest.java b/gson/src/test/java/com/google/gson/JsonStreamParserTest.java
new file mode 100644
index 0000000..1b40b58
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/JsonStreamParserTest.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2009 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson;
+
+import junit.framework.TestCase;
+
+import java.util.NoSuchElementException;
+
+/**
+ * Unit tests for {@link JsonStreamParser}
+ * 
+ * @author Inderjeet Singh
+ */
+public class JsonStreamParserTest extends TestCase {
+  private JsonStreamParser parser;
+  
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    parser = new JsonStreamParser("'one' 'two'");
+  }
+
+  public void testParseTwoStrings() {
+    String actualOne = parser.next().getAsString();
+    assertEquals("one", actualOne);
+    String actualTwo = parser.next().getAsString();
+    assertEquals("two", actualTwo);
+  }
+
+  public void testIterator() {
+    assertTrue(parser.hasNext());
+    assertEquals("one", parser.next().getAsString());
+    assertTrue(parser.hasNext());
+    assertEquals("two", parser.next().getAsString());
+    assertFalse(parser.hasNext());
+  }
+
+  public void testNoSideEffectForHasNext() throws Exception {
+    assertTrue(parser.hasNext());
+    assertTrue(parser.hasNext());
+    assertTrue(parser.hasNext());
+    assertEquals("one", parser.next().getAsString());
+    
+    assertTrue(parser.hasNext());
+    assertTrue(parser.hasNext());
+    assertEquals("two", parser.next().getAsString());
+    
+    assertFalse(parser.hasNext());
+    assertFalse(parser.hasNext());
+  }
+
+  public void testCallingNextBeyondAvailableInput() {
+    parser.next();
+    parser.next();
+    try {
+      parser.next();
+      fail("Parser should not go beyond available input");
+    } catch (NoSuchElementException expected) {
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/LongSerializationPolicyTest.java b/gson/src/test/java/com/google/gson/LongSerializationPolicyTest.java
new file mode 100644
index 0000000..a4ad8f1
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/LongSerializationPolicyTest.java
@@ -0,0 +1,84 @@
+/*
+ * Copyright (C) 2009 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import junit.framework.TestCase;
+
+/**
+ * Unit test for the {@link LongSerializationPolicy} class.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public class LongSerializationPolicyTest extends TestCase {
+
+  public void testDefaultLongSerialization() throws Exception {
+    JsonElement element = LongSerializationPolicy.DEFAULT.serialize(1556L);
+    assertTrue(element.isJsonPrimitive());
+
+    JsonPrimitive jsonPrimitive = element.getAsJsonPrimitive();
+    assertFalse(jsonPrimitive.isString());
+    assertTrue(jsonPrimitive.isNumber());
+    assertEquals(1556L, element.getAsLong());
+  }
+
+  public void testDefaultLongSerializationIntegration() {
+    Gson gson = new GsonBuilder()
+      .setLongSerializationPolicy(LongSerializationPolicy.DEFAULT)
+      .create();
+    assertEquals("[1]", gson.toJson(new long[] { 1L }, long[].class));
+    assertEquals("[1]", gson.toJson(new Long[] { 1L }, Long[].class));
+  }
+
+  public void testDefaultLongSerializationNull() {
+    LongSerializationPolicy policy = LongSerializationPolicy.DEFAULT;
+    assertTrue(policy.serialize(null).isJsonNull());
+
+    Gson gson = new GsonBuilder()
+      .setLongSerializationPolicy(policy)
+      .create();
+    assertEquals("null", gson.toJson(null, Long.class));
+  }
+
+  public void testStringLongSerialization() throws Exception {
+    JsonElement element = LongSerializationPolicy.STRING.serialize(1556L);
+    assertTrue(element.isJsonPrimitive());
+
+    JsonPrimitive jsonPrimitive = element.getAsJsonPrimitive();
+    assertFalse(jsonPrimitive.isNumber());
+    assertTrue(jsonPrimitive.isString());
+    assertEquals("1556", element.getAsString());
+  }
+
+  public void testStringLongSerializationIntegration() {
+    Gson gson = new GsonBuilder()
+      .setLongSerializationPolicy(LongSerializationPolicy.STRING)
+      .create();
+    assertEquals("[\"1\"]", gson.toJson(new long[] { 1L }, long[].class));
+    assertEquals("[\"1\"]", gson.toJson(new Long[] { 1L }, Long[].class));
+  }
+
+  public void testStringLongSerializationNull() {
+    LongSerializationPolicy policy = LongSerializationPolicy.STRING;
+    assertTrue(policy.serialize(null).isJsonNull());
+
+    Gson gson = new GsonBuilder()
+      .setLongSerializationPolicy(policy)
+      .create();
+    assertEquals("null", gson.toJson(null, Long.class));
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/MixedStreamTest.java b/gson/src/test/java/com/google/gson/MixedStreamTest.java
new file mode 100644
index 0000000..00eb4bc
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/MixedStreamTest.java
@@ -0,0 +1,239 @@
+/*
+ * Copyright (C) 2010 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import com.google.gson.reflect.TypeToken;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.lang.reflect.Type;
+import java.util.Arrays;
+import java.util.List;
+import junit.framework.TestCase;
+
+public final class MixedStreamTest extends TestCase {
+
+  private static final Car BLUE_MUSTANG = new Car("mustang", 0x0000FF);
+  private static final Car BLACK_BMW = new Car("bmw", 0x000000);
+  private static final Car RED_MIATA = new Car("miata", 0xFF0000);
+  private static final String CARS_JSON = "[\n"
+      + "  {\n"
+      + "    \"name\": \"mustang\",\n"
+      + "    \"color\": 255\n"
+      + "  },\n"
+      + "  {\n"
+      + "    \"name\": \"bmw\",\n"
+      + "    \"color\": 0\n"
+      + "  },\n"
+      + "  {\n"
+      + "    \"name\": \"miata\",\n"
+      + "    \"color\": 16711680\n"
+      + "  }\n"
+      + "]";
+
+  public void testWriteMixedStreamed() throws IOException {
+    Gson gson = new Gson();
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter jsonWriter = new JsonWriter(stringWriter);
+
+    jsonWriter.beginArray();
+    jsonWriter.setIndent("  ");
+    gson.toJson(BLUE_MUSTANG, Car.class, jsonWriter);
+    gson.toJson(BLACK_BMW, Car.class, jsonWriter);
+    gson.toJson(RED_MIATA, Car.class, jsonWriter);
+    jsonWriter.endArray();
+
+    assertEquals(CARS_JSON, stringWriter.toString());
+  }
+
+  public void testReadMixedStreamed() throws IOException {
+    Gson gson = new Gson();
+    StringReader stringReader = new StringReader(CARS_JSON);
+    JsonReader jsonReader = new JsonReader(stringReader);
+
+    jsonReader.beginArray();
+    assertEquals(BLUE_MUSTANG, gson.fromJson(jsonReader, Car.class));
+    assertEquals(BLACK_BMW, gson.fromJson(jsonReader, Car.class));
+    assertEquals(RED_MIATA, gson.fromJson(jsonReader, Car.class));
+    jsonReader.endArray();
+  }
+
+  public void testReaderDoesNotMutateState() throws IOException {
+    Gson gson = new Gson();
+    JsonReader jsonReader = new JsonReader(new StringReader(CARS_JSON));
+    jsonReader.beginArray();
+
+    jsonReader.setLenient(false);
+    gson.fromJson(jsonReader, Car.class);
+    assertFalse(jsonReader.isLenient());
+
+    jsonReader.setLenient(true);
+    gson.fromJson(jsonReader, Car.class);
+    assertTrue(jsonReader.isLenient());
+  }
+
+  public void testWriteDoesNotMutateState() throws IOException {
+    Gson gson = new Gson();
+    JsonWriter jsonWriter = new JsonWriter(new StringWriter());
+    jsonWriter.beginArray();
+
+    jsonWriter.setHtmlSafe(true);
+    jsonWriter.setLenient(true);
+    gson.toJson(BLUE_MUSTANG, Car.class, jsonWriter);
+    assertTrue(jsonWriter.isHtmlSafe());
+    assertTrue(jsonWriter.isLenient());
+
+    jsonWriter.setHtmlSafe(false);
+    jsonWriter.setLenient(false);
+    gson.toJson(BLUE_MUSTANG, Car.class, jsonWriter);
+    assertFalse(jsonWriter.isHtmlSafe());
+    assertFalse(jsonWriter.isLenient());
+  }
+
+  public void testReadInvalidState() throws IOException {
+    Gson gson = new Gson();
+    JsonReader jsonReader = new JsonReader(new StringReader(CARS_JSON));
+    jsonReader.beginArray();
+    jsonReader.beginObject();
+    try {
+      gson.fromJson(jsonReader, String.class);
+      fail();
+    } catch (JsonParseException expected) {
+    }
+  }
+
+  public void testReadClosed() throws IOException {
+    Gson gson = new Gson();
+    JsonReader jsonReader = new JsonReader(new StringReader(CARS_JSON));
+    jsonReader.close();
+    try {
+      gson.fromJson(jsonReader, new TypeToken<List<Car>>() {}.getType());
+      fail();
+    } catch (JsonParseException expected) {
+    }
+  }
+
+  public void testWriteInvalidState() throws IOException {
+    Gson gson = new Gson();
+    JsonWriter jsonWriter = new JsonWriter(new StringWriter());
+    jsonWriter.beginObject();
+    try {
+      gson.toJson(BLUE_MUSTANG, Car.class, jsonWriter);
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+  }
+
+  public void testWriteClosed() throws IOException {
+    Gson gson = new Gson();
+    JsonWriter jsonWriter = new JsonWriter(new StringWriter());
+    jsonWriter.beginArray();
+    jsonWriter.endArray();
+    jsonWriter.close();
+    try {
+      gson.toJson(BLUE_MUSTANG, Car.class, jsonWriter);
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+  }
+
+  public void testWriteNulls() {
+    Gson gson = new Gson();
+    try {
+      gson.toJson(new JsonPrimitive("hello"), (JsonWriter) null);
+      fail();
+    } catch (NullPointerException expected) {
+    }
+
+    StringWriter stringWriter = new StringWriter();
+    gson.toJson(null, new JsonWriter(stringWriter));
+    assertEquals("null", stringWriter.toString());
+  }
+
+  public void testReadNulls() {
+    Gson gson = new Gson();
+    try {
+      gson.fromJson((JsonReader) null, Integer.class);
+      fail();
+    } catch (NullPointerException expected) {
+    }
+    try {
+      gson.fromJson(new JsonReader(new StringReader("true")), null);
+      fail();
+    } catch (NullPointerException expected) {
+    }
+  }
+
+  public void testWriteHtmlSafe() {
+    List<String> contents = Arrays.asList("<", ">", "&", "=", "'");
+    Type type = new TypeToken<List<String>>() {}.getType();
+
+    StringWriter writer = new StringWriter();
+    new Gson().toJson(contents, type, new JsonWriter(writer));
+    assertEquals("[\"\\u003c\",\"\\u003e\",\"\\u0026\",\"\\u003d\",\"\\u0027\"]",
+        writer.toString());
+
+    writer = new StringWriter();
+    new GsonBuilder().disableHtmlEscaping().create()
+        .toJson(contents, type, new JsonWriter(writer));
+    assertEquals("[\"<\",\">\",\"&\",\"=\",\"'\"]",
+        writer.toString());
+  }
+
+  public void testWriteLenient() {
+    List<Double> doubles = Arrays.asList(Double.NaN, Double.NEGATIVE_INFINITY,
+        Double.POSITIVE_INFINITY, -0.0d, 0.5d, 0.0d);
+    Type type = new TypeToken<List<Double>>() {}.getType();
+
+    StringWriter writer = new StringWriter();
+    JsonWriter jsonWriter = new JsonWriter(writer);
+    new GsonBuilder().serializeSpecialFloatingPointValues().create()
+        .toJson(doubles, type, jsonWriter);
+    assertEquals("[NaN,-Infinity,Infinity,-0.0,0.5,0.0]", writer.toString());
+
+    try {
+      new Gson().toJson(doubles, type, new JsonWriter(new StringWriter()));
+      fail();
+    } catch (IllegalArgumentException expected) {
+    }
+  }
+
+  static final class Car {
+    String name;
+    int color;
+
+    Car(String name, int color) {
+      this.name = name;
+      this.color = color;
+    }
+
+    // used by Gson
+    Car() {}
+
+    @Override public int hashCode() {
+      return name.hashCode() ^ color;
+    }
+
+    @Override public boolean equals(Object o) {
+      return o instanceof Car
+          && ((Car) o).name.equals(name)
+          && ((Car) o).color == color;
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/MockExclusionStrategy.java b/gson/src/test/java/com/google/gson/MockExclusionStrategy.java
new file mode 100644
index 0000000..7830d8a
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/MockExclusionStrategy.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+/**
+ * This is a configurable {@link ExclusionStrategy} that can be used for
+ * unit testing.
+ *
+ * @author Joel Leitch
+ */
+final class MockExclusionStrategy implements ExclusionStrategy {
+  private final boolean skipClass;
+  private final boolean skipField;
+
+  public MockExclusionStrategy(boolean skipClass, boolean skipField) {
+    this.skipClass = skipClass;
+    this.skipField = skipField;
+  }
+
+  @Override
+  public boolean shouldSkipField(FieldAttributes f) {
+    return skipField;
+  }
+
+  @Override
+  public boolean shouldSkipClass(Class<?> clazz) {
+    return skipClass;
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/ObjectTypeAdapterParameterizedTest.java b/gson/src/test/java/com/google/gson/ObjectTypeAdapterParameterizedTest.java
new file mode 100644
index 0000000..60740ce
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/ObjectTypeAdapterParameterizedTest.java
@@ -0,0 +1,41 @@
+package com.google.gson;
+
+import static org.junit.Assert.assertEquals;
+
+import java.io.IOException;
+import java.util.Arrays;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.junit.runners.Parameterized.Parameter;
+import org.junit.runners.Parameterized.Parameters;
+
+@RunWith(Parameterized.class)
+public class ObjectTypeAdapterParameterizedTest {
+  @Parameters
+  public static Iterable<String> data() {
+    return Arrays.asList(
+      "[]",
+      "{}",
+      "null",
+      "1.0",
+      "true",
+      "\"string\"",
+      "[true,1.0,null,{},2.0,{\"a\":[false]},[3.0,\"test\"],4.0]",
+      "{\"\":1.0,\"a\":true,\"b\":null,\"c\":[],\"d\":{\"a1\":2.0,\"b2\":[true,{\"a3\":3.0}]},\"e\":[{\"f\":4.0},\"test\"]}"
+    );
+  }
+
+  private final TypeAdapter<Object> adapter = new Gson().getAdapter(Object.class);
+  @Parameter
+  public String json;
+
+  @Test
+  public void testReadWrite() throws IOException {
+    Object deserialized = adapter.fromJson(json);
+    String actualSerialized = adapter.toJson(deserialized);
+
+    // Serialized Object should be the same as original JSON
+    assertEquals(json, actualSerialized);
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/ObjectTypeAdapterTest.java b/gson/src/test/java/com/google/gson/ObjectTypeAdapterTest.java
new file mode 100644
index 0000000..534c398
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/ObjectTypeAdapterTest.java
@@ -0,0 +1,110 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import junit.framework.TestCase;
+
+public final class ObjectTypeAdapterTest extends TestCase {
+  private final Gson gson = new GsonBuilder().create();
+  private final TypeAdapter<Object> adapter = gson.getAdapter(Object.class);
+
+  public void testDeserialize() throws Exception {
+    Map<?, ?> map = (Map<?, ?>) adapter.fromJson("{\"a\":5,\"b\":[1,2,null],\"c\":{\"x\":\"y\"}}");
+    assertEquals(5.0, map.get("a"));
+    assertEquals(Arrays.asList(1.0, 2.0, null), map.get("b"));
+    assertEquals(Collections.singletonMap("x", "y"), map.get("c"));
+    assertEquals(3, map.size());
+  }
+
+  public void testSerialize() throws Exception {
+    Object object = new RuntimeType();
+    assertEquals("{'a':5,'b':[1,2,null]}", adapter.toJson(object).replace("\"", "'"));
+  }
+
+  public void testSerializeNullValue() throws Exception {
+    Map<String, Object> map = new LinkedHashMap<>();
+    map.put("a", null);
+    assertEquals("{'a':null}", adapter.toJson(map).replace('"', '\''));
+  }
+
+  public void testDeserializeNullValue() throws Exception {
+    Map<String, Object> map = new LinkedHashMap<>();
+    map.put("a", null);
+    assertEquals(map, adapter.fromJson("{\"a\":null}"));
+  }
+
+  public void testSerializeObject() throws Exception {
+    assertEquals("{}", adapter.toJson(new Object()));
+  }
+
+  private static String repeat(String s, int times) {
+    StringBuilder stringBuilder = new StringBuilder(s.length() * times);
+    for (int i = 0; i < times; i++) {
+      stringBuilder.append(s);
+    }
+    return stringBuilder.toString();
+  }
+
+  /** Deeply nested JSON arrays should not cause {@link StackOverflowError} */
+  @SuppressWarnings("unchecked")
+  public void testDeserializeDeeplyNestedArrays() throws IOException {
+    int times = 10000;
+    // [[[ ... ]]]
+    String json = repeat("[", times) + repeat("]", times);
+
+    int actualTimes = 0;
+    List<List<?>> current = (List<List<?>>) adapter.fromJson(json);
+    while (true) {
+      actualTimes++;
+      if (current.isEmpty()) {
+        break;
+      }
+      assertEquals(1, current.size());
+      current = (List<List<?>>) current.get(0);
+    }
+    assertEquals(times, actualTimes);
+  }
+
+  /** Deeply nested JSON objects should not cause {@link StackOverflowError} */
+  @SuppressWarnings("unchecked")
+  public void testDeserializeDeeplyNestedObjects() throws IOException {
+    int times = 10000;
+    // {"a":{"a": ... {"a":null} ... }}
+    String json = repeat("{\"a\":", times) + "null" + repeat("}", times);
+
+    int actualTimes = 0;
+    Map<String, Map<?, ?>> current = (Map<String, Map<?, ?>>) adapter.fromJson(json);
+    while (current != null) {
+      assertEquals(1, current.size());
+      actualTimes++;
+      current = (Map<String, Map<?, ?>>) current.get("a");
+    }
+    assertEquals(times, actualTimes);
+  }
+
+  @SuppressWarnings("unused")
+  private class RuntimeType {
+    Object a = 5;
+    Object b = Arrays.asList(1, 2, null);
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/OverrideCoreTypeAdaptersTest.java b/gson/src/test/java/com/google/gson/OverrideCoreTypeAdaptersTest.java
new file mode 100644
index 0000000..79ae169
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/OverrideCoreTypeAdaptersTest.java
@@ -0,0 +1,77 @@
+/*
+ * Copyright (C) 2012 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
+import java.util.Locale;
+import junit.framework.TestCase;
+
+/**
+ * @author Jesse Wilson
+ */
+public class OverrideCoreTypeAdaptersTest extends TestCase {
+  private static final TypeAdapter<Boolean> booleanAsIntAdapter = new TypeAdapter<Boolean>() {
+    @Override public void write(JsonWriter out, Boolean value) throws IOException {
+      out.value(value ? 1 : 0);
+    }
+    @Override public Boolean read(JsonReader in) throws IOException {
+      int value = in.nextInt();
+      return value != 0;
+    }
+  };
+
+  private static final TypeAdapter<String> swapCaseStringAdapter = new TypeAdapter<String>() {
+    @Override public void write(JsonWriter out, String value) throws IOException {
+      out.value(value.toUpperCase(Locale.US));
+    }
+    @Override public String read(JsonReader in) throws IOException {
+      return in.nextString().toLowerCase(Locale.US);
+    }
+  };
+
+  public void testOverrideWrapperBooleanAdapter() {
+    Gson gson = new GsonBuilder()
+        .registerTypeAdapter(Boolean.class, booleanAsIntAdapter)
+        .create();
+    assertEquals("true", gson.toJson(true, boolean.class));
+    assertEquals("1", gson.toJson(true, Boolean.class));
+    assertEquals(Boolean.TRUE, gson.fromJson("true", boolean.class));
+    assertEquals(Boolean.TRUE, gson.fromJson("1", Boolean.class));
+    assertEquals(Boolean.FALSE, gson.fromJson("0", Boolean.class));
+  }
+
+  public void testOverridePrimitiveBooleanAdapter() {
+    Gson gson = new GsonBuilder()
+        .registerTypeAdapter(boolean.class, booleanAsIntAdapter)
+        .create();
+    assertEquals("1", gson.toJson(true, boolean.class));
+    assertEquals("true", gson.toJson(true, Boolean.class));
+    assertEquals(Boolean.TRUE, gson.fromJson("1", boolean.class));
+    assertEquals(Boolean.TRUE, gson.fromJson("true", Boolean.class));
+    assertEquals("0", gson.toJson(false, boolean.class));
+  }
+
+  public void testOverrideStringAdapter() {
+    Gson gson = new GsonBuilder()
+        .registerTypeAdapter(String.class, swapCaseStringAdapter)
+        .create();
+    assertEquals("\"HELLO\"", gson.toJson("Hello", String.class));
+    assertEquals("hello", gson.fromJson("\"Hello\"", String.class));
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/ParameterizedTypeFixtures.java b/gson/src/test/java/com/google/gson/ParameterizedTypeFixtures.java
new file mode 100644
index 0000000..3aca9fb
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/ParameterizedTypeFixtures.java
@@ -0,0 +1,177 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import com.google.gson.internal.$Gson$Types;
+
+import com.google.gson.internal.Primitives;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+
+
+/**
+ * This class contains some test fixtures for Parameterized types. These classes should ideally
+ * belong either in the common or functional package, but they are placed here because they need
+ * access to package protected elements of com.google.gson.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public class ParameterizedTypeFixtures {
+
+  public static class MyParameterizedType<T> {
+    public final T value;
+    public MyParameterizedType(T value) {
+      this.value = value;
+    }
+    public T getValue() {
+      return value;
+    }
+
+    public String getExpectedJson() {
+      String valueAsJson = getExpectedJson(value);
+      return String.format("{\"value\":%s}", valueAsJson);
+    }
+
+    private String getExpectedJson(Object obj) {
+      Class<?> clazz = obj.getClass();
+      if (Primitives.isWrapperType(Primitives.wrap(clazz))) {
+        return obj.toString();
+      } else if (obj.getClass().equals(String.class)) {
+        return "\"" + obj.toString() + "\"";
+      } else {
+        // Try invoking a getExpectedJson() method if it exists
+        try {
+          Method method = clazz.getMethod("getExpectedJson");
+          Object results = method.invoke(obj);
+          return (String) results;
+        } catch (SecurityException e) {
+          throw new RuntimeException(e);
+        } catch (NoSuchMethodException e) {
+          throw new RuntimeException(e);
+        } catch (IllegalArgumentException e) {
+          throw new RuntimeException(e);
+        } catch (IllegalAccessException e) {
+          throw new RuntimeException(e);
+        } catch (InvocationTargetException e) {
+          throw new RuntimeException(e);
+        }
+      }
+    }
+
+    @Override
+    public int hashCode() {
+      return value == null ? 0 : value.hashCode();
+    }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public boolean equals(Object obj) {
+      if (this == obj) {
+        return true;
+      }
+      if (obj == null) {
+        return false;
+      }
+      if (getClass() != obj.getClass()) {
+        return false;
+      }
+      MyParameterizedType<T> other = (MyParameterizedType<T>) obj;
+      if (value == null) {
+        if (other.value != null) {
+          return false;
+        }
+      } else if (!value.equals(other.value)) {
+        return false;
+      }
+      return true;
+    }
+  }
+
+  public static class MyParameterizedTypeInstanceCreator<T>
+      implements InstanceCreator<MyParameterizedType<T>>{
+    private final T instanceOfT;
+    /**
+     * Caution the specified instance is reused by the instance creator for each call.
+     * This means that the fields of the same objects will be overwritten by Gson.
+     * This is usually fine in tests since there we deserialize just once, but quite
+     * dangerous in practice.
+     *
+     * @param instanceOfT
+     */
+    public MyParameterizedTypeInstanceCreator(T instanceOfT) {
+      this.instanceOfT = instanceOfT;
+    }
+    @Override public MyParameterizedType<T> createInstance(Type type) {
+      return new MyParameterizedType<>(instanceOfT);
+    }
+  }
+
+  public static final class MyParameterizedTypeAdapter<T>
+  implements JsonSerializer<MyParameterizedType<T>>, JsonDeserializer<MyParameterizedType<T>> {
+    @SuppressWarnings("unchecked")
+    public static<T> String getExpectedJson(MyParameterizedType<T> obj) {
+      Class<T> clazz = (Class<T>) obj.value.getClass();
+      boolean addQuotes = !clazz.isArray() && !Primitives.unwrap(clazz).isPrimitive();
+      StringBuilder sb = new StringBuilder("{\"");
+      sb.append(obj.value.getClass().getSimpleName()).append("\":");
+      if (addQuotes) {
+        sb.append("\"");
+      }
+      sb.append(obj.value.toString());
+      if (addQuotes) {
+        sb.append("\"");
+      }
+      sb.append("}");
+      return sb.toString();
+    }
+
+    @Override public JsonElement serialize(MyParameterizedType<T> src, Type classOfSrc,
+        JsonSerializationContext context) {
+      JsonObject json = new JsonObject();
+      T value = src.getValue();
+      json.add(value.getClass().getSimpleName(), context.serialize(value));
+      return json;
+    }
+
+    @SuppressWarnings("unchecked")
+    @Override public MyParameterizedType<T> deserialize(JsonElement json, Type typeOfT,
+        JsonDeserializationContext context) throws JsonParseException {
+      Type genericClass = ((ParameterizedType) typeOfT).getActualTypeArguments()[0];
+      Class<?> rawType = $Gson$Types.getRawType(genericClass);
+      String className = rawType.getSimpleName();
+      JsonElement jsonElement = json.getAsJsonObject().get(className);
+
+      T value;
+      if (genericClass == Integer.class) {
+        value = (T) Integer.valueOf(jsonElement.getAsInt());
+      } else if (genericClass == String.class) {
+        value = (T) jsonElement.getAsString();
+      } else {
+        value = (T) jsonElement;
+      }
+
+      if (Primitives.isPrimitive(genericClass)) {
+        PrimitiveTypeAdapter typeAdapter = new PrimitiveTypeAdapter();
+        value = (T) typeAdapter.adaptType(value, rawType);
+      }
+      return new MyParameterizedType<>(value);
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/ParameterizedTypeTest.java b/gson/src/test/java/com/google/gson/ParameterizedTypeTest.java
new file mode 100644
index 0000000..24d78e8
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/ParameterizedTypeTest.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import com.google.gson.internal.$Gson$Types;
+import com.google.gson.reflect.TypeToken;
+
+import junit.framework.TestCase;
+
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.util.List;
+
+/**
+ * Unit tests for {@code ParameterizedType}s created by the {@link $Gson$Types} class.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public class ParameterizedTypeTest extends TestCase {
+  private ParameterizedType ourType;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    ourType = $Gson$Types.newParameterizedTypeWithOwner(null, List.class, String.class);
+  }
+
+  public void testOurTypeFunctionality() throws Exception {
+    Type parameterizedType = new TypeToken<List<String>>() {}.getType();
+    assertNull(ourType.getOwnerType());
+    assertEquals(String.class, ourType.getActualTypeArguments()[0]);
+    assertEquals(List.class, ourType.getRawType());
+    assertEquals(parameterizedType, ourType);
+    assertEquals(parameterizedType.hashCode(), ourType.hashCode());
+  }
+
+  public void testNotEquals() throws Exception {
+    Type differentParameterizedType = new TypeToken<List<Integer>>() {}.getType();
+    assertFalse(differentParameterizedType.equals(ourType));
+    assertFalse(ourType.equals(differentParameterizedType));
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/PrimitiveTypeAdapter.java b/gson/src/test/java/com/google/gson/PrimitiveTypeAdapter.java
new file mode 100644
index 0000000..fb38687
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/PrimitiveTypeAdapter.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import com.google.gson.internal.Primitives;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+
+/**
+ * Handles type conversion from some object to some primitive (or primitive
+ * wrapper instance).
+ *
+ * @author Joel Leitch
+ */
+final class PrimitiveTypeAdapter {
+
+  @SuppressWarnings("unchecked")
+  public <T> T adaptType(Object from, Class<T> to) {
+    Class<?> aClass = Primitives.wrap(to);
+    if (Primitives.isWrapperType(aClass)) {
+      if (aClass == Character.class) {
+        String value = from.toString();
+        if (value.length() == 1) {
+          return (T) (Character) from.toString().charAt(0);
+        }
+        throw new JsonParseException("The value: " + value + " contains more than a character.");
+      }
+
+      try {
+        Constructor<?> constructor = aClass.getConstructor(String.class);
+        return (T) constructor.newInstance(from.toString());
+      } catch (NoSuchMethodException e) {
+        throw new JsonParseException(e);
+      } catch (IllegalAccessException e) {
+        throw new JsonParseException(e);
+      } catch (InvocationTargetException e) {
+        throw new JsonParseException(e);
+      } catch (InstantiationException e) {
+        throw new JsonParseException(e);
+      }
+    } else if (Enum.class.isAssignableFrom(to)) {
+      // Case where the type being adapted to is an Enum
+      // We will try to convert from.toString() to the enum
+      try {
+        Method valuesMethod = to.getMethod("valueOf", String.class);
+        return (T) valuesMethod.invoke(null, from.toString());
+      } catch (NoSuchMethodException e) {
+        throw new RuntimeException(e);
+      } catch (IllegalAccessException e) {
+        throw new RuntimeException(e);
+      } catch (InvocationTargetException e) {
+        throw new RuntimeException(e);
+      }
+    } else {
+      throw new JsonParseException("Can not adapt type " + from.getClass() + " to " + to);
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/ToNumberPolicyTest.java b/gson/src/test/java/com/google/gson/ToNumberPolicyTest.java
new file mode 100644
index 0000000..db9898d
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/ToNumberPolicyTest.java
@@ -0,0 +1,139 @@
+/*
+ * Copyright (C) 2021 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import java.io.IOException;
+import java.io.StringReader;
+import java.math.BigDecimal;
+import com.google.gson.internal.LazilyParsedNumber;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.MalformedJsonException;
+import junit.framework.TestCase;
+
+public class ToNumberPolicyTest extends TestCase {
+  public void testDouble() throws IOException {
+    ToNumberStrategy strategy = ToNumberPolicy.DOUBLE;
+    assertEquals(10.1, strategy.readNumber(fromString("10.1")));
+    assertEquals(3.141592653589793D, strategy.readNumber(fromString("3.141592653589793238462643383279")));
+    try {
+      strategy.readNumber(fromString("1e400"));
+      fail();
+    } catch (MalformedJsonException expected) {
+      assertEquals("JSON forbids NaN and infinities: Infinity at line 1 column 6 path $", expected.getMessage());
+    }
+    try {
+      strategy.readNumber(fromString("\"not-a-number\""));
+      fail();
+    } catch (NumberFormatException expected) {
+    }
+  }
+
+  public void testLazilyParsedNumber() throws IOException {
+    ToNumberStrategy strategy = ToNumberPolicy.LAZILY_PARSED_NUMBER;
+    assertEquals(new LazilyParsedNumber("10.1"), strategy.readNumber(fromString("10.1")));
+    assertEquals(new LazilyParsedNumber("3.141592653589793238462643383279"), strategy.readNumber(fromString("3.141592653589793238462643383279")));
+    assertEquals(new LazilyParsedNumber("1e400"), strategy.readNumber(fromString("1e400")));
+  }
+
+  public void testLongOrDouble() throws IOException {
+    ToNumberStrategy strategy = ToNumberPolicy.LONG_OR_DOUBLE;
+    assertEquals(10L, strategy.readNumber(fromString("10")));
+    assertEquals(10.1, strategy.readNumber(fromString("10.1")));
+    assertEquals(3.141592653589793D, strategy.readNumber(fromString("3.141592653589793238462643383279")));
+    try {
+      strategy.readNumber(fromString("1e400"));
+      fail();
+    } catch (MalformedJsonException expected) {
+      assertEquals("JSON forbids NaN and infinities: Infinity; at path $", expected.getMessage());
+    }
+    try {
+      strategy.readNumber(fromString("\"not-a-number\""));
+      fail();
+    } catch (JsonParseException expected) {
+      assertEquals("Cannot parse not-a-number; at path $", expected.getMessage());
+    }
+
+    assertEquals(Double.NaN, strategy.readNumber(fromStringLenient("NaN")));
+    assertEquals(Double.POSITIVE_INFINITY, strategy.readNumber(fromStringLenient("Infinity")));
+    assertEquals(Double.NEGATIVE_INFINITY, strategy.readNumber(fromStringLenient("-Infinity")));
+    try {
+      strategy.readNumber(fromString("NaN"));
+      fail();
+    } catch (MalformedJsonException expected) {
+      assertEquals("Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $", expected.getMessage());
+    }
+    try {
+      strategy.readNumber(fromString("Infinity"));
+      fail();
+    } catch (MalformedJsonException expected) {
+      assertEquals("Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $", expected.getMessage());
+    }
+    try {
+      strategy.readNumber(fromString("-Infinity"));
+      fail();
+    } catch (MalformedJsonException expected) {
+      assertEquals("Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $", expected.getMessage());
+    }
+  }
+
+  public void testBigDecimal() throws IOException {
+    ToNumberStrategy strategy = ToNumberPolicy.BIG_DECIMAL;
+    assertEquals(new BigDecimal("10.1"), strategy.readNumber(fromString("10.1")));
+    assertEquals(new BigDecimal("3.141592653589793238462643383279"), strategy.readNumber(fromString("3.141592653589793238462643383279")));
+    assertEquals(new BigDecimal("1e400"), strategy.readNumber(fromString("1e400")));
+
+    try {
+      strategy.readNumber(fromString("\"not-a-number\""));
+      fail();
+    } catch (JsonParseException expected) {
+      assertEquals("Cannot parse not-a-number; at path $", expected.getMessage());
+    }
+  }
+
+  public void testNullsAreNeverExpected() throws IOException {
+    try {
+      ToNumberPolicy.DOUBLE.readNumber(fromString("null"));
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+    try {
+      ToNumberPolicy.LAZILY_PARSED_NUMBER.readNumber(fromString("null"));
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+    try {
+      ToNumberPolicy.LONG_OR_DOUBLE.readNumber(fromString("null"));
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+    try {
+      ToNumberPolicy.BIG_DECIMAL.readNumber(fromString("null"));
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+  }
+
+  private static JsonReader fromString(String json) {
+    return new JsonReader(new StringReader(json));
+  }
+
+  private static JsonReader fromStringLenient(String json) {
+    JsonReader jsonReader = fromString(json);
+    jsonReader.setLenient(true);
+    return jsonReader;
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/TypeAdapterTest.java b/gson/src/test/java/com/google/gson/TypeAdapterTest.java
new file mode 100644
index 0000000..ab44637
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/TypeAdapterTest.java
@@ -0,0 +1,52 @@
+package com.google.gson;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
+import java.io.StringReader;
+import org.junit.Test;
+
+public class TypeAdapterTest {
+  @Test
+  public void testNullSafe() throws IOException {
+    TypeAdapter<String> adapter = new TypeAdapter<String>() {
+      @Override public void write(JsonWriter out, String value) {
+        throw new AssertionError("unexpected call");
+      }
+
+      @Override public String read(JsonReader in) {
+        throw new AssertionError("unexpected call");
+      }
+    }.nullSafe();
+
+    assertEquals("null", adapter.toJson(null));
+    assertNull(adapter.fromJson("null"));
+  }
+
+  private static final TypeAdapter<String> adapter = new TypeAdapter<String>() {
+    @Override public void write(JsonWriter out, String value) throws IOException {
+      out.value(value);
+    }
+
+    @Override public String read(JsonReader in) throws IOException {
+      return in.nextString();
+    }
+  };
+
+  // Note: This test just verifies the current behavior; it is a bit questionable
+  // whether that behavior is actually desired
+  @Test
+  public void testFromJson_Reader_TrailingData() throws IOException {
+    assertEquals("a", adapter.fromJson(new StringReader("\"a\"1")));
+  }
+
+  // Note: This test just verifies the current behavior; it is a bit questionable
+  // whether that behavior is actually desired
+  @Test
+  public void testFromJson_String_TrailingData() throws IOException {
+    assertEquals("a", adapter.fromJson("\"a\"1"));
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/VersionExclusionStrategyTest.java b/gson/src/test/java/com/google/gson/VersionExclusionStrategyTest.java
new file mode 100644
index 0000000..d878850
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/VersionExclusionStrategyTest.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson;
+
+import com.google.gson.annotations.Since;
+import com.google.gson.internal.Excluder;
+import junit.framework.TestCase;
+
+/**
+ * Unit tests for the {@link Excluder} class.
+ *
+ * @author Joel Leitch
+ */
+public class VersionExclusionStrategyTest extends TestCase {
+  private static final double VERSION = 5.0D;
+
+  public void testClassAndFieldAreAtSameVersion() throws Exception {
+    Excluder excluder = Excluder.DEFAULT.withVersion(VERSION);
+    assertFalse(excluder.excludeClass(MockObject.class, true));
+    assertFalse(excluder.excludeField(MockObject.class.getField("someField"), true));
+  }
+
+  public void testClassAndFieldAreBehindInVersion() throws Exception {
+    Excluder excluder = Excluder.DEFAULT.withVersion(VERSION + 1);
+    assertFalse(excluder.excludeClass(MockObject.class, true));
+    assertFalse(excluder.excludeField(MockObject.class.getField("someField"), true));
+  }
+
+  public void testClassAndFieldAreAheadInVersion() throws Exception {
+    Excluder excluder = Excluder.DEFAULT.withVersion(VERSION - 1);
+    assertTrue(excluder.excludeClass(MockObject.class, true));
+    assertTrue(excluder.excludeField(MockObject.class.getField("someField"), true));
+  }
+
+  @Since(VERSION)
+  private static class MockObject {
+
+    @Since(VERSION)
+    public final int someField = 0;
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/common/MoreAsserts.java b/gson/src/test/java/com/google/gson/common/MoreAsserts.java
new file mode 100644
index 0000000..f409480
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/common/MoreAsserts.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.common;
+
+import org.junit.Assert;
+
+import java.util.Collection;
+
+/**
+ * Handy asserts that we wish were present in {@link Assert}
+ * so that we didn't have to write them.
+ *
+ * @author Inderjeet Singh
+ */
+public class MoreAsserts {
+
+  /**
+   * Asserts that the specified {@code value} is not present in {@code collection}
+   * @param collection the collection to look into
+   * @param value the value that needs to be checked for presence
+   */
+  public static <T> void assertContains(Collection<T> collection, T value) {
+    for (T entry : collection) {
+      if (entry.equals(value)) {
+        return;
+      }
+    }
+    Assert.fail(value + " not present in " + collection);
+  }
+
+  public static void assertEqualsAndHashCode(Object a, Object b) {
+    Assert.assertTrue(a.equals(b));
+    Assert.assertTrue(b.equals(a));
+    Assert.assertEquals(a.hashCode(), b.hashCode());
+    Assert.assertFalse(a.equals(null));
+    Assert.assertFalse(a.equals(new Object()));
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/common/TestTypes.java b/gson/src/test/java/com/google/gson/common/TestTypes.java
new file mode 100644
index 0000000..11d3d0a
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/common/TestTypes.java
@@ -0,0 +1,421 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.common;
+
+import java.lang.reflect.Type;
+import java.util.Collection;
+
+import com.google.gson.JsonDeserializationContext;
+import com.google.gson.JsonDeserializer;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParseException;
+import com.google.gson.JsonPrimitive;
+import com.google.gson.JsonSerializationContext;
+import com.google.gson.JsonSerializer;
+import com.google.gson.annotations.SerializedName;
+
+/**
+ * Types used for testing JSON serialization and deserialization
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public class TestTypes {
+  
+  public static class Base {
+    public static final String BASE_NAME = Base.class.getSimpleName();
+    public static final String BASE_FIELD_KEY = "baseName";
+    public static final String SERIALIZER_KEY = "serializerName";
+    public String baseName = BASE_NAME;
+    public String serializerName;
+  }
+
+  public static class Sub extends Base {
+    public static final String SUB_NAME = Sub.class.getSimpleName();
+    public static final String SUB_FIELD_KEY = "subName";
+    public final String subName = SUB_NAME;
+  }
+
+  public static class ClassWithBaseField {
+    public static final String FIELD_KEY = "base";
+    public final Base base;
+    public ClassWithBaseField(Base base) {
+      this.base = base;
+    }
+  }
+
+  public static class ClassWithBaseArrayField {
+    public static final String FIELD_KEY = "base";
+    public final Base[] base;
+    public ClassWithBaseArrayField(Base[] base) {
+      this.base = base;
+    }
+  }
+
+  public static class ClassWithBaseCollectionField {
+    public static final String FIELD_KEY = "base";
+    public final Collection<Base> base;
+    public ClassWithBaseCollectionField(Collection<Base> base) {
+      this.base = base;
+    }
+  }
+
+  public static class BaseSerializer implements JsonSerializer<Base> {
+    public static final String NAME = BaseSerializer.class.getSimpleName(); 
+    @Override
+    public JsonElement serialize(Base src, Type typeOfSrc, JsonSerializationContext context) {
+      JsonObject obj = new JsonObject();
+      obj.addProperty(Base.SERIALIZER_KEY, NAME);
+      return obj;
+    }
+  }
+  public static class SubSerializer implements JsonSerializer<Sub> {
+    public static final String NAME = SubSerializer.class.getSimpleName(); 
+    @Override
+    public JsonElement serialize(Sub src, Type typeOfSrc, JsonSerializationContext context) {
+      JsonObject obj = new JsonObject();
+      obj.addProperty(Base.SERIALIZER_KEY, NAME);
+      return obj;
+    }    
+  }
+
+  public static class StringWrapper {
+    public final String someConstantStringInstanceField;
+
+    public StringWrapper(String value) {
+      someConstantStringInstanceField = value;
+    }
+  }
+
+  public static class BagOfPrimitives {
+    public static final long DEFAULT_VALUE = 0;
+    public long longValue;
+    public int intValue;
+    public boolean booleanValue;
+    public String stringValue;
+
+    public BagOfPrimitives() {
+      this(DEFAULT_VALUE, 0, false, "");
+    }
+
+    public BagOfPrimitives(long longValue, int intValue, boolean booleanValue, String stringValue) {
+      this.longValue = longValue;
+      this.intValue = intValue;
+      this.booleanValue = booleanValue;
+      this.stringValue = stringValue;
+    }
+
+    public int getIntValue() {
+      return intValue;
+    }
+
+    public String getExpectedJson() {
+      StringBuilder sb = new StringBuilder();
+      sb.append("{");
+      sb.append("\"longValue\":").append(longValue).append(",");
+      sb.append("\"intValue\":").append(intValue).append(",");
+      sb.append("\"booleanValue\":").append(booleanValue).append(",");
+      sb.append("\"stringValue\":\"").append(stringValue).append("\"");
+      sb.append("}");
+      return sb.toString();
+    }
+
+    @Override
+    public int hashCode() {
+      final int prime = 31;
+      int result = 1;
+      result = prime * result + (booleanValue ? 1231 : 1237);
+      result = prime * result + intValue;
+      result = prime * result + (int) (longValue ^ (longValue >>> 32));
+      result = prime * result + ((stringValue == null) ? 0 : stringValue.hashCode());
+      return result;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+      if (this == obj)
+        return true;
+      if (obj == null)
+        return false;
+      if (getClass() != obj.getClass())
+        return false;
+      BagOfPrimitives other = (BagOfPrimitives) obj;
+      if (booleanValue != other.booleanValue)
+        return false;
+      if (intValue != other.intValue)
+        return false;
+      if (longValue != other.longValue)
+        return false;
+      if (stringValue == null) {
+        if (other.stringValue != null)
+          return false;
+      } else if (!stringValue.equals(other.stringValue))
+        return false;
+      return true;
+    }
+
+    @Override
+    public String toString() {
+      return String.format("(longValue=%d,intValue=%d,booleanValue=%b,stringValue=%s)",
+          longValue, intValue, booleanValue, stringValue);
+    }
+  }
+
+  public static class BagOfPrimitiveWrappers {
+    private final Long longValue;
+    private final Integer intValue;
+    private final Boolean booleanValue;
+
+    public BagOfPrimitiveWrappers(Long longValue, Integer intValue, Boolean booleanValue) {
+      this.longValue = longValue;
+      this.intValue = intValue;
+      this.booleanValue = booleanValue;
+    }
+
+    public String getExpectedJson() {
+      StringBuilder sb = new StringBuilder();
+      sb.append("{");
+      sb.append("\"longValue\":").append(longValue).append(",");
+      sb.append("\"intValue\":").append(intValue).append(",");
+      sb.append("\"booleanValue\":").append(booleanValue);
+      sb.append("}");
+      return sb.toString();
+    }
+  }
+
+  public static class PrimitiveArray {
+    private final long[] longArray;
+
+    public PrimitiveArray() {
+      this(new long[0]);
+    }
+
+    public PrimitiveArray(long[] longArray) {
+      this.longArray = longArray;
+    }
+
+    public String getExpectedJson() {
+      StringBuilder sb = new StringBuilder();
+      sb.append("{\"longArray\":[");
+
+      boolean first = true;
+      for (long l : longArray) {
+        if (!first) {
+          sb.append(",");
+        } else {
+          first = false;
+        }
+        sb.append(l);
+      }
+
+      sb.append("]}");
+      return sb.toString();
+    }
+  }
+
+  public static class ClassWithNoFields {
+    // Nothing here..
+    @Override
+    public boolean equals(Object other) {
+      return other.getClass() == ClassWithNoFields.class;
+    }
+  }
+
+  public static class Nested {
+    private final BagOfPrimitives primitive1;
+    private final BagOfPrimitives primitive2;
+
+    public Nested() {
+      this(null, null);
+    }
+
+    public Nested(BagOfPrimitives primitive1, BagOfPrimitives primitive2) {
+      this.primitive1 = primitive1;
+      this.primitive2 = primitive2;
+    }
+
+    public String getExpectedJson() {
+      StringBuilder sb = new StringBuilder();
+      sb.append("{");
+      appendFields(sb);
+      sb.append("}");
+      return sb.toString();
+    }
+
+    public void appendFields(StringBuilder sb) {
+      if (primitive1 != null) {
+        sb.append("\"primitive1\":").append(primitive1.getExpectedJson());
+      }
+      if (primitive1 != null && primitive2 != null) {
+        sb.append(",");
+      }
+      if (primitive2 != null) {
+        sb.append("\"primitive2\":").append(primitive2.getExpectedJson());
+      }
+    }
+  }
+
+  public static class ClassWithTransientFields<T> {
+    public transient T transientT; 
+    public final transient long transientLongValue;
+    private final long[] longValue;
+
+    public ClassWithTransientFields() {
+      this(0L);
+    }
+
+    public ClassWithTransientFields(long value) {
+      longValue = new long[] { value };
+      transientLongValue = value + 1;
+    }
+
+    public String getExpectedJson() {
+      StringBuilder sb = new StringBuilder();
+      sb.append("{");
+      sb.append("\"longValue\":[").append(longValue[0]).append("]");
+      sb.append("}");
+      return sb.toString();
+    }
+  }
+
+  public static class ClassWithCustomTypeConverter {
+    private final BagOfPrimitives bag;
+    private final int value;
+
+    public ClassWithCustomTypeConverter() {
+      this(new BagOfPrimitives(), 10);
+    }
+
+    public ClassWithCustomTypeConverter(int value) {
+      this(new BagOfPrimitives(value, value, false, ""), value);
+    }
+
+    public ClassWithCustomTypeConverter(BagOfPrimitives bag, int value) {
+      this.bag = bag;
+      this.value = value;
+    }
+
+    public BagOfPrimitives getBag() {
+      return bag;
+    }
+
+    public String getExpectedJson() {
+      return "{\"url\":\"" + bag.getExpectedJson() + "\",\"value\":" + value + "}";
+    }
+
+    public int getValue() {
+      return value;
+    }
+  }
+
+  public static class ArrayOfObjects {
+    private final BagOfPrimitives[] elements;
+    public ArrayOfObjects() {
+      elements = new BagOfPrimitives[3];
+      for (int i = 0; i < elements.length; ++i) {
+        elements[i] = new BagOfPrimitives(i, i+2, false, "i"+i);
+      }
+    }
+    public String getExpectedJson() {
+      StringBuilder sb = new StringBuilder("{\"elements\":[");
+      boolean first = true;
+      for (BagOfPrimitives element : elements) {
+        if (first) {
+          first = false;
+        } else {
+          sb.append(",");
+        }
+        sb.append(element.getExpectedJson());
+      }
+      sb.append("]}");
+      return sb.toString();
+    }
+  }
+
+  public static class ClassOverridingEquals {
+    public ClassOverridingEquals ref;
+
+    public String getExpectedJson() {
+      if (ref == null) {
+        return "{}";
+      }
+      return "{\"ref\":" + ref.getExpectedJson() + "}";
+    }
+    @Override
+    public boolean equals(Object obj) {
+      return true;
+    }
+
+    @Override
+    public int hashCode() {
+      return 1;
+    }
+  }
+
+  public static class ClassWithArray {
+    public final Object[] array;
+    public ClassWithArray() {
+      array = null;
+    }
+
+    public ClassWithArray(Object[] array) {
+      this.array = array;
+    }
+  }
+
+  public static class ClassWithObjects {
+    public final BagOfPrimitives bag;
+    public ClassWithObjects() {
+      this(new BagOfPrimitives());
+    }
+    public ClassWithObjects(BagOfPrimitives bag) {
+      this.bag = bag;
+    }
+  }
+
+  public static class ClassWithSerializedNameFields {
+    @SerializedName("fooBar") public final int f;
+    @SerializedName("Another Foo") public final int g;
+
+    public ClassWithSerializedNameFields() {
+      this(1, 4);
+    }
+    public ClassWithSerializedNameFields(int f, int g) {
+      this.f = f;
+      this.g = g;
+    }
+
+    public String getExpectedJson() {
+      return '{' + "\"fooBar\":" + f + ",\"Another Foo\":" + g + '}';
+    }
+  }
+
+  public static class CrazyLongTypeAdapter
+      implements JsonSerializer<Long>, JsonDeserializer<Long> {
+    public static final long DIFFERENCE = 5L;
+    @Override
+    public JsonElement serialize(Long src, Type typeOfSrc, JsonSerializationContext context) {
+      return new JsonPrimitive(src + DIFFERENCE);
+    }
+    @Override
+    public Long deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
+        throws JsonParseException {
+      return json.getAsLong() - DIFFERENCE;
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/ArrayTest.java b/gson/src/test/java/com/google/gson/functional/ArrayTest.java
new file mode 100644
index 0000000..da8be85
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/ArrayTest.java
@@ -0,0 +1,268 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.functional;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonParseException;
+import com.google.gson.common.TestTypes.BagOfPrimitives;
+import com.google.gson.common.TestTypes.ClassWithObjects;
+import com.google.gson.reflect.TypeToken;
+
+import junit.framework.TestCase;
+import static org.junit.Assert.assertArrayEquals;
+
+import java.lang.reflect.Type;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collection;
+/**
+ * Functional tests for Json serialization and deserialization of arrays.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public class ArrayTest extends TestCase {
+  private Gson gson;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    gson = new Gson();
+  }
+
+  public void testTopLevelArrayOfIntsSerialization() {
+    int[] target = {1, 2, 3, 4, 5, 6, 7, 8, 9};
+    assertEquals("[1,2,3,4,5,6,7,8,9]", gson.toJson(target));
+  }
+
+  public void testTopLevelArrayOfIntsDeserialization() {
+    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);
+    assertArrayEquals(expected, actual);
+  }
+
+  public void testInvalidArrayDeserialization() {
+    String json = "[1, 2 3, 4, 5]";
+    try {
+      gson.fromJson(json, int[].class);
+      fail("Gson should not deserialize array elements with missing ,");
+    } catch (JsonParseException expected) {
+    }
+  }
+
+  public void testEmptyArraySerialization() {
+    int[] target = {};
+    assertEquals("[]", gson.toJson(target));
+  }
+
+  public void testEmptyArrayDeserialization() {
+    int[] actualObject = gson.fromJson("[]", int[].class);
+    assertTrue(actualObject.length == 0);
+
+    Integer[] actualObject2 = gson.fromJson("[]", Integer[].class);
+    assertTrue(actualObject2.length == 0);
+
+    actualObject = gson.fromJson("[ ]", int[].class);
+    assertTrue(actualObject.length == 0);
+  }
+
+  public void testNullsInArraySerialization() {
+    String[] array = {"foo", null, "bar"};
+    String expected = "[\"foo\",null,\"bar\"]";
+    String json = gson.toJson(array);
+    assertEquals(expected, json);
+  }
+
+  public void testNullsInArrayDeserialization() {
+    String json = "[\"foo\",null,\"bar\"]";
+    String[] expected = {"foo", null, "bar"};
+    String[] target = gson.fromJson(json, expected.getClass());
+    for (int i = 0; i < expected.length; ++i) {
+      assertEquals(expected[i], target[i]);
+    }
+  }
+
+  public void testSingleNullInArraySerialization() {
+    BagOfPrimitives[] array = new BagOfPrimitives[1];
+    array[0] = null;
+    String json = gson.toJson(array);
+    assertEquals("[null]", json);
+  }
+
+  public void testSingleNullInArrayDeserialization() {
+    BagOfPrimitives[] array = gson.fromJson("[null]", BagOfPrimitives[].class);
+    assertNull(array[0]);
+  }
+
+  public void testNullsInArrayWithSerializeNullPropertySetSerialization() {
+    gson = new GsonBuilder().serializeNulls().create();
+    String[] array = {"foo", null, "bar"};
+    String expected = "[\"foo\",null,\"bar\"]";
+    String json = gson.toJson(array);
+    assertEquals(expected, json);
+  }
+
+  public void testArrayOfStringsSerialization() {
+    String[] target = {"Hello", "World"};
+    assertEquals("[\"Hello\",\"World\"]", gson.toJson(target));
+  }
+
+  public void testArrayOfStringsDeserialization() {
+    String json = "[\"Hello\",\"World\"]";
+    String[] target = gson.fromJson(json, String[].class);
+    assertEquals("Hello", target[0]);
+    assertEquals("World", target[1]);
+  }
+
+  public void testSingleStringArraySerialization() throws Exception {
+    String[] s = { "hello" };
+    String output = gson.toJson(s);
+    assertEquals("[\"hello\"]", output);
+  }
+
+  public void testSingleStringArrayDeserialization() throws Exception {
+    String json = "[\"hello\"]";
+    String[] arrayType = gson.fromJson(json, String[].class);
+    assertEquals(1, arrayType.length);
+    assertEquals("hello", arrayType[0]);
+  }
+
+  @SuppressWarnings("unchecked")
+  public void testArrayOfCollectionSerialization() throws Exception {
+    StringBuilder sb = new StringBuilder("[");
+    int arraySize = 3;
+
+    Type typeToSerialize = new TypeToken<Collection<Integer>[]>() {}.getType();
+    Collection<Integer>[] arrayOfCollection = new ArrayList[arraySize];
+    for (int i = 0; i < arraySize; ++i) {
+      int startValue = (3 * i) + 1;
+      sb.append('[').append(startValue).append(',').append(startValue + 1).append(']');
+      ArrayList<Integer> tmpList = new ArrayList<>();
+      tmpList.add(startValue);
+      tmpList.add(startValue + 1);
+      arrayOfCollection[i] = tmpList;
+
+      if (i < arraySize - 1) {
+        sb.append(',');
+      }
+    }
+    sb.append(']');
+
+    String json = gson.toJson(arrayOfCollection, typeToSerialize);
+    assertEquals(sb.toString(), json);
+  }
+
+  public void testArrayOfCollectionDeserialization() throws Exception {
+    String json = "[[1,2],[3,4]]";
+    Type type = new TypeToken<Collection<Integer>[]>() {}.getType();
+    Collection<Integer>[] target = gson.fromJson(json, type);
+
+    assertEquals(2, target.length);
+    assertArrayEquals(new Integer[] { 1, 2 }, target[0].toArray(new Integer[0]));
+    assertArrayEquals(new Integer[] { 3, 4 }, target[1].toArray(new Integer[0]));
+  }
+
+  public void testArrayOfPrimitivesAsObjectsSerialization() throws Exception {
+    Object[] objs = new Object[] {1, "abc", 0.3f, 5L};
+    String json = gson.toJson(objs);
+    assertTrue(json.contains("abc"));
+    assertTrue(json.contains("0.3"));
+    assertTrue(json.contains("5"));
+  }
+
+  public void testArrayOfPrimitivesAsObjectsDeserialization() throws Exception {
+    String json = "[1,'abc',0.3,1.1,5]";
+    Object[] objs = gson.fromJson(json, Object[].class);
+    assertEquals(1, ((Number)objs[0]).intValue());
+    assertEquals("abc", objs[1]);
+    assertEquals(0.3, ((Number)objs[2]).doubleValue());
+    assertEquals(new BigDecimal("1.1"), new BigDecimal(objs[3].toString()));
+    assertEquals(5, ((Number)objs[4]).shortValue());
+  }
+
+  public void testObjectArrayWithNonPrimitivesSerialization() throws Exception {
+    ClassWithObjects classWithObjects = new ClassWithObjects();
+    BagOfPrimitives bagOfPrimitives = new BagOfPrimitives();
+    String classWithObjectsJson = gson.toJson(classWithObjects);
+    String bagOfPrimitivesJson = gson.toJson(bagOfPrimitives);
+
+    Object[] objects = new Object[] { classWithObjects, bagOfPrimitives };
+    String json = gson.toJson(objects);
+
+    assertTrue(json.contains(classWithObjectsJson));
+    assertTrue(json.contains(bagOfPrimitivesJson));
+  }
+
+  public void testArrayOfNullSerialization() {
+    Object[] array = new Object[] {null};
+    String json = gson.toJson(array);
+    assertEquals("[null]", json);
+  }
+
+  public void testArrayOfNullDeserialization() {
+    String[] values = gson.fromJson("[null]", String[].class);
+    assertNull(values[0]);
+  }
+
+  /**
+   * Regression tests for Issue 272
+   */
+  public void testMultidimenstionalArraysSerialization() {
+    String[][] items = new String[][]{
+        {"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"}
+    };
+    String json = gson.toJson(items);
+    assertTrue(json.contains("[[\"3m Co"));
+    assertTrue(json.contains("Manufacturing\"]]"));
+  }
+
+  public void testMultiDimenstionalObjectArraysSerialization() {
+    Object[][] array = new Object[][] { new Object[] { 1, 2 } };
+    assertEquals("[[1,2]]", gson.toJson(array));
+  }
+
+  /**
+   * Regression test for Issue 205
+   */
+  public void testMixingTypesInObjectArraySerialization() {
+    Object[] array = new Object[] { 1, 2, new Object[] { "one", "two", 3 } };
+    assertEquals("[1,2,[\"one\",\"two\",3]]", gson.toJson(array));
+  }
+
+  /**
+   * Regression tests for Issue 272
+   */
+  public void testMultidimenstionalArraysDeserialization() {
+    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']]";
+    String[][] items = gson.fromJson(json, String[][].class);
+    assertEquals("3m Co", items[0][0]);
+    assertEquals("Manufacturing", items[1][5]);
+  }
+
+  /** http://code.google.com/p/google-gson/issues/detail?id=342 */
+  public void testArrayElementsAreArrays() {
+    Object[] stringArrays = {
+        new String[] {"test1", "test2"},
+        new String[] {"test3", "test4"}
+    };
+    assertEquals("[[\"test1\",\"test2\"],[\"test3\",\"test4\"]]",
+        new Gson().toJson(stringArrays));
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/CircularReferenceTest.java b/gson/src/test/java/com/google/gson/functional/CircularReferenceTest.java
new file mode 100644
index 0000000..f441955
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/CircularReferenceTest.java
@@ -0,0 +1,126 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.functional;
+
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.Collection;
+
+import junit.framework.TestCase;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonSerializationContext;
+import com.google.gson.JsonSerializer;
+import com.google.gson.common.TestTypes.ClassOverridingEquals;
+
+/**
+ * Functional tests related to circular reference detection and error reporting.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public class CircularReferenceTest extends TestCase {
+  private Gson gson;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    gson = new Gson();
+  }
+
+  public void testCircularSerialization() throws Exception {
+    ContainsReferenceToSelfType a = new ContainsReferenceToSelfType();
+    ContainsReferenceToSelfType b = new ContainsReferenceToSelfType();
+    a.children.add(b);
+    b.children.add(a);
+    try {
+      gson.toJson(a);
+      fail("Circular types should not get printed!");
+    } catch (StackOverflowError expected) {
+    }
+  }
+
+  public void testSelfReferenceIgnoredInSerialization() throws Exception {
+    ClassOverridingEquals objA = new ClassOverridingEquals();
+    objA.ref = objA;
+
+    String json = gson.toJson(objA);
+    assertFalse(json.contains("ref")); // self-reference is ignored
+  }
+
+  public void testSelfReferenceArrayFieldSerialization() throws Exception {
+    ClassWithSelfReferenceArray objA = new ClassWithSelfReferenceArray();
+    objA.children = new ClassWithSelfReferenceArray[]{objA};
+
+    try {
+      gson.toJson(objA);
+      fail("Circular reference to self can not be serialized!");
+    } catch (StackOverflowError expected) {
+    }
+  }
+
+  public void testSelfReferenceCustomHandlerSerialization() throws Exception {
+    ClassWithSelfReference obj = new ClassWithSelfReference();
+    obj.child = obj;
+    Gson gson = new GsonBuilder().registerTypeAdapter(ClassWithSelfReference.class, new JsonSerializer<ClassWithSelfReference>() {
+      @Override public JsonElement serialize(ClassWithSelfReference src, Type typeOfSrc,
+          JsonSerializationContext context) {
+        JsonObject obj = new JsonObject();
+        obj.addProperty("property", "value");
+        obj.add("child", context.serialize(src.child));
+        return obj;
+      }
+    }).create();
+    try {
+      gson.toJson(obj);
+      fail("Circular reference to self can not be serialized!");
+    } catch (StackOverflowError expected) {
+    }
+  }
+
+  public void testDirectedAcyclicGraphSerialization() throws Exception {
+    ContainsReferenceToSelfType a = new ContainsReferenceToSelfType();
+    ContainsReferenceToSelfType b = new ContainsReferenceToSelfType();
+    ContainsReferenceToSelfType c = new ContainsReferenceToSelfType();
+    a.children.add(b);
+    a.children.add(c);
+    b.children.add(c);
+    assertNotNull(gson.toJson(a));
+  }
+
+  public void testDirectedAcyclicGraphDeserialization() throws Exception {
+    String json = "{\"children\":[{\"children\":[{\"children\":[]}]},{\"children\":[]}]}";
+    ContainsReferenceToSelfType target = gson.fromJson(json, ContainsReferenceToSelfType.class);
+    assertNotNull(target);
+    assertEquals(2, target.children.size());
+  }
+
+  private static class ContainsReferenceToSelfType {
+    Collection<ContainsReferenceToSelfType> children = new ArrayList<>();
+  }
+
+  private static class ClassWithSelfReference {
+    ClassWithSelfReference child;
+  }
+
+  private static class ClassWithSelfReferenceArray {
+    @SuppressWarnings("unused")
+    ClassWithSelfReferenceArray[] children;
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/CollectionTest.java b/gson/src/test/java/com/google/gson/functional/CollectionTest.java
new file mode 100644
index 0000000..f113b85
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/CollectionTest.java
@@ -0,0 +1,415 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.functional;
+
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.PriorityQueue;
+import java.util.Queue;
+import java.util.Set;
+import java.util.Stack;
+import java.util.Vector;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonPrimitive;
+import com.google.gson.JsonSerializationContext;
+import com.google.gson.JsonSerializer;
+import com.google.gson.common.TestTypes.BagOfPrimitives;
+import com.google.gson.reflect.TypeToken;
+
+import junit.framework.TestCase;
+import static org.junit.Assert.assertArrayEquals;
+
+/**
+ * Functional tests for Json serialization and deserialization of collections.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public class CollectionTest extends TestCase {
+  private Gson gson;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    gson = new Gson();
+  }
+
+  public void testTopLevelCollectionOfIntegersSerialization() {
+    Collection<Integer> target = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
+    Type targetType = new TypeToken<Collection<Integer>>() {}.getType();
+    String json = gson.toJson(target, targetType);
+    assertEquals("[1,2,3,4,5,6,7,8,9]", json);
+  }
+
+  public void testTopLevelCollectionOfIntegersDeserialization() {
+    String json = "[0,1,2,3,4,5,6,7,8,9]";
+    Type collectionType = new TypeToken<Collection<Integer>>() { }.getType();
+    Collection<Integer> target = gson.fromJson(json, collectionType);
+    int[] expected = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
+    assertArrayEquals(expected, toIntArray(target));
+  }
+
+  public void testTopLevelListOfIntegerCollectionsDeserialization() throws Exception {
+    String json = "[[1,2,3],[4,5,6],[7,8,9]]";
+    Type collectionType = new TypeToken<Collection<Collection<Integer>>>() {}.getType();
+    List<Collection<Integer>> target = gson.fromJson(json, collectionType);
+    int[][] expected = new int[3][3];
+    for (int i = 0; i < 3; ++i) {
+      int start = (3 * i) + 1;
+      for (int j = 0; j < 3; ++j) {
+        expected[i][j] = start + j;
+      }
+    }
+
+    for (int i = 0; i < 3; i++) {
+      assertArrayEquals(expected[i], toIntArray(target.get(i)));
+    }
+  }
+
+  public void testLinkedListSerialization() {
+    List<String> list = new LinkedList<>();
+    list.add("a1");
+    list.add("a2");
+    Type linkedListType = new TypeToken<LinkedList<String>>() {}.getType();
+    String json = gson.toJson(list, linkedListType);
+    assertTrue(json.contains("a1"));
+    assertTrue(json.contains("a2"));
+  }
+
+  public void testLinkedListDeserialization() {
+    String json = "['a1','a2']";
+    Type linkedListType = new TypeToken<LinkedList<String>>() {}.getType();
+    List<String> list = gson.fromJson(json, linkedListType);
+    assertEquals("a1", list.get(0));
+    assertEquals("a2", list.get(1));
+  }
+
+  public void testQueueSerialization() {
+    Queue<String> queue = new LinkedList<>();
+    queue.add("a1");
+    queue.add("a2");
+    Type queueType = new TypeToken<Queue<String>>() {}.getType();
+    String json = gson.toJson(queue, queueType);
+    assertTrue(json.contains("a1"));
+    assertTrue(json.contains("a2"));
+  }
+
+  public void testQueueDeserialization() {
+    String json = "['a1','a2']";
+    Type queueType = new TypeToken<Queue<String>>() {}.getType();
+    Queue<String> queue = gson.fromJson(json, queueType);
+    assertEquals("a1", queue.element());
+    queue.remove();
+    assertEquals("a2", queue.element());
+  }
+
+  public void testPriorityQueue() throws Exception {
+    Type type = new TypeToken<PriorityQueue<Integer>>(){}.getType();
+    PriorityQueue<Integer> queue = gson.fromJson("[10, 20, 22]", type);
+    assertEquals(3, queue.size());
+    String json = gson.toJson(queue);
+    assertEquals(10, queue.remove().intValue());
+    assertEquals(20, queue.remove().intValue());
+    assertEquals(22, queue.remove().intValue());
+    assertEquals("[10,20,22]", json);
+  }
+
+  public void testVector() {
+    Type type = new TypeToken<Vector<Integer>>(){}.getType();
+    Vector<Integer> target = gson.fromJson("[10, 20, 31]", type);
+    assertEquals(3, target.size());
+    assertEquals(10, target.get(0).intValue());
+    assertEquals(20, target.get(1).intValue());
+    assertEquals(31, target.get(2).intValue());
+    String json = gson.toJson(target);
+    assertEquals("[10,20,31]", json);
+  }
+
+  public void testStack() {
+    Type type = new TypeToken<Stack<Integer>>(){}.getType();
+    Stack<Integer> target = gson.fromJson("[11, 13, 17]", type);
+    assertEquals(3, target.size());
+    String json = gson.toJson(target);
+    assertEquals(17, target.pop().intValue());
+    assertEquals(13, target.pop().intValue());
+    assertEquals(11, target.pop().intValue());
+    assertEquals("[11,13,17]", json);
+  }
+
+  public void testNullsInListSerialization() {
+    List<String> list = new ArrayList<>();
+    list.add("foo");
+    list.add(null);
+    list.add("bar");
+    String expected = "[\"foo\",null,\"bar\"]";
+    Type typeOfList = new TypeToken<List<String>>() {}.getType();
+    String json = gson.toJson(list, typeOfList);
+    assertEquals(expected, json);
+  }
+
+  public void testNullsInListDeserialization() {
+    List<String> expected = new ArrayList<>();
+    expected.add("foo");
+    expected.add(null);
+    expected.add("bar");
+    String json = "[\"foo\",null,\"bar\"]";
+    Type expectedType = new TypeToken<List<String>>() {}.getType();
+    List<String> target = gson.fromJson(json, expectedType);
+    for (int i = 0; i < expected.size(); ++i) {
+      assertEquals(expected.get(i), target.get(i));
+    }
+  }
+
+  public void testCollectionOfObjectSerialization() {
+    List<Object> target = new ArrayList<>();
+    target.add("Hello");
+    target.add("World");
+    assertEquals("[\"Hello\",\"World\"]", gson.toJson(target));
+
+    Type type = new TypeToken<List<Object>>() {}.getType();
+    assertEquals("[\"Hello\",\"World\"]", gson.toJson(target, type));
+  }
+
+  public void testCollectionOfObjectWithNullSerialization() {
+    List<Object> target = new ArrayList<>();
+    target.add("Hello");
+    target.add(null);
+    target.add("World");
+    assertEquals("[\"Hello\",null,\"World\"]", gson.toJson(target));
+
+    Type type = new TypeToken<List<Object>>() {}.getType();
+    assertEquals("[\"Hello\",null,\"World\"]", gson.toJson(target, type));
+  }
+
+  public void testCollectionOfStringsSerialization() {
+    List<String> target = new ArrayList<>();
+    target.add("Hello");
+    target.add("World");
+    assertEquals("[\"Hello\",\"World\"]", gson.toJson(target));
+  }
+
+  public void testCollectionOfBagOfPrimitivesSerialization() {
+    List<BagOfPrimitives> target = new ArrayList<>();
+    BagOfPrimitives objA = new BagOfPrimitives(3L, 1, true, "blah");
+    BagOfPrimitives objB = new BagOfPrimitives(2L, 6, false, "blahB");
+    target.add(objA);
+    target.add(objB);
+
+    String result = gson.toJson(target);
+    assertTrue(result.startsWith("["));
+    assertTrue(result.endsWith("]"));
+    for (BagOfPrimitives obj : target) {
+      assertTrue(result.contains(obj.getExpectedJson()));
+    }
+  }
+
+  public void testCollectionOfStringsDeserialization() {
+    String json = "[\"Hello\",\"World\"]";
+    Type collectionType = new TypeToken<Collection<String>>() { }.getType();
+    Collection<String> target = gson.fromJson(json, collectionType);
+
+    assertTrue(target.contains("Hello"));
+    assertTrue(target.contains("World"));
+  }
+
+  public void testRawCollectionOfIntegersSerialization() {
+    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));
+  }
+
+  @SuppressWarnings("rawtypes")
+  public void testRawCollectionSerialization() {
+    BagOfPrimitives bag1 = new BagOfPrimitives();
+    Collection target = Arrays.asList(bag1, bag1);
+    String json = gson.toJson(target);
+    assertTrue(json.contains(bag1.getExpectedJson()));
+  }
+
+  @SuppressWarnings("rawtypes")
+  public void testRawCollectionDeserializationNotAlllowed() {
+    String json = "[0,1,2,3,4,5,6,7,8,9]";
+    Collection integers = gson.fromJson(json, Collection.class);
+    // JsonReader converts numbers to double by default so we need a floating point comparison
+    assertEquals(Arrays.asList(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0), integers);
+
+    json = "[\"Hello\", \"World\"]";
+    Collection strings = gson.fromJson(json, Collection.class);
+    assertTrue(strings.contains("Hello"));
+    assertTrue(strings.contains("World"));
+  }
+
+  @SuppressWarnings({"rawtypes", "unchecked"})
+  public void testRawCollectionOfBagOfPrimitivesNotAllowed() {
+    BagOfPrimitives bag = new BagOfPrimitives(10, 20, false, "stringValue");
+    String json = '[' + bag.getExpectedJson() + ',' + bag.getExpectedJson() + ']';
+    Collection target = gson.fromJson(json, Collection.class);
+    assertEquals(2, target.size());
+    for (Object bag1 : target) {
+      // Gson 2.0 converts raw objects into maps
+      Map<String, Object> values = (Map<String, Object>) bag1;
+      assertTrue(values.containsValue(10.0));
+      assertTrue(values.containsValue(20.0));
+      assertTrue(values.containsValue("stringValue"));
+    }
+  }
+
+  public void testWildcardPrimitiveCollectionSerilaization() throws Exception {
+    Collection<? extends Integer> target = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
+    Type collectionType = new TypeToken<Collection<? extends Integer>>() { }.getType();
+    String json = gson.toJson(target, collectionType);
+    assertEquals("[1,2,3,4,5,6,7,8,9]", json);
+
+    json = gson.toJson(target);
+    assertEquals("[1,2,3,4,5,6,7,8,9]", json);
+  }
+
+  public void testWildcardPrimitiveCollectionDeserilaization() throws Exception {
+    String json = "[1,2,3,4,5,6,7,8,9]";
+    Type collectionType = new TypeToken<Collection<? extends Integer>>() { }.getType();
+    Collection<? extends Integer> target = gson.fromJson(json, collectionType);
+    assertEquals(9, target.size());
+    assertTrue(target.contains(1));
+    assertTrue(target.contains(9));
+  }
+
+  public void testWildcardCollectionField() throws Exception {
+    Collection<BagOfPrimitives> collection = new ArrayList<>();
+    BagOfPrimitives objA = new BagOfPrimitives(3L, 1, true, "blah");
+    BagOfPrimitives objB = new BagOfPrimitives(2L, 6, false, "blahB");
+    collection.add(objA);
+    collection.add(objB);
+
+    ObjectWithWildcardCollection target = new ObjectWithWildcardCollection(collection);
+    String json = gson.toJson(target);
+    assertTrue(json.contains(objA.getExpectedJson()));
+    assertTrue(json.contains(objB.getExpectedJson()));
+
+    target = gson.fromJson(json, ObjectWithWildcardCollection.class);
+    Collection<? extends BagOfPrimitives> deserializedCollection = target.getCollection();
+    assertEquals(2, deserializedCollection.size());
+    assertTrue(deserializedCollection.contains(objA));
+    assertTrue(deserializedCollection.contains(objB));
+  }
+
+  public void testFieldIsArrayList() {
+    HasArrayListField object = new HasArrayListField();
+    object.longs.add(1L);
+    object.longs.add(3L);
+    String json = gson.toJson(object, HasArrayListField.class);
+    assertEquals("{\"longs\":[1,3]}", json);
+    HasArrayListField copy = gson.fromJson("{\"longs\":[1,3]}", HasArrayListField.class);
+    assertEquals(Arrays.asList(1L, 3L), copy.longs);
+  }
+  
+  public void testUserCollectionTypeAdapter() {
+    Type listOfString = new TypeToken<List<String>>() {}.getType();
+    Object stringListSerializer = new JsonSerializer<List<String>>() {
+      @Override public JsonElement serialize(List<String> src, Type typeOfSrc,
+          JsonSerializationContext context) {
+        return new JsonPrimitive(src.get(0) + ";" + src.get(1));
+      }
+    };
+    Gson gson = new GsonBuilder()
+        .registerTypeAdapter(listOfString, stringListSerializer)
+        .create();
+    assertEquals("\"ab;cd\"", gson.toJson(Arrays.asList("ab", "cd"), listOfString));
+  }
+
+  static class HasArrayListField {
+    ArrayList<Long> longs = new ArrayList<>();
+  }
+
+  @SuppressWarnings("rawtypes")
+  private static int[] toIntArray(Collection collection) {
+    int[] ints = new int[collection.size()];
+    int i = 0;
+    for (Iterator iterator = collection.iterator(); iterator.hasNext(); ++i) {
+      Object obj = iterator.next();
+      if (obj instanceof Integer) {
+        ints[i] = ((Integer)obj).intValue();
+      } else if (obj instanceof Long) {
+        ints[i] = ((Long)obj).intValue();
+      }
+    }
+    return ints;
+  }
+
+  private static class ObjectWithWildcardCollection {
+    private final Collection<? extends BagOfPrimitives> collection;
+
+    public ObjectWithWildcardCollection(Collection<? extends BagOfPrimitives> collection) {
+      this.collection = collection;
+    }
+
+    public Collection<? extends BagOfPrimitives> getCollection() {
+      return collection;
+    }
+  }
+
+  private static class Entry {
+    int value;
+    Entry(int value) {
+      this.value = value;
+    }
+  }
+  public void testSetSerialization() {
+    Set<Entry> set = new HashSet<>();
+    set.add(new Entry(1));
+    set.add(new Entry(2));
+    String json = gson.toJson(set);
+    assertTrue(json.contains("1"));
+    assertTrue(json.contains("2"));
+  }
+  public void testSetDeserialization() {
+    String json = "[{value:1},{value:2}]";
+    Type type = new TypeToken<Set<Entry>>() {}.getType();
+    Set<Entry> set = gson.fromJson(json, type);
+    assertEquals(2, set.size());
+    for (Entry entry : set) {
+      assertTrue(entry.value == 1 || entry.value == 2);
+    }
+  }
+
+  private class BigClass { private Map<String, ? extends List<SmallClass>> inBig; }
+
+  private class SmallClass { private String inSmall; }
+
+  public void testIssue1107() {
+    String json = "{\n" +
+            "  \"inBig\": {\n" +
+            "    \"key\": [\n" +
+            "      { \"inSmall\": \"hello\" }\n" +
+            "    ]\n" +
+            "  }\n" +
+            "}";
+    BigClass bigClass = new Gson().fromJson(json, BigClass.class);
+    SmallClass small = bigClass.inBig.get("key").get(0);
+    assertNotNull(small);
+    assertEquals("hello", small.inSmall);
+  }
+
+}
diff --git a/gson/src/test/java/com/google/gson/functional/ConcurrencyTest.java b/gson/src/test/java/com/google/gson/functional/ConcurrencyTest.java
new file mode 100644
index 0000000..318c6ac
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/ConcurrencyTest.java
@@ -0,0 +1,140 @@
+/*

+ * Copyright (C) 2008 Google Inc.

+ *

+ * Licensed under the Apache License, Version 2.0 (the "License");

+ * you may not use this file except in compliance with the License.

+ * You may obtain a copy of the License at

+ *

+ * http://www.apache.org/licenses/LICENSE-2.0

+ *

+ * Unless required by applicable law or agreed to in writing, software

+ * distributed under the License is distributed on an "AS IS" BASIS,

+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

+ * See the License for the specific language governing permissions and

+ * limitations under the License.

+ */

+package com.google.gson.functional;

+

+import java.util.concurrent.CountDownLatch;

+import java.util.concurrent.ExecutorService;

+import java.util.concurrent.Executors;

+import java.util.concurrent.atomic.AtomicBoolean;

+

+import junit.framework.TestCase;

+

+import com.google.gson.Gson;

+

+/**

+ * Tests for ensuring Gson thread-safety.

+ * 

+ * @author Inderjeet Singh

+ * @author Joel Leitch

+ */

+public class ConcurrencyTest extends TestCase {

+  private Gson gson;

+

+  @Override

+  protected void setUp() throws Exception {

+    super.setUp();

+    gson = new Gson();

+  }

+

+  /**

+   * Source-code based on

+   * http://groups.google.com/group/google-gson/browse_thread/thread/563bb51ee2495081

+   */

+  public void testSingleThreadSerialization() { 

+    MyObject myObj = new MyObject(); 

+    for (int i = 0; i < 10; i++) { 

+      gson.toJson(myObj); 

+    } 

+  } 

+

+  /**

+   * Source-code based on

+   * http://groups.google.com/group/google-gson/browse_thread/thread/563bb51ee2495081

+   */

+  public void testSingleThreadDeserialization() { 

+    for (int i = 0; i < 10; i++) { 

+      gson.fromJson("{'a':'hello','b':'world','i':1}", MyObject.class); 

+    } 

+  } 

+

+  /**

+   * Source-code based on

+   * http://groups.google.com/group/google-gson/browse_thread/thread/563bb51ee2495081

+   */

+  public void testMultiThreadSerialization() throws InterruptedException {

+    final CountDownLatch startLatch = new CountDownLatch(1);

+    final CountDownLatch finishedLatch = new CountDownLatch(10);

+    final AtomicBoolean failed = new AtomicBoolean(false);

+    ExecutorService executor = Executors.newFixedThreadPool(10);

+    for (int taskCount = 0; taskCount < 10; taskCount++) {

+      executor.execute(new Runnable() {

+        @Override public void run() {

+          MyObject myObj = new MyObject();

+          try {

+            startLatch.await();

+            for (int i = 0; i < 10; i++) {

+              gson.toJson(myObj);

+            }

+          } catch (Throwable t) {

+            failed.set(true);

+          } finally {

+            finishedLatch.countDown();

+          }

+        }

+      });

+    }

+    startLatch.countDown();

+    finishedLatch.await();

+    assertFalse(failed.get());

+  }

+

+  /**

+   * Source-code based on

+   * http://groups.google.com/group/google-gson/browse_thread/thread/563bb51ee2495081

+   */

+  public void testMultiThreadDeserialization() throws InterruptedException {

+    final CountDownLatch startLatch = new CountDownLatch(1);

+    final CountDownLatch finishedLatch = new CountDownLatch(10);

+    final AtomicBoolean failed = new AtomicBoolean(false);

+    ExecutorService executor = Executors.newFixedThreadPool(10);

+    for (int taskCount = 0; taskCount < 10; taskCount++) {

+      executor.execute(new Runnable() {

+        @Override public void run() {

+          try {

+            startLatch.await();

+            for (int i = 0; i < 10; i++) {

+              gson.fromJson("{'a':'hello','b':'world','i':1}", MyObject.class); 

+            }

+          } catch (Throwable t) {

+            failed.set(true);

+          } finally {

+            finishedLatch.countDown();

+          }

+        }

+      });

+    }

+    startLatch.countDown();

+    finishedLatch.await();

+    assertFalse(failed.get());

+  }

+  

+  @SuppressWarnings("unused")

+  private static class MyObject {

+    String a;

+    String b;

+    int i;

+

+    MyObject() {

+      this("hello", "world", 42);

+    }

+

+    public MyObject(String a, String b, int i) {

+      this.a = a;

+      this.b = b;

+      this.i = i;

+    }

+  }

+}

diff --git a/gson/src/test/java/com/google/gson/functional/CustomDeserializerTest.java b/gson/src/test/java/com/google/gson/functional/CustomDeserializerTest.java
new file mode 100644
index 0000000..8134ae2
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/CustomDeserializerTest.java
@@ -0,0 +1,212 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.functional;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonDeserializationContext;
+import com.google.gson.JsonDeserializer;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParseException;
+import com.google.gson.common.TestTypes.Base;
+import com.google.gson.common.TestTypes.ClassWithBaseField;
+
+import junit.framework.TestCase;
+
+import java.lang.reflect.Type;
+
+/**
+ * Functional Test exercising custom deserialization only. When test applies to both
+ * serialization and deserialization then add it to CustomTypeAdapterTest.
+ *
+ * @author Joel Leitch
+ */
+public class CustomDeserializerTest extends TestCase {
+  private static final String DEFAULT_VALUE = "test123";
+  private static final String SUFFIX = "blah";
+
+  private Gson gson;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    gson = new GsonBuilder().registerTypeAdapter(DataHolder.class, new DataHolderDeserializer()).create();
+  }
+
+  public void testDefaultConstructorNotCalledOnObject() throws Exception {
+    DataHolder data = new DataHolder(DEFAULT_VALUE);
+    String json = gson.toJson(data);
+
+    DataHolder actual = gson.fromJson(json, DataHolder.class);
+    assertEquals(DEFAULT_VALUE + SUFFIX, actual.getData());
+  }
+
+  public void testDefaultConstructorNotCalledOnField() throws Exception {
+    DataHolderWrapper dataWrapper = new DataHolderWrapper(new DataHolder(DEFAULT_VALUE));
+    String json = gson.toJson(dataWrapper);
+
+    DataHolderWrapper actual = gson.fromJson(json, DataHolderWrapper.class);
+    assertEquals(DEFAULT_VALUE + SUFFIX, actual.getWrappedData().getData());
+  }
+
+  private static class DataHolder {
+    private final String data;
+
+    // For use by Gson
+    @SuppressWarnings("unused")
+    private DataHolder() {
+      throw new IllegalStateException();
+    }
+
+    public DataHolder(String data) {
+      this.data = data;
+    }
+
+    public String getData() {
+      return data;
+    }
+  }
+
+  private static class DataHolderWrapper {
+    private final DataHolder wrappedData;
+
+    // For use by Gson
+    @SuppressWarnings("unused")
+    private DataHolderWrapper() {
+      this(new DataHolder(DEFAULT_VALUE));
+    }
+
+    public DataHolderWrapper(DataHolder data) {
+      this.wrappedData = data;
+    }
+
+    public DataHolder getWrappedData() {
+      return wrappedData;
+    }
+  }
+
+  private static class DataHolderDeserializer implements JsonDeserializer<DataHolder> {
+    @Override
+    public DataHolder deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
+        throws JsonParseException {
+      JsonObject jsonObj = json.getAsJsonObject();
+      String dataString = jsonObj.get("data").getAsString();
+      return new DataHolder(dataString + SUFFIX);
+    }
+  }
+
+  public void testJsonTypeFieldBasedDeserialization() {
+    String json = "{field1:'abc',field2:'def',__type__:'SUB_TYPE1'}";
+    Gson gson = new GsonBuilder().registerTypeAdapter(MyBase.class, new JsonDeserializer<MyBase>() {
+      @Override public MyBase deserialize(JsonElement json, Type pojoType,
+          JsonDeserializationContext context) throws JsonParseException {
+        String type = json.getAsJsonObject().get(MyBase.TYPE_ACCESS).getAsString();
+        return context.deserialize(json, SubTypes.valueOf(type).getSubclass());
+      }
+    }).create();
+    SubType1 target = (SubType1) gson.fromJson(json, MyBase.class);
+    assertEquals("abc", target.field1);
+  }
+
+  private static class MyBase {
+    static final String TYPE_ACCESS = "__type__";
+  }
+
+  private enum SubTypes {
+    SUB_TYPE1(SubType1.class),
+    SUB_TYPE2(SubType2.class);
+    private final Type subClass;
+    private SubTypes(Type subClass) {
+      this.subClass = subClass;
+    }
+    public Type getSubclass() {
+      return subClass;
+    }
+  }
+
+  private static class SubType1 extends MyBase {
+    String field1;
+  }
+
+  private static class SubType2 extends MyBase {
+    @SuppressWarnings("unused")
+    String field2;
+  }
+
+  public void testCustomDeserializerReturnsNullForTopLevelObject() {
+    Gson gson = new GsonBuilder()
+      .registerTypeAdapter(Base.class, new JsonDeserializer<Base>() {
+        @Override
+        public Base deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
+            throws JsonParseException {
+          return null;
+        }
+      }).create();
+    String json = "{baseName:'Base',subName:'SubRevised'}";
+    Base target = gson.fromJson(json, Base.class);
+    assertNull(target);
+  }
+
+  public void testCustomDeserializerReturnsNull() {
+    Gson gson = new GsonBuilder()
+      .registerTypeAdapter(Base.class, new JsonDeserializer<Base>() {
+        @Override
+        public Base deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
+            throws JsonParseException {
+          return null;
+        }
+      }).create();
+    String json = "{base:{baseName:'Base',subName:'SubRevised'}}";
+    ClassWithBaseField target = gson.fromJson(json, ClassWithBaseField.class);
+    assertNull(target.base);
+  }
+
+  public void testCustomDeserializerReturnsNullForArrayElements() {
+    Gson gson = new GsonBuilder()
+      .registerTypeAdapter(Base.class, new JsonDeserializer<Base>() {
+        @Override
+        public Base deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
+            throws JsonParseException {
+          return null;
+        }
+      }).create();
+    String json = "[{baseName:'Base'},{baseName:'Base'}]";
+    Base[] target = gson.fromJson(json, Base[].class);
+    assertNull(target[0]);
+    assertNull(target[1]);
+  }
+
+  public void testCustomDeserializerReturnsNullForArrayElementsForArrayField() {
+    Gson gson = new GsonBuilder()
+      .registerTypeAdapter(Base.class, new JsonDeserializer<Base>() {
+        @Override
+        public Base deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
+            throws JsonParseException {
+          return null;
+        }
+      }).create();
+    String json = "{bases:[{baseName:'Base'},{baseName:'Base'}]}";
+    ClassWithBaseArray target = gson.fromJson(json, ClassWithBaseArray.class);
+    assertNull(target.bases[0]);
+    assertNull(target.bases[1]);
+  }
+
+  private static final class ClassWithBaseArray {
+    Base[] bases;
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/CustomSerializerTest.java b/gson/src/test/java/com/google/gson/functional/CustomSerializerTest.java
new file mode 100644
index 0000000..e04cb67
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/CustomSerializerTest.java
@@ -0,0 +1,102 @@
+/*
+ * Copyright (C) 2009 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.functional;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonSerializationContext;
+import com.google.gson.JsonSerializer;
+import com.google.gson.common.TestTypes.Base;
+import com.google.gson.common.TestTypes.BaseSerializer;
+import com.google.gson.common.TestTypes.ClassWithBaseArrayField;
+import com.google.gson.common.TestTypes.ClassWithBaseField;
+import com.google.gson.common.TestTypes.Sub;
+import com.google.gson.common.TestTypes.SubSerializer;
+
+import junit.framework.TestCase;
+
+import java.lang.reflect.Type;
+
+/**
+ * Functional Test exercising custom serialization only.  When test applies to both
+ * serialization and deserialization then add it to CustomTypeAdapterTest.
+ *
+ * @author Inderjeet Singh
+ */
+public class CustomSerializerTest extends TestCase {
+
+   public void testBaseClassSerializerInvokedForBaseClassFields() {
+     Gson gson = new GsonBuilder()
+         .registerTypeAdapter(Base.class, new BaseSerializer())
+         .registerTypeAdapter(Sub.class, new SubSerializer())
+         .create();
+     ClassWithBaseField target = new ClassWithBaseField(new Base());
+     JsonObject json = (JsonObject) gson.toJsonTree(target);
+     JsonObject base = json.get("base").getAsJsonObject();
+     assertEquals(BaseSerializer.NAME, base.get(Base.SERIALIZER_KEY).getAsString());
+   }
+
+   public void testSubClassSerializerInvokedForBaseClassFieldsHoldingSubClassInstances() {
+     Gson gson = new GsonBuilder()
+         .registerTypeAdapter(Base.class, new BaseSerializer())
+         .registerTypeAdapter(Sub.class, new SubSerializer())
+         .create();
+     ClassWithBaseField target = new ClassWithBaseField(new Sub());
+     JsonObject json = (JsonObject) gson.toJsonTree(target);
+     JsonObject base = json.get("base").getAsJsonObject();
+     assertEquals(SubSerializer.NAME, base.get(Base.SERIALIZER_KEY).getAsString());
+   }
+
+   public void testSubClassSerializerInvokedForBaseClassFieldsHoldingArrayOfSubClassInstances() {
+     Gson gson = new GsonBuilder()
+         .registerTypeAdapter(Base.class, new BaseSerializer())
+         .registerTypeAdapter(Sub.class, new SubSerializer())
+         .create();
+     ClassWithBaseArrayField target = new ClassWithBaseArrayField(new Base[] {new Sub(), new Sub()});
+     JsonObject json = (JsonObject) gson.toJsonTree(target);
+     JsonArray array = json.get("base").getAsJsonArray();
+     for (JsonElement element : array) {
+       JsonElement serializerKey = element.getAsJsonObject().get(Base.SERIALIZER_KEY);
+      assertEquals(SubSerializer.NAME, serializerKey.getAsString());
+     }
+   }
+
+   public void testBaseClassSerializerInvokedForBaseClassFieldsHoldingSubClassInstances() {
+     Gson gson = new GsonBuilder()
+         .registerTypeAdapter(Base.class, new BaseSerializer())
+         .create();
+     ClassWithBaseField target = new ClassWithBaseField(new Sub());
+     JsonObject json = (JsonObject) gson.toJsonTree(target);
+     JsonObject base = json.get("base").getAsJsonObject();
+     assertEquals(BaseSerializer.NAME, base.get(Base.SERIALIZER_KEY).getAsString());
+   }
+
+   public void testSerializerReturnsNull() {
+     Gson gson = new GsonBuilder()
+       .registerTypeAdapter(Base.class, new JsonSerializer<Base>() {
+         @Override public JsonElement serialize(Base src, Type typeOfSrc, JsonSerializationContext context) {
+           return null;
+         }
+       })
+       .create();
+       JsonElement json = gson.toJsonTree(new Base());
+       assertTrue(json.isJsonNull());
+   }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/CustomTypeAdaptersTest.java b/gson/src/test/java/com/google/gson/functional/CustomTypeAdaptersTest.java
new file mode 100644
index 0000000..b14ed52
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/CustomTypeAdaptersTest.java
@@ -0,0 +1,465 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.functional;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.InstanceCreator;
+import com.google.gson.JsonDeserializationContext;
+import com.google.gson.JsonDeserializer;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParseException;
+import com.google.gson.JsonPrimitive;
+import com.google.gson.JsonSerializationContext;
+import com.google.gson.JsonSerializer;
+import com.google.gson.common.TestTypes.BagOfPrimitives;
+import com.google.gson.common.TestTypes.ClassWithCustomTypeConverter;
+import com.google.gson.reflect.TypeToken;
+
+import java.util.Date;
+import junit.framework.TestCase;
+
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Functional tests for the support of custom serializer and deserializers.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public class CustomTypeAdaptersTest extends TestCase {
+  private GsonBuilder builder;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    builder = new GsonBuilder();
+  }
+
+  public void testCustomSerializers() {
+    Gson gson = builder.registerTypeAdapter(
+        ClassWithCustomTypeConverter.class, new JsonSerializer<ClassWithCustomTypeConverter>() {
+          @Override public JsonElement serialize(ClassWithCustomTypeConverter src, Type typeOfSrc,
+              JsonSerializationContext context) {
+        JsonObject json = new JsonObject();
+        json.addProperty("bag", 5);
+        json.addProperty("value", 25);
+        return json;
+      }
+    }).create();
+    ClassWithCustomTypeConverter target = new ClassWithCustomTypeConverter();
+    assertEquals("{\"bag\":5,\"value\":25}", gson.toJson(target));
+  }
+
+  public void testCustomDeserializers() {
+    Gson gson = new GsonBuilder().registerTypeAdapter(
+        ClassWithCustomTypeConverter.class, new JsonDeserializer<ClassWithCustomTypeConverter>() {
+          @Override public ClassWithCustomTypeConverter deserialize(JsonElement json, Type typeOfT,
+              JsonDeserializationContext context) {
+        JsonObject jsonObject = json.getAsJsonObject();
+        int value = jsonObject.get("bag").getAsInt();
+        return new ClassWithCustomTypeConverter(new BagOfPrimitives(value,
+            value, false, ""), value);
+      }
+    }).create();
+    String json = "{\"bag\":5,\"value\":25}";
+    ClassWithCustomTypeConverter target = gson.fromJson(json, ClassWithCustomTypeConverter.class);
+    assertEquals(5, target.getBag().getIntValue());
+  }
+
+  public void disable_testCustomSerializersOfSelf() {
+    Gson gson = createGsonObjectWithFooTypeAdapter();
+    Gson basicGson = new Gson();
+    Foo newFooObject = new Foo(1, 2L);
+    String jsonFromCustomSerializer = gson.toJson(newFooObject);
+    String jsonFromGson = basicGson.toJson(newFooObject);
+
+    assertEquals(jsonFromGson, jsonFromCustomSerializer);
+  }
+
+  public void disable_testCustomDeserializersOfSelf() {
+    Gson gson = createGsonObjectWithFooTypeAdapter();
+    Gson basicGson = new Gson();
+    Foo expectedFoo = new Foo(1, 2L);
+    String json = basicGson.toJson(expectedFoo);
+    Foo newFooObject = gson.fromJson(json, Foo.class);
+
+    assertEquals(expectedFoo.key, newFooObject.key);
+    assertEquals(expectedFoo.value, newFooObject.value);
+  }
+
+  public void testCustomNestedSerializers() {
+    Gson gson = new GsonBuilder().registerTypeAdapter(
+        BagOfPrimitives.class, new JsonSerializer<BagOfPrimitives>() {
+          @Override public JsonElement serialize(BagOfPrimitives src, Type typeOfSrc,
+          JsonSerializationContext context) {
+        return new JsonPrimitive(6);
+      }
+    }).create();
+    ClassWithCustomTypeConverter target = new ClassWithCustomTypeConverter();
+    assertEquals("{\"bag\":6,\"value\":10}", gson.toJson(target));
+  }
+
+  public void testCustomNestedDeserializers() {
+    Gson gson = new GsonBuilder().registerTypeAdapter(
+        BagOfPrimitives.class, new JsonDeserializer<BagOfPrimitives>() {
+          @Override public BagOfPrimitives deserialize(JsonElement json, Type typeOfT,
+          JsonDeserializationContext context) throws JsonParseException {
+        int value = json.getAsInt();
+        return new BagOfPrimitives(value, value, false, "");
+      }
+    }).create();
+    String json = "{\"bag\":7,\"value\":25}";
+    ClassWithCustomTypeConverter target = gson.fromJson(json, ClassWithCustomTypeConverter.class);
+    assertEquals(7, target.getBag().getIntValue());
+  }
+
+  public void testCustomTypeAdapterDoesNotAppliesToSubClasses() {
+    Gson gson = new GsonBuilder().registerTypeAdapter(Base.class, new JsonSerializer<Base> () {
+      @Override
+      public JsonElement serialize(Base src, Type typeOfSrc, JsonSerializationContext context) {
+        JsonObject json = new JsonObject();
+        json.addProperty("value", src.baseValue);
+        return json;
+      }
+    }).create();
+    Base b = new Base();
+    String json = gson.toJson(b);
+    assertTrue(json.contains("value"));
+    b = new Derived();
+    json = gson.toJson(b);
+    assertTrue(json.contains("derivedValue"));
+  }
+
+  public void testCustomTypeAdapterAppliesToSubClassesSerializedAsBaseClass() {
+    Gson gson = new GsonBuilder().registerTypeAdapter(Base.class, new JsonSerializer<Base> () {
+      @Override
+      public JsonElement serialize(Base src, Type typeOfSrc, JsonSerializationContext context) {
+        JsonObject json = new JsonObject();
+        json.addProperty("value", src.baseValue);
+        return json;
+      }
+    }).create();
+    Base b = new Base();
+    String json = gson.toJson(b);
+    assertTrue(json.contains("value"));
+    b = new Derived();
+    json = gson.toJson(b, Base.class);
+    assertTrue(json.contains("value"));
+    assertFalse(json.contains("derivedValue"));
+  }
+
+  private static class Base {
+    int baseValue = 2;
+  }
+
+  private static class Derived extends Base {
+    @SuppressWarnings("unused")
+    int derivedValue = 3;
+  }
+
+
+  private Gson createGsonObjectWithFooTypeAdapter() {
+    return new GsonBuilder().registerTypeAdapter(Foo.class, new FooTypeAdapter()).create();
+  }
+
+  public static class Foo {
+    private final int key;
+    private final long value;
+
+    public Foo() {
+      this(0, 0L);
+    }
+
+    public Foo(int key, long value) {
+      this.key = key;
+      this.value = value;
+    }
+  }
+
+  public static final class FooTypeAdapter implements JsonSerializer<Foo>, JsonDeserializer<Foo> {
+    @Override
+    public Foo deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
+        throws JsonParseException {
+      return context.deserialize(json, typeOfT);
+    }
+
+    @Override
+    public JsonElement serialize(Foo src, Type typeOfSrc, JsonSerializationContext context) {
+      return context.serialize(src, typeOfSrc);
+    }
+  }
+
+  public void testCustomSerializerInvokedForPrimitives() {
+    Gson gson = new GsonBuilder()
+        .registerTypeAdapter(boolean.class, new JsonSerializer<Boolean>() {
+          @Override public JsonElement serialize(Boolean s, Type t, JsonSerializationContext c) {
+            return new JsonPrimitive(s ? 1 : 0);
+          }
+        })
+        .create();
+    assertEquals("1", gson.toJson(true, boolean.class));
+    assertEquals("true", gson.toJson(true, Boolean.class));
+  }
+
+  @SuppressWarnings("rawtypes")
+  public void testCustomDeserializerInvokedForPrimitives() {
+    Gson gson = new GsonBuilder()
+        .registerTypeAdapter(boolean.class, new JsonDeserializer() {
+          @Override
+          public Object deserialize(JsonElement json, Type t, JsonDeserializationContext context) {
+            return json.getAsInt() != 0;
+          }
+        })
+        .create();
+    assertEquals(Boolean.TRUE, gson.fromJson("1", boolean.class));
+    assertEquals(Boolean.TRUE, gson.fromJson("true", Boolean.class));
+  }
+
+  public void testCustomByteArraySerializer() {
+    Gson gson = new GsonBuilder().registerTypeAdapter(byte[].class, new JsonSerializer<byte[]>() {
+      @Override
+      public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) {
+        StringBuilder sb = new StringBuilder(src.length);
+        for (byte b : src) {
+          sb.append(b);
+        }
+        return new JsonPrimitive(sb.toString());
+      }
+    }).create();
+    byte[] data = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
+    String json = gson.toJson(data);
+    assertEquals("\"0123456789\"", json);
+  }
+
+  public void testCustomByteArrayDeserializerAndInstanceCreator() {
+    GsonBuilder gsonBuilder = new GsonBuilder().registerTypeAdapter(byte[].class,
+        new JsonDeserializer<byte[]>() {
+          @Override public byte[] deserialize(JsonElement json,
+              Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
+        String str = json.getAsString();
+        byte[] data = new byte[str.length()];
+        for (int i = 0; i < data.length; ++i) {
+          data[i] = Byte.parseByte(""+str.charAt(i));
+        }
+        return data;
+      }
+    });
+    Gson gson = gsonBuilder.create();
+    String json = "'0123456789'";
+    byte[] actual = gson.fromJson(json, byte[].class);
+    byte[] expected = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
+    for (int i = 0; i < actual.length; ++i) {
+      assertEquals(expected[i], actual[i]);
+    }
+  }
+
+  private static final class StringHolder {
+    String part1;
+    String part2;
+
+    public StringHolder(String string) {
+      String[] parts = string.split(":");
+      part1 = parts[0];
+      part2 = parts[1];
+    }
+    public StringHolder(String part1, String part2) {
+      this.part1 = part1;
+      this.part2 = part2;
+    }
+  }
+
+  private static class StringHolderTypeAdapter implements JsonSerializer<StringHolder>,
+      JsonDeserializer<StringHolder>, InstanceCreator<StringHolder> {
+
+    @Override public StringHolder createInstance(Type type) {
+      //Fill up with objects that will be thrown away
+      return new StringHolder("unknown:thing");
+    }
+
+    @Override public StringHolder deserialize(JsonElement src, Type type,
+        JsonDeserializationContext context) {
+      return new StringHolder(src.getAsString());
+    }
+
+    @Override public JsonElement serialize(StringHolder src, Type typeOfSrc,
+        JsonSerializationContext context) {
+      String contents = src.part1 + ':' + src.part2;
+      return new JsonPrimitive(contents);
+    }
+  }
+
+  // Test created from Issue 70
+  public void testCustomAdapterInvokedForCollectionElementSerializationWithType() {
+    Gson gson = new GsonBuilder()
+      .registerTypeAdapter(StringHolder.class, new StringHolderTypeAdapter())
+      .create();
+    Type setType = new TypeToken<Set<StringHolder>>() {}.getType();
+    StringHolder holder = new StringHolder("Jacob", "Tomaw");
+    Set<StringHolder> setOfHolders = new HashSet<>();
+    setOfHolders.add(holder);
+    String json = gson.toJson(setOfHolders, setType);
+    assertTrue(json.contains("Jacob:Tomaw"));
+  }
+
+  // Test created from Issue 70
+  public void testCustomAdapterInvokedForCollectionElementSerialization() {
+    Gson gson = new GsonBuilder()
+      .registerTypeAdapter(StringHolder.class, new StringHolderTypeAdapter())
+      .create();
+    StringHolder holder = new StringHolder("Jacob", "Tomaw");
+    Set<StringHolder> setOfHolders = new HashSet<>();
+    setOfHolders.add(holder);
+    String json = gson.toJson(setOfHolders);
+    assertTrue(json.contains("Jacob:Tomaw"));
+  }
+
+  // Test created from Issue 70
+  public void testCustomAdapterInvokedForCollectionElementDeserialization() {
+    Gson gson = new GsonBuilder()
+      .registerTypeAdapter(StringHolder.class, new StringHolderTypeAdapter())
+      .create();
+    Type setType = new TypeToken<Set<StringHolder>>() {}.getType();
+    Set<StringHolder> setOfHolders = gson.fromJson("['Jacob:Tomaw']", setType);
+    assertEquals(1, setOfHolders.size());
+    StringHolder foo = setOfHolders.iterator().next();
+    assertEquals("Jacob", foo.part1);
+    assertEquals("Tomaw", foo.part2);
+  }
+
+  // Test created from Issue 70
+  public void testCustomAdapterInvokedForMapElementSerializationWithType() {
+    Gson gson = new GsonBuilder()
+      .registerTypeAdapter(StringHolder.class, new StringHolderTypeAdapter())
+      .create();
+    Type mapType = new TypeToken<Map<String,StringHolder>>() {}.getType();
+    StringHolder holder = new StringHolder("Jacob", "Tomaw");
+    Map<String, StringHolder> mapOfHolders = new HashMap<>();
+    mapOfHolders.put("foo", holder);
+    String json = gson.toJson(mapOfHolders, mapType);
+    assertTrue(json.contains("\"foo\":\"Jacob:Tomaw\""));
+  }
+
+  // Test created from Issue 70
+  public void testCustomAdapterInvokedForMapElementSerialization() {
+    Gson gson = new GsonBuilder()
+      .registerTypeAdapter(StringHolder.class, new StringHolderTypeAdapter())
+      .create();
+    StringHolder holder = new StringHolder("Jacob", "Tomaw");
+    Map<String, StringHolder> mapOfHolders = new HashMap<>();
+    mapOfHolders.put("foo", holder);
+    String json = gson.toJson(mapOfHolders);
+    assertTrue(json.contains("\"foo\":\"Jacob:Tomaw\""));
+  }
+
+  // Test created from Issue 70
+  public void testCustomAdapterInvokedForMapElementDeserialization() {
+    Gson gson = new GsonBuilder()
+      .registerTypeAdapter(StringHolder.class, new StringHolderTypeAdapter())
+      .create();
+    Type mapType = new TypeToken<Map<String, StringHolder>>() {}.getType();
+    Map<String, StringHolder> mapOfFoo = gson.fromJson("{'foo':'Jacob:Tomaw'}", mapType);
+    assertEquals(1, mapOfFoo.size());
+    StringHolder foo = mapOfFoo.get("foo");
+    assertEquals("Jacob", foo.part1);
+    assertEquals("Tomaw", foo.part2);
+  }
+
+  public void testEnsureCustomSerializerNotInvokedForNullValues() {
+    Gson gson = new GsonBuilder()
+        .registerTypeAdapter(DataHolder.class, new DataHolderSerializer())
+        .create();
+    DataHolderWrapper target = new DataHolderWrapper(new DataHolder("abc"));
+    String json = gson.toJson(target);
+    assertEquals("{\"wrappedData\":{\"myData\":\"abc\"}}", json);
+  }
+
+  public void testEnsureCustomDeserializerNotInvokedForNullValues() {
+    Gson gson = new GsonBuilder()
+        .registerTypeAdapter(DataHolder.class, new DataHolderDeserializer())
+        .create();
+    String json = "{wrappedData:null}";
+    DataHolderWrapper actual = gson.fromJson(json, DataHolderWrapper.class);
+    assertNull(actual.wrappedData);
+  }
+
+  // Test created from Issue 352
+  public void testRegisterHierarchyAdapterForDate() {
+    Gson gson = new GsonBuilder()
+        .registerTypeHierarchyAdapter(Date.class, new DateTypeAdapter())
+        .create();
+    assertEquals("0", gson.toJson(new Date(0)));
+    assertEquals("0", gson.toJson(new java.sql.Date(0)));
+    assertEquals(new Date(0), gson.fromJson("0", Date.class));
+    assertEquals(new java.sql.Date(0), gson.fromJson("0", java.sql.Date.class));
+  }
+
+  private static class DataHolder {
+    final String data;
+
+    public DataHolder(String data) {
+      this.data = data;
+    }
+  }
+
+  private static class DataHolderWrapper {
+    final DataHolder wrappedData;
+
+    public DataHolderWrapper(DataHolder data) {
+      this.wrappedData = data;
+    }
+  }
+
+  private static class DataHolderSerializer implements JsonSerializer<DataHolder> {
+    @Override
+    public JsonElement serialize(DataHolder src, Type typeOfSrc, JsonSerializationContext context) {
+      JsonObject obj = new JsonObject();
+      obj.addProperty("myData", src.data);
+      return obj;
+    }
+  }
+
+  private static class DataHolderDeserializer implements JsonDeserializer<DataHolder> {
+    @Override
+    public DataHolder deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
+        throws JsonParseException {
+      JsonObject jsonObj = json.getAsJsonObject();
+      JsonElement jsonElement = jsonObj.get("data");
+      if (jsonElement == null || jsonElement.isJsonNull()) {
+        return new DataHolder(null);
+      }
+      return new DataHolder(jsonElement.getAsString());
+    }
+  }
+
+  private static class DateTypeAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
+    @Override
+    public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
+      return typeOfT == Date.class
+          ? new Date(json.getAsLong())
+          : new java.sql.Date(json.getAsLong());
+    }
+    @Override
+    public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
+      return new JsonPrimitive(src.getTime());
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/DefaultTypeAdaptersTest.java b/gson/src/test/java/com/google/gson/functional/DefaultTypeAdaptersTest.java
new file mode 100644
index 0000000..91a4639
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/DefaultTypeAdaptersTest.java
@@ -0,0 +1,690 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.functional;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonDeserializationContext;
+import com.google.gson.JsonDeserializer;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonNull;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParseException;
+import com.google.gson.JsonPrimitive;
+import com.google.gson.JsonSyntaxException;
+import com.google.gson.TypeAdapter;
+import com.google.gson.internal.JavaVersion;
+import com.google.gson.reflect.TypeToken;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Type;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.net.InetAddress;
+import java.net.URI;
+import java.net.URL;
+import java.text.DateFormat;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.BitSet;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Properties;
+import java.util.Set;
+import java.util.TimeZone;
+import java.util.TreeSet;
+import java.util.UUID;
+
+import junit.framework.TestCase;
+
+/**
+ * Functional test for Json serialization and deserialization for common classes for which default
+ * support is provided in Gson. The tests for Map types are available in {@link MapTest}.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public class DefaultTypeAdaptersTest extends TestCase {
+  private Gson gson;
+  private TimeZone oldTimeZone;
+  private Locale oldLocale;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    this.oldTimeZone = TimeZone.getDefault();
+    TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles"));
+    this.oldLocale = Locale.getDefault();
+    Locale.setDefault(Locale.US);
+    gson = new Gson();
+  }
+
+  @Override
+  protected void tearDown() throws Exception {
+    TimeZone.setDefault(oldTimeZone);
+    Locale.setDefault(oldLocale);
+    super.tearDown();
+  }
+
+  public void testClassSerialization() {
+    try {
+      gson.toJson(String.class);
+      fail();
+    } catch (UnsupportedOperationException expected) {
+    }
+    // Override with a custom type adapter for class.
+    gson = new GsonBuilder().registerTypeAdapter(Class.class, new MyClassTypeAdapter()).create();
+    assertEquals("\"java.lang.String\"", gson.toJson(String.class));
+  }
+
+  public void testClassDeserialization() {
+    try {
+      gson.fromJson("String.class", String.class.getClass());
+      fail();
+    } catch (UnsupportedOperationException expected) {
+    }
+    // Override with a custom type adapter for class.
+    gson = new GsonBuilder().registerTypeAdapter(Class.class, new MyClassTypeAdapter()).create();
+    assertEquals(String.class, gson.fromJson("java.lang.String", Class.class));
+  }
+
+  public void testUrlSerialization() throws Exception {
+    String urlValue = "http://google.com/";
+    URL url = new URL(urlValue);
+    assertEquals("\"http://google.com/\"", gson.toJson(url));
+  }
+
+  public void testUrlDeserialization() {
+    String urlValue = "http://google.com/";
+    String json = "'http:\\/\\/google.com\\/'";
+    URL target = gson.fromJson(json, URL.class);
+    assertEquals(urlValue, target.toExternalForm());
+
+    gson.fromJson('"' + urlValue + '"', URL.class);
+    assertEquals(urlValue, target.toExternalForm());
+  }
+
+  public void testUrlNullSerialization() throws Exception {
+    ClassWithUrlField target = new ClassWithUrlField();
+    assertEquals("{}", gson.toJson(target));
+  }
+
+  public void testUrlNullDeserialization() {
+    String json = "{}";
+    ClassWithUrlField target = gson.fromJson(json, ClassWithUrlField.class);
+    assertNull(target.url);
+  }
+
+  private static class ClassWithUrlField {
+    URL url;
+  }
+
+  public void testUriSerialization() throws Exception {
+    String uriValue = "http://google.com/";
+    URI uri = new URI(uriValue);
+    assertEquals("\"http://google.com/\"", gson.toJson(uri));
+  }
+
+  public void testUriDeserialization() {
+    String uriValue = "http://google.com/";
+    String json = '"' + uriValue + '"';
+    URI target = gson.fromJson(json, URI.class);
+    assertEquals(uriValue, target.toASCIIString());
+  }
+
+  public void testNullSerialization() throws Exception {
+    testNullSerializationAndDeserialization(Boolean.class);
+    testNullSerializationAndDeserialization(Byte.class);
+    testNullSerializationAndDeserialization(Short.class);
+    testNullSerializationAndDeserialization(Integer.class);
+    testNullSerializationAndDeserialization(Long.class);
+    testNullSerializationAndDeserialization(Double.class);
+    testNullSerializationAndDeserialization(Float.class);
+    testNullSerializationAndDeserialization(Number.class);
+    testNullSerializationAndDeserialization(Character.class);
+    testNullSerializationAndDeserialization(String.class);
+    testNullSerializationAndDeserialization(StringBuilder.class);
+    testNullSerializationAndDeserialization(StringBuffer.class);
+    testNullSerializationAndDeserialization(BigDecimal.class);
+    testNullSerializationAndDeserialization(BigInteger.class);
+    testNullSerializationAndDeserialization(TreeSet.class);
+    testNullSerializationAndDeserialization(ArrayList.class);
+    testNullSerializationAndDeserialization(HashSet.class);
+    testNullSerializationAndDeserialization(Properties.class);
+    testNullSerializationAndDeserialization(URL.class);
+    testNullSerializationAndDeserialization(URI.class);
+    testNullSerializationAndDeserialization(UUID.class);
+    testNullSerializationAndDeserialization(Locale.class);
+    testNullSerializationAndDeserialization(InetAddress.class);
+    testNullSerializationAndDeserialization(BitSet.class);
+    testNullSerializationAndDeserialization(Date.class);
+    testNullSerializationAndDeserialization(GregorianCalendar.class);
+    testNullSerializationAndDeserialization(Calendar.class);
+    testNullSerializationAndDeserialization(Class.class);
+  }
+
+  private void testNullSerializationAndDeserialization(Class<?> c) {
+    testNullSerializationAndDeserialization(gson, c);
+  }
+
+  public static void testNullSerializationAndDeserialization(Gson gson, Class<?> c) {
+    assertEquals("null", gson.toJson(null, c));
+    assertEquals(null, gson.fromJson("null", c));
+  }
+
+  public void testUuidSerialization() throws Exception {
+    String uuidValue = "c237bec1-19ef-4858-a98e-521cf0aad4c0";
+    UUID uuid = UUID.fromString(uuidValue);
+    assertEquals('"' + uuidValue + '"', gson.toJson(uuid));
+  }
+
+  public void testUuidDeserialization() {
+    String uuidValue = "c237bec1-19ef-4858-a98e-521cf0aad4c0";
+    String json = '"' + uuidValue + '"';
+    UUID target = gson.fromJson(json, UUID.class);
+    assertEquals(uuidValue, target.toString());
+  }
+
+  public void testLocaleSerializationWithLanguage() {
+    Locale target = new Locale("en");
+    assertEquals("\"en\"", gson.toJson(target));
+  }
+
+  public void testLocaleDeserializationWithLanguage() {
+    String json = "\"en\"";
+    Locale locale = gson.fromJson(json, Locale.class);
+    assertEquals("en", locale.getLanguage());
+  }
+
+  public void testLocaleSerializationWithLanguageCountry() {
+    Locale target = Locale.CANADA_FRENCH;
+    assertEquals("\"fr_CA\"", gson.toJson(target));
+  }
+
+  public void testLocaleDeserializationWithLanguageCountry() {
+    String json = "\"fr_CA\"";
+    Locale locale = gson.fromJson(json, Locale.class);
+    assertEquals(Locale.CANADA_FRENCH, locale);
+  }
+
+  public void testLocaleSerializationWithLanguageCountryVariant() {
+    Locale target = new Locale("de", "DE", "EURO");
+    String json = gson.toJson(target);
+    assertEquals("\"de_DE_EURO\"", json);
+  }
+
+  public void testLocaleDeserializationWithLanguageCountryVariant() {
+    String json = "\"de_DE_EURO\"";
+    Locale locale = gson.fromJson(json, Locale.class);
+    assertEquals("de", locale.getLanguage());
+    assertEquals("DE", locale.getCountry());
+    assertEquals("EURO", locale.getVariant());
+  }
+
+  public void testBigDecimalFieldSerialization() {
+    ClassWithBigDecimal target = new ClassWithBigDecimal("-122.01e-21");
+    String json = gson.toJson(target);
+    String actual = json.substring(json.indexOf(':') + 1, json.indexOf('}'));
+    assertEquals(target.value, new BigDecimal(actual));
+  }
+
+  public void testBigDecimalFieldDeserialization() {
+    ClassWithBigDecimal expected = new ClassWithBigDecimal("-122.01e-21");
+    String json = expected.getExpectedJson();
+    ClassWithBigDecimal actual = gson.fromJson(json, ClassWithBigDecimal.class);
+    assertEquals(expected.value, actual.value);
+  }
+
+  public void testBadValueForBigDecimalDeserialization() {
+    try {
+      gson.fromJson("{\"value\"=1.5e-1.0031}", ClassWithBigDecimal.class);
+      fail("Exponent of a BigDecimal must be an integer value.");
+    } catch (JsonParseException expected) { }
+  }
+
+  public void testBigIntegerFieldSerialization() {
+    ClassWithBigInteger target = new ClassWithBigInteger("23232323215323234234324324324324324324");
+    String json = gson.toJson(target);
+    assertEquals(target.getExpectedJson(), json);
+  }
+
+  public void testBigIntegerFieldDeserialization() {
+    ClassWithBigInteger expected = new ClassWithBigInteger("879697697697697697697697697697697697");
+    String json = expected.getExpectedJson();
+    ClassWithBigInteger actual = gson.fromJson(json, ClassWithBigInteger.class);
+    assertEquals(expected.value, actual.value);
+  }
+
+  public void testOverrideBigIntegerTypeAdapter() throws Exception {
+    gson = new GsonBuilder()
+        .registerTypeAdapter(BigInteger.class, new NumberAsStringAdapter(BigInteger.class))
+        .create();
+    assertEquals("\"123\"", gson.toJson(new BigInteger("123"), BigInteger.class));
+    assertEquals(new BigInteger("123"), gson.fromJson("\"123\"", BigInteger.class));
+  }
+
+  public void testOverrideBigDecimalTypeAdapter() throws Exception {
+    gson = new GsonBuilder()
+        .registerTypeAdapter(BigDecimal.class, new NumberAsStringAdapter(BigDecimal.class))
+        .create();
+    assertEquals("\"1.1\"", gson.toJson(new BigDecimal("1.1"), BigDecimal.class));
+    assertEquals(new BigDecimal("1.1"), gson.fromJson("\"1.1\"", BigDecimal.class));
+  }
+
+  public void testSetSerialization() throws Exception {
+    Gson gson = new Gson();
+    HashSet<String> s = new HashSet<>();
+    s.add("blah");
+    String json = gson.toJson(s);
+    assertEquals("[\"blah\"]", json);
+
+    json = gson.toJson(s, Set.class);
+    assertEquals("[\"blah\"]", json);
+  }
+
+  public void testBitSetSerialization() throws Exception {
+    Gson gson = new Gson();
+    BitSet bits = new BitSet();
+    bits.set(1);
+    bits.set(3, 6);
+    bits.set(9);
+    String json = gson.toJson(bits);
+    assertEquals("[0,1,0,1,1,1,0,0,0,1]", json);
+  }
+
+  public void testBitSetDeserialization() throws Exception {
+    BitSet expected = new BitSet();
+    expected.set(0);
+    expected.set(2, 6);
+    expected.set(8);
+
+    Gson gson = new Gson();
+    String json = gson.toJson(expected);
+    assertEquals(expected, gson.fromJson(json, BitSet.class));
+
+    json = "[1,0,1,1,1,1,0,0,1,0,0,0]";
+    assertEquals(expected, gson.fromJson(json, BitSet.class));
+
+    json = "[\"1\",\"0\",\"1\",\"1\",\"1\",\"1\",\"0\",\"0\",\"1\"]";
+    assertEquals(expected, gson.fromJson(json, BitSet.class));
+
+    json = "[true,false,true,true,true,true,false,false,true,false,false]";
+    assertEquals(expected, gson.fromJson(json, BitSet.class));
+
+    try {
+      gson.fromJson("[1, []]", BitSet.class);
+      fail();
+    } catch (JsonSyntaxException e) {
+      assertEquals("Invalid bitset value type: BEGIN_ARRAY; at path $[1]", e.getMessage());
+    }
+
+    try {
+      gson.fromJson("[1, 2]", BitSet.class);
+      fail();
+    } catch (JsonSyntaxException e) {
+      assertEquals("Invalid bitset value 2, expected 0 or 1; at path $[1]", e.getMessage());
+    }
+  }
+
+  public void testDefaultDateSerialization() {
+    Date now = new Date(1315806903103L);
+    String json = gson.toJson(now);
+    if (JavaVersion.isJava9OrLater()) {
+      assertEquals("\"Sep 11, 2011, 10:55:03 PM\"", json);
+    } else {
+      assertEquals("\"Sep 11, 2011 10:55:03 PM\"", json);
+    }
+  }
+
+  public void testDefaultDateDeserialization() {
+    String json = "'Dec 13, 2009 07:18:02 AM'";
+    Date extracted = gson.fromJson(json, Date.class);
+    assertEqualsDate(extracted, 2009, 11, 13);
+    assertEqualsTime(extracted, 7, 18, 2);
+  }
+
+  // Date can not directly be compared with another instance since the deserialization loses the
+  // millisecond portion.
+  @SuppressWarnings("deprecation")
+  public static void assertEqualsDate(Date date, int year, int month, int day) {
+    assertEquals(year-1900, date.getYear());
+    assertEquals(month, date.getMonth());
+    assertEquals(day, date.getDate());
+  }
+
+  @SuppressWarnings("deprecation")
+  public static void assertEqualsTime(Date date, int hours, int minutes, int seconds) {
+    assertEquals(hours, date.getHours());
+    assertEquals(minutes, date.getMinutes());
+    assertEquals(seconds, date.getSeconds());
+  }
+
+  public void testDefaultDateSerializationUsingBuilder() throws Exception {
+    Gson gson = new GsonBuilder().create();
+    Date now = new Date(1315806903103L);
+    String json = gson.toJson(now);
+    if (JavaVersion.isJava9OrLater()) {
+      assertEquals("\"Sep 11, 2011, 10:55:03 PM\"", json);
+    } else {
+      assertEquals("\"Sep 11, 2011 10:55:03 PM\"", json);
+    }
+  }
+
+  public void testDefaultDateDeserializationUsingBuilder() throws Exception {
+    Gson gson = new GsonBuilder().create();
+    Date now = new Date(1315806903103L);
+    String json = gson.toJson(now);
+    Date extracted = gson.fromJson(json, Date.class);
+    assertEquals(now.toString(), extracted.toString());
+  }
+
+  public void testDefaultCalendarSerialization() throws Exception {
+    Gson gson = new GsonBuilder().create();
+    String json = gson.toJson(Calendar.getInstance());
+    assertTrue(json.contains("year"));
+    assertTrue(json.contains("month"));
+    assertTrue(json.contains("dayOfMonth"));
+    assertTrue(json.contains("hourOfDay"));
+    assertTrue(json.contains("minute"));
+    assertTrue(json.contains("second"));
+  }
+
+  public void testDefaultCalendarDeserialization() throws Exception {
+    Gson gson = new GsonBuilder().create();
+    String json = "{year:2009,month:2,dayOfMonth:11,hourOfDay:14,minute:29,second:23}";
+    Calendar cal = gson.fromJson(json, Calendar.class);
+    assertEquals(2009, cal.get(Calendar.YEAR));
+    assertEquals(2, cal.get(Calendar.MONTH));
+    assertEquals(11, cal.get(Calendar.DAY_OF_MONTH));
+    assertEquals(14, cal.get(Calendar.HOUR_OF_DAY));
+    assertEquals(29, cal.get(Calendar.MINUTE));
+    assertEquals(23, cal.get(Calendar.SECOND));
+  }
+
+  public void testDefaultGregorianCalendarSerialization() throws Exception {
+    Gson gson = new GsonBuilder().create();
+    GregorianCalendar cal = new GregorianCalendar();
+    String json = gson.toJson(cal);
+    assertTrue(json.contains("year"));
+    assertTrue(json.contains("month"));
+    assertTrue(json.contains("dayOfMonth"));
+    assertTrue(json.contains("hourOfDay"));
+    assertTrue(json.contains("minute"));
+    assertTrue(json.contains("second"));
+  }
+
+  public void testDefaultGregorianCalendarDeserialization() throws Exception {
+    Gson gson = new GsonBuilder().create();
+    String json = "{year:2009,month:2,dayOfMonth:11,hourOfDay:14,minute:29,second:23}";
+    GregorianCalendar cal = gson.fromJson(json, GregorianCalendar.class);
+    assertEquals(2009, cal.get(Calendar.YEAR));
+    assertEquals(2, cal.get(Calendar.MONTH));
+    assertEquals(11, cal.get(Calendar.DAY_OF_MONTH));
+    assertEquals(14, cal.get(Calendar.HOUR_OF_DAY));
+    assertEquals(29, cal.get(Calendar.MINUTE));
+    assertEquals(23, cal.get(Calendar.SECOND));
+  }
+
+  public void testDateSerializationWithPattern() throws Exception {
+    String pattern = "yyyy-MM-dd";
+    Gson gson = new GsonBuilder().setDateFormat(DateFormat.FULL).setDateFormat(pattern).create();
+    Date now = new Date(1315806903103L);
+    String json = gson.toJson(now);
+    assertEquals("\"2011-09-11\"", json);
+  }
+
+  @SuppressWarnings("deprecation")
+  public void testDateDeserializationWithPattern() throws Exception {
+    String pattern = "yyyy-MM-dd";
+    Gson gson = new GsonBuilder().setDateFormat(DateFormat.FULL).setDateFormat(pattern).create();
+    Date now = new Date(1315806903103L);
+    String json = gson.toJson(now);
+    Date extracted = gson.fromJson(json, Date.class);
+    assertEquals(now.getYear(), extracted.getYear());
+    assertEquals(now.getMonth(), extracted.getMonth());
+    assertEquals(now.getDay(), extracted.getDay());
+  }
+
+  public void testDateSerializationWithPatternNotOverridenByTypeAdapter() throws Exception {
+    String pattern = "yyyy-MM-dd";
+    Gson gson = new GsonBuilder()
+        .setDateFormat(pattern)
+        .registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
+          @Override public Date deserialize(JsonElement json, Type typeOfT,
+              JsonDeserializationContext context)
+              throws JsonParseException {
+            return new Date(1315806903103L);
+          }
+        })
+        .create();
+
+    Date now = new Date(1315806903103L);
+    String json = gson.toJson(now);
+    assertEquals("\"2011-09-11\"", json);
+  }
+
+  // http://code.google.com/p/google-gson/issues/detail?id=230
+  public void testDateSerializationInCollection() throws Exception {
+    Type listOfDates = new TypeToken<List<Date>>() {}.getType();
+    TimeZone defaultTimeZone = TimeZone.getDefault();
+    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
+    Locale defaultLocale = Locale.getDefault();
+    Locale.setDefault(Locale.US);
+    try {
+      Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
+      List<Date> dates = Arrays.asList(new Date(0));
+      String json = gson.toJson(dates, listOfDates);
+      assertEquals("[\"1970-01-01\"]", json);
+      assertEquals(0L, gson.<List<Date>>fromJson("[\"1970-01-01\"]", listOfDates).get(0).getTime());
+    } finally {
+      TimeZone.setDefault(defaultTimeZone);
+      Locale.setDefault(defaultLocale);
+    }
+  }
+
+  public void testJsonPrimitiveSerialization() {
+    assertEquals("5", gson.toJson(new JsonPrimitive(5), JsonElement.class));
+    assertEquals("true", gson.toJson(new JsonPrimitive(true), JsonElement.class));
+    assertEquals("\"foo\"", gson.toJson(new JsonPrimitive("foo"), JsonElement.class));
+    assertEquals("\"a\"", gson.toJson(new JsonPrimitive('a'), JsonElement.class));
+  }
+
+  public void testJsonPrimitiveDeserialization() {
+    assertEquals(new JsonPrimitive(5), gson.fromJson("5", JsonElement.class));
+    assertEquals(new JsonPrimitive(5), gson.fromJson("5", JsonPrimitive.class));
+    assertEquals(new JsonPrimitive(true), gson.fromJson("true", JsonElement.class));
+    assertEquals(new JsonPrimitive(true), gson.fromJson("true", JsonPrimitive.class));
+    assertEquals(new JsonPrimitive("foo"), gson.fromJson("\"foo\"", JsonElement.class));
+    assertEquals(new JsonPrimitive("foo"), gson.fromJson("\"foo\"", JsonPrimitive.class));
+    assertEquals(new JsonPrimitive('a'), gson.fromJson("\"a\"", JsonElement.class));
+    assertEquals(new JsonPrimitive('a'), gson.fromJson("\"a\"", JsonPrimitive.class));
+  }
+
+  public void testJsonNullSerialization() {
+    assertEquals("null", gson.toJson(JsonNull.INSTANCE, JsonElement.class));
+    assertEquals("null", gson.toJson(JsonNull.INSTANCE, JsonNull.class));
+  }
+
+  public void testNullJsonElementSerialization() {
+    assertEquals("null", gson.toJson(null, JsonElement.class));
+    assertEquals("null", gson.toJson(null, JsonNull.class));
+  }
+
+  public void testJsonArraySerialization() {
+    JsonArray array = new JsonArray();
+    array.add(new JsonPrimitive(1));
+    array.add(new JsonPrimitive(2));
+    array.add(new JsonPrimitive(3));
+    assertEquals("[1,2,3]", gson.toJson(array, JsonElement.class));
+  }
+
+  public void testJsonArrayDeserialization() {
+    JsonArray array = new JsonArray();
+    array.add(new JsonPrimitive(1));
+    array.add(new JsonPrimitive(2));
+    array.add(new JsonPrimitive(3));
+
+    String json = "[1,2,3]";
+    assertEquals(array, gson.fromJson(json, JsonElement.class));
+    assertEquals(array, gson.fromJson(json, JsonArray.class));
+  }
+
+  public void testJsonObjectSerialization() {
+    JsonObject object = new JsonObject();
+    object.add("foo", new JsonPrimitive(1));
+    object.add("bar", new JsonPrimitive(2));
+    assertEquals("{\"foo\":1,\"bar\":2}", gson.toJson(object, JsonElement.class));
+  }
+
+  public void testJsonObjectDeserialization() {
+    JsonObject object = new JsonObject();
+    object.add("foo", new JsonPrimitive(1));
+    object.add("bar", new JsonPrimitive(2));
+
+    String json = "{\"foo\":1,\"bar\":2}";
+    JsonElement actual = gson.fromJson(json, JsonElement.class);
+    assertEquals(object, actual);
+
+    JsonObject actualObj = gson.fromJson(json, JsonObject.class);
+    assertEquals(object, actualObj);
+  }
+
+  public void testJsonNullDeserialization() {
+    assertEquals(JsonNull.INSTANCE, gson.fromJson("null", JsonElement.class));
+    assertEquals(JsonNull.INSTANCE, gson.fromJson("null", JsonNull.class));
+  }
+
+  public void testJsonElementTypeMismatch() {
+    try {
+      gson.fromJson("\"abc\"", JsonObject.class);
+      fail();
+    } catch (JsonSyntaxException expected) {
+      assertEquals("Expected a com.google.gson.JsonObject but was com.google.gson.JsonPrimitive; at path $",
+          expected.getMessage());
+    }
+  }
+
+  private static class ClassWithBigDecimal {
+    BigDecimal value;
+    ClassWithBigDecimal(String value) {
+      this.value = new BigDecimal(value);
+    }
+    String getExpectedJson() {
+      return "{\"value\":" + value.toEngineeringString() + "}";
+    }
+  }
+
+  private static class ClassWithBigInteger {
+    BigInteger value;
+    ClassWithBigInteger(String value) {
+      this.value = new BigInteger(value);
+    }
+    String getExpectedJson() {
+      return "{\"value\":" + value + "}";
+    }
+  }
+
+  public void testPropertiesSerialization() {
+    Properties props = new Properties();
+    props.setProperty("foo", "bar");
+    String json = gson.toJson(props);
+    String expected = "{\"foo\":\"bar\"}";
+    assertEquals(expected, json);
+  }
+
+  public void testPropertiesDeserialization() {
+    String json = "{foo:'bar'}";
+    Properties props = gson.fromJson(json, Properties.class);
+    assertEquals("bar", props.getProperty("foo"));
+  }
+
+  public void testTreeSetSerialization() {
+    TreeSet<String> treeSet = new TreeSet<>();
+    treeSet.add("Value1");
+    String json = gson.toJson(treeSet);
+    assertEquals("[\"Value1\"]", json);
+  }
+
+  public void testTreeSetDeserialization() {
+    String json = "['Value1']";
+    Type type = new TypeToken<TreeSet<String>>() {}.getType();
+    TreeSet<String> treeSet = gson.fromJson(json, type);
+    assertTrue(treeSet.contains("Value1"));
+  }
+
+  public void testStringBuilderSerialization() {
+    StringBuilder sb = new StringBuilder("abc");
+    String json = gson.toJson(sb);
+    assertEquals("\"abc\"", json);
+  }
+
+  public void testStringBuilderDeserialization() {
+    StringBuilder sb = gson.fromJson("'abc'", StringBuilder.class);
+    assertEquals("abc", sb.toString());
+  }
+
+  public void testStringBufferSerialization() {
+    StringBuffer sb = new StringBuffer("abc");
+    String json = gson.toJson(sb);
+    assertEquals("\"abc\"", json);
+  }
+
+  public void testStringBufferDeserialization() {
+    StringBuffer sb = gson.fromJson("'abc'", StringBuffer.class);
+    assertEquals("abc", sb.toString());
+  }
+
+  @SuppressWarnings("rawtypes")
+  private static class MyClassTypeAdapter extends TypeAdapter<Class> {
+    @Override
+    public void write(JsonWriter out, Class value) throws IOException {
+      out.value(value.getName());
+    }
+    @Override
+    public Class read(JsonReader in) throws IOException {
+      String className = in.nextString();
+      try {
+        return Class.forName(className);
+      } catch (ClassNotFoundException e) {
+        throw new IOException(e);
+      }
+    }
+  }
+
+  static class NumberAsStringAdapter extends TypeAdapter<Number> {
+    private final Constructor<? extends Number> constructor;
+    NumberAsStringAdapter(Class<? extends Number> type) throws Exception {
+      this.constructor = type.getConstructor(String.class);
+    }
+    @Override public void write(JsonWriter out, Number value) throws IOException {
+      out.value(value.toString());
+    }
+    @Override public Number read(JsonReader in) throws IOException {
+      try {
+        return constructor.newInstance(in.nextString());
+      } catch (Exception e) {
+        throw new AssertionError(e);
+      }
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/DelegateTypeAdapterTest.java b/gson/src/test/java/com/google/gson/functional/DelegateTypeAdapterTest.java
new file mode 100644
index 0000000..87ee81e
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/DelegateTypeAdapterTest.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright (C) 2012 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.functional;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import junit.framework.TestCase;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.TypeAdapter;
+import com.google.gson.TypeAdapterFactory;
+import com.google.gson.common.TestTypes.BagOfPrimitives;
+import com.google.gson.reflect.TypeToken;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonWriter;
+
+/**
+ * Functional tests for {@link Gson#getDelegateAdapter(TypeAdapterFactory, TypeToken)} method.
+ *
+ * @author Inderjeet Singh
+ */
+public class DelegateTypeAdapterTest extends TestCase {
+
+  private StatsTypeAdapterFactory stats;
+  private Gson gson;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    stats = new StatsTypeAdapterFactory();
+    gson = new GsonBuilder()
+      .registerTypeAdapterFactory(stats)
+      .create();
+  }
+
+  public void testDelegateInvoked() {
+    List<BagOfPrimitives> bags = new ArrayList<>();
+    for (int i = 0; i < 10; ++i) {
+      bags.add(new BagOfPrimitives(i, i, i % 2 == 0, String.valueOf(i)));
+    }
+    String json = gson.toJson(bags);
+    bags = gson.fromJson(json, new TypeToken<List<BagOfPrimitives>>(){}.getType());
+    // 11: 1 list object, and 10 entries. stats invoked on all 5 fields
+    assertEquals(51, stats.numReads);
+    assertEquals(51, stats.numWrites);
+  }
+
+  public void testDelegateInvokedOnStrings() {
+    String[] bags = {"1", "2", "3", "4"};
+    String json = gson.toJson(bags);
+    bags = gson.fromJson(json, String[].class);
+    // 1 array object with 4 elements.
+    assertEquals(5, stats.numReads);
+    assertEquals(5, stats.numWrites);
+  }
+
+  private static class StatsTypeAdapterFactory implements TypeAdapterFactory {
+    public int numReads = 0;
+    public int numWrites = 0;
+
+    @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
+      final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
+      return new TypeAdapter<T>() {
+        @Override
+        public void write(JsonWriter out, T value) throws IOException {
+          ++numWrites;
+          delegate.write(out, value);
+        }
+
+        @Override
+        public T read(JsonReader in) throws IOException {
+          ++numReads;
+          return delegate.read(in);
+        }
+      };
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/EnumTest.java b/gson/src/test/java/com/google/gson/functional/EnumTest.java
new file mode 100644
index 0000000..b46f80b
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/EnumTest.java
@@ -0,0 +1,276 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.functional;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonDeserializationContext;
+import com.google.gson.JsonDeserializer;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonParseException;
+import com.google.gson.JsonPrimitive;
+import com.google.gson.JsonSerializationContext;
+import com.google.gson.JsonSerializer;
+import com.google.gson.annotations.SerializedName;
+import com.google.gson.common.MoreAsserts;
+import com.google.gson.reflect.TypeToken;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.EnumMap;
+import java.util.EnumSet;
+import java.util.Map;
+import java.util.Set;
+import junit.framework.TestCase;
+
+/**
+ * Functional tests for Java 5.0 enums.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public class EnumTest extends TestCase {
+
+  private Gson gson;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    gson = new Gson();
+  }
+
+  public void testTopLevelEnumSerialization() throws Exception {
+    String result = gson.toJson(MyEnum.VALUE1);
+    assertEquals('"' + MyEnum.VALUE1.toString() + '"', result);
+  }
+
+  public void testTopLevelEnumDeserialization() throws Exception {
+    MyEnum result = gson.fromJson('"' + MyEnum.VALUE1.toString() + '"', MyEnum.class);
+    assertEquals(MyEnum.VALUE1, result);
+  }
+
+  public void testCollectionOfEnumsSerialization() {
+    Type type = new TypeToken<Collection<MyEnum>>() {}.getType();
+    Collection<MyEnum> target = new ArrayList<>();
+    target.add(MyEnum.VALUE1);
+    target.add(MyEnum.VALUE2);
+    String expectedJson = "[\"VALUE1\",\"VALUE2\"]";
+    String actualJson = gson.toJson(target);
+    assertEquals(expectedJson, actualJson);
+    actualJson = gson.toJson(target, type);
+    assertEquals(expectedJson, actualJson);
+  }
+
+  public void testCollectionOfEnumsDeserialization() {
+    Type type = new TypeToken<Collection<MyEnum>>() {}.getType();
+    String json = "[\"VALUE1\",\"VALUE2\"]";
+    Collection<MyEnum> target = gson.fromJson(json, type);
+    MoreAsserts.assertContains(target, MyEnum.VALUE1);
+    MoreAsserts.assertContains(target, MyEnum.VALUE2);
+  }
+
+  public void testClassWithEnumFieldSerialization() throws Exception {
+    ClassWithEnumFields target = new ClassWithEnumFields();
+    assertEquals(target.getExpectedJson(), gson.toJson(target));
+  }
+
+  public void testClassWithEnumFieldDeserialization() throws Exception {
+    String json = "{value1:'VALUE1',value2:'VALUE2'}";
+    ClassWithEnumFields target = gson.fromJson(json, ClassWithEnumFields.class);
+    assertEquals(MyEnum.VALUE1,target.value1);
+    assertEquals(MyEnum.VALUE2,target.value2);
+  }
+
+  private static enum MyEnum {
+    VALUE1, VALUE2
+  }
+
+  private static class ClassWithEnumFields {
+    private final MyEnum value1 = MyEnum.VALUE1;
+    private final MyEnum value2 = MyEnum.VALUE2;
+    public String getExpectedJson() {
+      return "{\"value1\":\"" + value1 + "\",\"value2\":\"" + value2 + "\"}";
+    }
+  }
+
+  /**
+   * Test for issue 226.
+   */
+  public void testEnumSubclass() {
+    assertFalse(Roshambo.class == Roshambo.ROCK.getClass());
+    assertEquals("\"ROCK\"", gson.toJson(Roshambo.ROCK));
+    assertEquals("[\"ROCK\",\"PAPER\",\"SCISSORS\"]", gson.toJson(EnumSet.allOf(Roshambo.class)));
+    assertEquals(Roshambo.ROCK, gson.fromJson("\"ROCK\"", Roshambo.class));
+    assertEquals(EnumSet.allOf(Roshambo.class),
+        gson.fromJson("[\"ROCK\",\"PAPER\",\"SCISSORS\"]", new TypeToken<Set<Roshambo>>() {}.getType()));
+  }
+
+  public void testEnumSubclassWithRegisteredTypeAdapter() {
+    gson = new GsonBuilder()
+        .registerTypeHierarchyAdapter(Roshambo.class, new MyEnumTypeAdapter())
+        .create();
+    assertFalse(Roshambo.class == Roshambo.ROCK.getClass());
+    assertEquals("\"123ROCK\"", gson.toJson(Roshambo.ROCK));
+    assertEquals("[\"123ROCK\",\"123PAPER\",\"123SCISSORS\"]", gson.toJson(EnumSet.allOf(Roshambo.class)));
+    assertEquals(Roshambo.ROCK, gson.fromJson("\"123ROCK\"", Roshambo.class));
+    assertEquals(EnumSet.allOf(Roshambo.class),
+        gson.fromJson("[\"123ROCK\",\"123PAPER\",\"123SCISSORS\"]", new TypeToken<Set<Roshambo>>() {}.getType()));
+  }
+
+  public void testEnumSubclassAsParameterizedType() {
+    Collection<Roshambo> list = new ArrayList<>();
+    list.add(Roshambo.ROCK);
+    list.add(Roshambo.PAPER);
+
+    String json = gson.toJson(list);
+    assertEquals("[\"ROCK\",\"PAPER\"]", json);
+
+    Type collectionType = new TypeToken<Collection<Roshambo>>() {}.getType();
+    Collection<Roshambo> actualJsonList = gson.fromJson(json, collectionType);
+    MoreAsserts.assertContains(actualJsonList, Roshambo.ROCK);
+    MoreAsserts.assertContains(actualJsonList, Roshambo.PAPER);
+  }
+
+  public void testEnumCaseMapping() {
+    assertEquals(Gender.MALE, gson.fromJson("\"boy\"", Gender.class));
+    assertEquals("\"boy\"", gson.toJson(Gender.MALE, Gender.class));
+  }
+
+  public void testEnumSet() {
+    EnumSet<Roshambo> foo = EnumSet.of(Roshambo.ROCK, Roshambo.PAPER);
+    String json = gson.toJson(foo);
+    assertEquals("[\"ROCK\",\"PAPER\"]", json);
+
+    Type type = new TypeToken<EnumSet<Roshambo>>() {}.getType();
+    EnumSet<Roshambo> bar = gson.fromJson(json, type);
+    assertTrue(bar.contains(Roshambo.ROCK));
+    assertTrue(bar.contains(Roshambo.PAPER));
+    assertFalse(bar.contains(Roshambo.SCISSORS));
+  }
+
+  public void testEnumMap() throws Exception {
+    EnumMap<MyEnum, String> map = new EnumMap<>(MyEnum.class);
+    map.put(MyEnum.VALUE1, "test");
+    String json = gson.toJson(map);
+    assertEquals("{\"VALUE1\":\"test\"}", json);
+
+    Type type = new TypeToken<EnumMap<MyEnum, String>>() {}.getType();
+    EnumMap<?, ?> actualMap = gson.fromJson("{\"VALUE1\":\"test\"}", type);
+    Map<?, ?> expectedMap = Collections.singletonMap(MyEnum.VALUE1, "test");
+    assertEquals(expectedMap, actualMap);
+  }
+
+  private enum Roshambo {
+    ROCK {
+      @Override Roshambo defeats() {
+        return SCISSORS;
+      }
+    },
+    PAPER {
+      @Override Roshambo defeats() {
+        return ROCK;
+      }
+    },
+    SCISSORS {
+      @Override Roshambo defeats() {
+        return PAPER;
+      }
+    };
+
+    abstract Roshambo defeats();
+  }
+
+  private static class MyEnumTypeAdapter
+      implements JsonSerializer<Roshambo>, JsonDeserializer<Roshambo> {
+    @Override public JsonElement serialize(Roshambo src, Type typeOfSrc, JsonSerializationContext context) {
+      return new JsonPrimitive("123" + src.name());
+    }
+
+    @Override public Roshambo deserialize(JsonElement json, Type classOfT, JsonDeserializationContext context)
+        throws JsonParseException {
+      return Roshambo.valueOf(json.getAsString().substring(3));
+    }
+  }
+
+  private enum Gender {
+    @SerializedName("boy")
+    MALE,
+
+    @SerializedName("girl")
+    FEMALE
+  }
+
+  public void testEnumClassWithFields() {
+    assertEquals("\"RED\"", gson.toJson(Color.RED));
+    assertEquals("red", gson.fromJson("RED", Color.class).value);
+    assertEquals(2, gson.fromJson("BLUE", Color.class).index);
+  }
+
+  private enum Color {
+    RED("red", 1), BLUE("blue", 2), GREEN("green", 3);
+    String value;
+    int index;
+    private Color(String value, int index) {
+      this.value = value;
+      this.index = index;
+    }
+  }
+
+  public void testEnumToStringRead() {
+    // Should still be able to read constant name
+    assertEquals(CustomToString.A, gson.fromJson("\"A\"", CustomToString.class));
+    // Should be able to read toString() value
+    assertEquals(CustomToString.A, gson.fromJson("\"test\"", CustomToString.class));
+
+    assertNull(gson.fromJson("\"other\"", CustomToString.class));
+  }
+
+  private enum CustomToString {
+    A;
+
+    @Override
+    public String toString() {
+      return "test";
+    }
+  }
+
+  /**
+   * Test that enum constant names have higher precedence than {@code toString()}
+   * result.
+   */
+  public void testEnumToStringReadInterchanged() {
+    assertEquals(InterchangedToString.A, gson.fromJson("\"A\"", InterchangedToString.class));
+    assertEquals(InterchangedToString.B, gson.fromJson("\"B\"", InterchangedToString.class));
+  }
+
+  private enum InterchangedToString {
+    A("B"),
+    B("A");
+
+    private final String toString;
+
+    InterchangedToString(String toString) {
+      this.toString = toString;
+    }
+
+    @Override
+    public String toString() {
+      return toString;
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/EnumWithObfuscatedTest.java b/gson/src/test/java/com/google/gson/functional/EnumWithObfuscatedTest.java
new file mode 100644
index 0000000..080b81f
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/EnumWithObfuscatedTest.java
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.functional;
+
+import com.google.gson.Gson;
+import com.google.gson.annotations.SerializedName;
+
+import junit.framework.TestCase;
+
+/**
+ * Functional tests for enums with Proguard.
+ *
+ * @author Young Cha
+ */
+public class EnumWithObfuscatedTest extends TestCase {
+  private Gson gson;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    gson = new Gson();
+  }
+
+  public enum Gender {
+    @SerializedName("MAIL")
+    MALE,
+
+    @SerializedName("FEMAIL")
+    FEMALE
+  }
+
+  public void testEnumClassWithObfuscated() {
+    for (Gender enumConstant: Gender.class.getEnumConstants()) {
+      try {
+        Gender.class.getField(enumConstant.name());
+        fail("Enum is not obfuscated");
+      } catch (NoSuchFieldException ignore) {
+      }
+    }
+
+    assertEquals(Gender.MALE, gson.fromJson("\"MAIL\"", Gender.class));
+    assertEquals("\"MAIL\"", gson.toJson(Gender.MALE, Gender.class));
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/EscapingTest.java b/gson/src/test/java/com/google/gson/functional/EscapingTest.java
new file mode 100644
index 0000000..053fd9a
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/EscapingTest.java
@@ -0,0 +1,92 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.functional;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.common.TestTypes.BagOfPrimitives;
+import java.util.ArrayList;
+import java.util.List;
+import junit.framework.TestCase;
+
+/**
+ * Performs some functional test involving JSON output escaping.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public class EscapingTest extends TestCase {
+  private Gson gson;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    gson = new Gson();
+  }
+
+  public void testEscapingQuotesInStringArray() throws Exception {
+    String[] valueWithQuotes = { "beforeQuote\"afterQuote" };
+    String jsonRepresentation = gson.toJson(valueWithQuotes);
+    String[] target = gson.fromJson(jsonRepresentation, String[].class);
+    assertEquals(1, target.length);
+    assertEquals(valueWithQuotes[0], target[0]);
+  }
+
+  public void testEscapeAllHtmlCharacters() {
+    List<String> strings = new ArrayList<>();
+    strings.add("<");
+    strings.add(">");
+    strings.add("=");
+    strings.add("&");
+    strings.add("'");
+    strings.add("\"");
+    assertEquals("[\"\\u003c\",\"\\u003e\",\"\\u003d\",\"\\u0026\",\"\\u0027\",\"\\\"\"]",
+        gson.toJson(strings));
+  }
+
+  public void testEscapingObjectFields() throws Exception {
+    BagOfPrimitives objWithPrimitives = new BagOfPrimitives(1L, 1, true, "test with\" <script>");
+    String jsonRepresentation = gson.toJson(objWithPrimitives);
+    assertFalse(jsonRepresentation.contains("<"));
+    assertFalse(jsonRepresentation.contains(">"));
+    assertTrue(jsonRepresentation.contains("\\\""));
+
+    BagOfPrimitives expectedObject = gson.fromJson(jsonRepresentation, BagOfPrimitives.class);
+    assertEquals(objWithPrimitives.getExpectedJson(), expectedObject.getExpectedJson());
+  }
+  
+  public void testGsonAcceptsEscapedAndNonEscapedJsonDeserialization() throws Exception {
+    Gson escapeHtmlGson = new GsonBuilder().create();
+    Gson noEscapeHtmlGson = new GsonBuilder().disableHtmlEscaping().create();
+    
+    BagOfPrimitives target = new BagOfPrimitives(1L, 1, true, "test' / w'ith\" / \\ <script>");
+    String escapedJsonForm = escapeHtmlGson.toJson(target);
+    String nonEscapedJsonForm = noEscapeHtmlGson.toJson(target);
+    assertFalse(escapedJsonForm.equals(nonEscapedJsonForm));
+    
+    assertEquals(target, noEscapeHtmlGson.fromJson(escapedJsonForm, BagOfPrimitives.class));
+    assertEquals(target, escapeHtmlGson.fromJson(nonEscapedJsonForm, BagOfPrimitives.class));
+  }
+
+  public void testGsonDoubleDeserialization() {
+    BagOfPrimitives expected = new BagOfPrimitives(3L, 4, true, "value1");
+    String json = gson.toJson(gson.toJson(expected));
+    String value = gson.fromJson(json, String.class);
+    BagOfPrimitives actual = gson.fromJson(value, BagOfPrimitives.class);
+    assertEquals(expected, actual);
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/ExclusionStrategyFunctionalTest.java b/gson/src/test/java/com/google/gson/functional/ExclusionStrategyFunctionalTest.java
new file mode 100644
index 0000000..2eca8bb
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/ExclusionStrategyFunctionalTest.java
@@ -0,0 +1,202 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.functional;
+
+import com.google.gson.ExclusionStrategy;
+import com.google.gson.FieldAttributes;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonPrimitive;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import junit.framework.TestCase;
+
+/**
+ * Performs some functional tests when Gson is instantiated with some common user defined
+ * {@link ExclusionStrategy} objects.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public class ExclusionStrategyFunctionalTest extends TestCase {
+  private static final ExclusionStrategy EXCLUDE_SAMPLE_OBJECT_FOR_TEST = new ExclusionStrategy() {
+    @Override public boolean shouldSkipField(FieldAttributes f) {
+      return false;
+    }
+    @Override public boolean shouldSkipClass(Class<?> clazz) {
+      return clazz == SampleObjectForTest.class;
+    }
+  };
+
+  private SampleObjectForTest src;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    src = new SampleObjectForTest();
+  }
+
+  public void testExclusionStrategySerialization() throws Exception {
+    Gson gson = createGson(new MyExclusionStrategy(String.class), true);
+    String json = gson.toJson(src);
+    assertFalse(json.contains("\"stringField\""));
+    assertFalse(json.contains("\"annotatedField\""));
+    assertTrue(json.contains("\"longField\""));
+  }
+
+  public void testExclusionStrategySerializationDoesNotImpactDeserialization() {
+    String json = "{\"annotatedField\":1,\"stringField\":\"x\",\"longField\":2}";
+    Gson gson = createGson(new MyExclusionStrategy(String.class), true);
+    SampleObjectForTest value = gson.fromJson(json, SampleObjectForTest.class);
+    assertEquals(1, value.annotatedField);
+    assertEquals("x", value.stringField);
+    assertEquals(2, value.longField);
+  }
+
+  public void testExclusionStrategyDeserialization() throws Exception {
+    Gson gson = createGson(new MyExclusionStrategy(String.class), false);
+    JsonObject json = new JsonObject();
+    json.add("annotatedField", new JsonPrimitive(src.annotatedField + 5));
+    json.add("stringField", new JsonPrimitive(src.stringField + "blah,blah"));
+    json.add("longField", new JsonPrimitive(1212311L));
+
+    SampleObjectForTest target = gson.fromJson(json, SampleObjectForTest.class);
+    assertEquals(1212311L, target.longField);
+
+    // assert excluded fields are set to the defaults
+    assertEquals(src.annotatedField, target.annotatedField);
+    assertEquals(src.stringField, target.stringField);
+  }
+
+  public void testExclusionStrategySerializationDoesNotImpactSerialization() throws Exception {
+    Gson gson = createGson(new MyExclusionStrategy(String.class), false);
+    String json = gson.toJson(src);
+    assertTrue(json.contains("\"stringField\""));
+    assertTrue(json.contains("\"annotatedField\""));
+    assertTrue(json.contains("\"longField\""));
+  }
+
+  public void testExclusionStrategyWithMode() throws Exception {
+    SampleObjectForTest testObj = new SampleObjectForTest(
+        src.annotatedField + 5, src.stringField + "blah,blah",
+        src.longField + 655L);
+
+    Gson gson = createGson(new MyExclusionStrategy(String.class), false);
+    JsonObject json = gson.toJsonTree(testObj).getAsJsonObject();
+    assertEquals(testObj.annotatedField, json.get("annotatedField").getAsInt());
+    assertEquals(testObj.stringField, json.get("stringField").getAsString());
+    assertEquals(testObj.longField, json.get("longField").getAsLong());
+
+    SampleObjectForTest target = gson.fromJson(json, SampleObjectForTest.class);
+    assertEquals(testObj.longField, target.longField);
+
+    // assert excluded fields are set to the defaults
+    assertEquals(src.annotatedField, target.annotatedField);
+    assertEquals(src.stringField, target.stringField);
+  }
+
+  public void testExcludeTopLevelClassSerialization() {
+    Gson gson = new GsonBuilder()
+        .addSerializationExclusionStrategy(EXCLUDE_SAMPLE_OBJECT_FOR_TEST)
+        .create();
+    assertEquals("null", gson.toJson(new SampleObjectForTest(), SampleObjectForTest.class));
+  }
+
+  public void testExcludeTopLevelClassSerializationDoesNotImpactDeserialization() {
+    Gson gson = new GsonBuilder()
+        .addSerializationExclusionStrategy(EXCLUDE_SAMPLE_OBJECT_FOR_TEST)
+        .create();
+    String json = "{\"annotatedField\":1,\"stringField\":\"x\",\"longField\":2}";
+    SampleObjectForTest value = gson.fromJson(json, SampleObjectForTest.class);
+    assertEquals(1, value.annotatedField);
+    assertEquals("x", value.stringField);
+    assertEquals(2, value.longField);
+  }
+
+  public void testExcludeTopLevelClassDeserialization() {
+    Gson gson = new GsonBuilder()
+        .addDeserializationExclusionStrategy(EXCLUDE_SAMPLE_OBJECT_FOR_TEST)
+        .create();
+    String json = "{\"annotatedField\":1,\"stringField\":\"x\",\"longField\":2}";
+    SampleObjectForTest value = gson.fromJson(json, SampleObjectForTest.class);
+    assertNull(value);
+  }
+
+  public void testExcludeTopLevelClassDeserializationDoesNotImpactSerialization() {
+    Gson gson = new GsonBuilder()
+        .addDeserializationExclusionStrategy(EXCLUDE_SAMPLE_OBJECT_FOR_TEST)
+        .create();
+    String json = gson.toJson(new SampleObjectForTest(), SampleObjectForTest.class);
+    assertTrue(json.contains("\"stringField\""));
+    assertTrue(json.contains("\"annotatedField\""));
+    assertTrue(json.contains("\"longField\""));
+  }
+
+  private static Gson createGson(ExclusionStrategy exclusionStrategy, boolean serialization) {
+    GsonBuilder gsonBuilder = new GsonBuilder();
+    if (serialization) {
+      gsonBuilder.addSerializationExclusionStrategy(exclusionStrategy);
+    } else {
+      gsonBuilder.addDeserializationExclusionStrategy(exclusionStrategy);
+    }
+    return gsonBuilder
+        .serializeNulls()
+        .create();
+  }
+
+  @Retention(RetentionPolicy.RUNTIME)
+  @Target({ElementType.FIELD})
+  private static @interface Foo {
+    // Field tag only annotation
+  }
+
+  private static class SampleObjectForTest {
+    @Foo
+    private final int annotatedField;
+    private final String stringField;
+    private final long longField;
+
+    public SampleObjectForTest() {
+      this(5, "someDefaultValue", 12345L);
+    }
+
+    public SampleObjectForTest(int annotatedField, String stringField, long longField) {
+      this.annotatedField = annotatedField;
+      this.stringField = stringField;
+      this.longField = longField;
+    }
+  }
+
+  private static final class MyExclusionStrategy implements ExclusionStrategy {
+    private final Class<?> typeToSkip;
+
+    private MyExclusionStrategy(Class<?> typeToSkip) {
+      this.typeToSkip = typeToSkip;
+    }
+
+    @Override public boolean shouldSkipClass(Class<?> clazz) {
+      return (clazz == typeToSkip);
+    }
+
+    @Override public boolean shouldSkipField(FieldAttributes f) {
+      return f.getAnnotation(Foo.class) != null;
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/ExposeFieldsTest.java b/gson/src/test/java/com/google/gson/functional/ExposeFieldsTest.java
new file mode 100644
index 0000000..0430ba4
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/ExposeFieldsTest.java
@@ -0,0 +1,169 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.functional;
+
+import java.lang.reflect.Type;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.InstanceCreator;
+import com.google.gson.annotations.Expose;
+
+import junit.framework.TestCase;
+
+/**
+ * Unit tests for the regarding functional "@Expose" type tests.
+ *
+ * @author Joel Leitch
+ */
+public class ExposeFieldsTest extends TestCase {
+
+  private Gson gson;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    gson = new GsonBuilder()
+        .excludeFieldsWithoutExposeAnnotation()
+        .registerTypeAdapter(SomeInterface.class, new SomeInterfaceInstanceCreator())
+        .create();
+  }
+
+  public void testNullExposeFieldSerialization() throws Exception {
+    ClassWithExposedFields object = new ClassWithExposedFields(null, 1);
+    String json = gson.toJson(object);
+
+    assertEquals(object.getExpectedJson(), json);
+  }
+
+  public void testArrayWithOneNullExposeFieldObjectSerialization() throws Exception {
+    ClassWithExposedFields object1 = new ClassWithExposedFields(1, 1);
+    ClassWithExposedFields object2 = new ClassWithExposedFields(null, 1);
+    ClassWithExposedFields object3 = new ClassWithExposedFields(2, 2);
+    ClassWithExposedFields[] objects = { object1, object2, object3 };
+
+    String json = gson.toJson(objects);
+    String expected = new StringBuilder()
+        .append('[').append(object1.getExpectedJson()).append(',')
+        .append(object2.getExpectedJson()).append(',')
+        .append(object3.getExpectedJson()).append(']')
+        .toString();
+
+    assertEquals(expected, json);
+  }
+
+  public void testExposeAnnotationSerialization() throws Exception {
+    ClassWithExposedFields target = new ClassWithExposedFields(1, 2);
+    assertEquals(target.getExpectedJson(), gson.toJson(target));
+  }
+
+  public void testExposeAnnotationDeserialization() throws Exception {
+    String json = "{a:3,b:4,d:20.0}";
+    ClassWithExposedFields target = gson.fromJson(json, ClassWithExposedFields.class);
+
+    assertEquals(3, (int) target.a);
+    assertNull(target.b);
+    assertFalse(target.d == 20);
+  }
+
+  public void testNoExposedFieldSerialization() throws Exception {
+    ClassWithNoExposedFields obj = new ClassWithNoExposedFields();
+    String json = gson.toJson(obj);
+
+    assertEquals("{}", json);
+  }
+
+  public void testNoExposedFieldDeserialization() throws Exception {
+    String json = "{a:4,b:5}";
+    ClassWithNoExposedFields obj = gson.fromJson(json, ClassWithNoExposedFields.class);
+
+    assertEquals(0, obj.a);
+    assertEquals(1, obj.b);
+  }
+  
+  public void testExposedInterfaceFieldSerialization() throws Exception {
+    String expected = "{\"interfaceField\":{}}";
+    ClassWithInterfaceField target = new ClassWithInterfaceField(new SomeObject());
+    String actual = gson.toJson(target);
+    
+    assertEquals(expected, actual);
+  }
+  
+  public void testExposedInterfaceFieldDeserialization() throws Exception {
+    String json = "{\"interfaceField\":{}}";
+    ClassWithInterfaceField obj = gson.fromJson(json, ClassWithInterfaceField.class);
+
+    assertNotNull(obj.interfaceField);
+  }
+
+  private static class ClassWithExposedFields {
+    @Expose private final Integer a;
+    private final Integer b;
+    @Expose(serialize = false) final long c;
+    @Expose(deserialize = false) final double d;
+    @Expose(serialize = false, deserialize = false) final char e;
+
+    public ClassWithExposedFields(Integer a, Integer b) {
+      this(a, b, 1L, 2.0, 'a');
+    }
+    public ClassWithExposedFields(Integer a, Integer b, long c, double d, char e) {
+      this.a = a;
+      this.b = b;
+      this.c = c;
+      this.d = d;
+      this.e = e;
+    }
+
+    public String getExpectedJson() {
+      StringBuilder sb = new StringBuilder("{");
+      if (a != null) {
+        sb.append("\"a\":").append(a).append(",");
+      }
+      sb.append("\"d\":").append(d);
+      sb.append("}");
+      return sb.toString();
+    }
+  }
+
+  private static class ClassWithNoExposedFields {
+    private final int a = 0;
+    private final int b = 1;
+  }
+  
+  private static interface SomeInterface {
+    // Empty interface
+  }
+  
+  private static class SomeObject implements SomeInterface {
+    // Do nothing
+  }
+  
+  private static class SomeInterfaceInstanceCreator implements InstanceCreator<SomeInterface> {
+    @Override public SomeInterface createInstance(Type type) {
+      return new SomeObject();
+    }
+  }
+  
+  private static class ClassWithInterfaceField {
+    @Expose
+    private final SomeInterface interfaceField;
+
+    public ClassWithInterfaceField(SomeInterface interfaceField) {
+      this.interfaceField = interfaceField;
+    }
+  }  
+}
diff --git a/gson/src/test/java/com/google/gson/functional/FieldExclusionTest.java b/gson/src/test/java/com/google/gson/functional/FieldExclusionTest.java
new file mode 100644
index 0000000..080a823
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/FieldExclusionTest.java
@@ -0,0 +1,92 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.functional;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+import junit.framework.TestCase;
+
+/**
+ * Performs some functional testing to ensure GSON infrastructure properly serializes/deserializes
+ * fields that either should or should not be included in the output based on the GSON
+ * configuration.
+ *
+ * @author Joel Leitch
+ */
+public class FieldExclusionTest extends TestCase {
+  private static final String VALUE = "blah_1234";
+
+  private Outer outer;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    outer = new Outer();
+  }
+
+  public void testDefaultInnerClassExclusion() throws Exception {
+    Gson gson = new Gson();
+    Outer.Inner target = outer.new Inner(VALUE);
+    String result = gson.toJson(target);
+    assertEquals(target.toJson(), result);
+
+    gson = new GsonBuilder().create();
+    target = outer.new Inner(VALUE);
+    result = gson.toJson(target);
+    assertEquals(target.toJson(), result);
+  }
+
+  public void testInnerClassExclusion() throws Exception {
+    Gson gson = new GsonBuilder().disableInnerClassSerialization().create();
+    Outer.Inner target = outer.new Inner(VALUE);
+    String result = gson.toJson(target);
+    assertEquals("null", result);
+  }
+
+  public void testDefaultNestedStaticClassIncluded() throws Exception {
+    Gson gson = new Gson();
+    Outer.Inner target = outer.new Inner(VALUE);
+    String result = gson.toJson(target);
+    assertEquals(target.toJson(), result);
+
+    gson = new GsonBuilder().create();
+    target = outer.new Inner(VALUE);
+    result = gson.toJson(target);
+    assertEquals(target.toJson(), result);
+  }
+
+  private static class Outer {
+    private class Inner extends NestedClass {
+      public Inner(String value) {
+        super(value);
+      }
+    }
+
+  }
+
+  private static class NestedClass {
+    private final String value;
+    public NestedClass(String value) {
+      this.value = value;
+    }
+
+    public String toJson() {
+      return "{\"value\":\"" + value + "\"}";
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/FieldNamingTest.java b/gson/src/test/java/com/google/gson/functional/FieldNamingTest.java
new file mode 100644
index 0000000..04ba7b7
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/FieldNamingTest.java
@@ -0,0 +1,99 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.functional;
+
+import static com.google.gson.FieldNamingPolicy.IDENTITY;
+import static com.google.gson.FieldNamingPolicy.LOWER_CASE_WITH_DASHES;
+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_WITH_SPACES;
+import static com.google.gson.FieldNamingPolicy.UPPER_CASE_WITH_UNDERSCORES;
+
+import com.google.gson.FieldNamingPolicy;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.annotations.SerializedName;
+import junit.framework.TestCase;
+
+public final class FieldNamingTest extends TestCase {
+  public void testIdentity() {
+    Gson gson = getGsonWithNamingPolicy(IDENTITY);
+    assertEquals("{'lowerCamel':1,'UpperCamel':2,'_lowerCamelLeadingUnderscore':3," +
+        "'_UpperCamelLeadingUnderscore':4,'lower_words':5,'UPPER_WORDS':6," +
+        "'annotatedName':7,'lowerId':8,'_9':9}",
+        gson.toJson(new TestNames()).replace('\"', '\''));
+  }
+
+  public void testUpperCamelCase() {
+    Gson gson = getGsonWithNamingPolicy(UPPER_CAMEL_CASE);
+    assertEquals("{'LowerCamel':1,'UpperCamel':2,'_LowerCamelLeadingUnderscore':3," +
+        "'_UpperCamelLeadingUnderscore':4,'Lower_words':5,'UPPER_WORDS':6," +
+        "'annotatedName':7,'LowerId':8,'_9':9}",
+        gson.toJson(new TestNames()).replace('\"', '\''));
+  }
+
+  public void testUpperCamelCaseWithSpaces() {
+    Gson gson = getGsonWithNamingPolicy(UPPER_CAMEL_CASE_WITH_SPACES);
+    assertEquals("{'Lower Camel':1,'Upper Camel':2,'_Lower Camel Leading Underscore':3," +
+        "'_ Upper Camel Leading Underscore':4,'Lower_words':5,'U P P E R_ W O R D S':6," +
+        "'annotatedName':7,'Lower Id':8,'_9':9}",
+        gson.toJson(new TestNames()).replace('\"', '\''));
+  }
+
+  public void testUpperCaseWithUnderscores() {
+    Gson gson = getGsonWithNamingPolicy(UPPER_CASE_WITH_UNDERSCORES);
+    assertEquals("{'LOWER_CAMEL':1,'UPPER_CAMEL':2,'_LOWER_CAMEL_LEADING_UNDERSCORE':3," +
+        "'__UPPER_CAMEL_LEADING_UNDERSCORE':4,'LOWER_WORDS':5,'U_P_P_E_R__W_O_R_D_S':6," +
+        "'annotatedName':7,'LOWER_ID':8,'_9':9}",
+        gson.toJson(new TestNames()).replace('\"', '\''));
+  }
+
+  public void testLowerCaseWithUnderscores() {
+    Gson gson = getGsonWithNamingPolicy(LOWER_CASE_WITH_UNDERSCORES);
+    assertEquals("{'lower_camel':1,'upper_camel':2,'_lower_camel_leading_underscore':3," +
+        "'__upper_camel_leading_underscore':4,'lower_words':5,'u_p_p_e_r__w_o_r_d_s':6," +
+        "'annotatedName':7,'lower_id':8,'_9':9}",
+        gson.toJson(new TestNames()).replace('\"', '\''));
+  }
+
+  public void testLowerCaseWithDashes() {
+    Gson gson = getGsonWithNamingPolicy(LOWER_CASE_WITH_DASHES);
+    assertEquals("{'lower-camel':1,'upper-camel':2,'_lower-camel-leading-underscore':3," +
+        "'_-upper-camel-leading-underscore':4,'lower_words':5,'u-p-p-e-r_-w-o-r-d-s':6," +
+        "'annotatedName':7,'lower-id':8,'_9':9}",
+        gson.toJson(new TestNames()).replace('\"', '\''));
+  }
+
+  private Gson getGsonWithNamingPolicy(FieldNamingPolicy fieldNamingPolicy){
+    return new GsonBuilder()
+      .setFieldNamingPolicy(fieldNamingPolicy)
+        .create();
+  }
+
+  @SuppressWarnings("unused") // fields are used reflectively
+  private static class TestNames {
+    int lowerCamel = 1;
+    int UpperCamel = 2;
+    int _lowerCamelLeadingUnderscore = 3;
+    int _UpperCamelLeadingUnderscore = 4;
+    int lower_words = 5;
+    int UPPER_WORDS = 6;
+    @SerializedName("annotatedName") int annotated = 7;
+    int lowerId = 8;
+    int _9 = 9;
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/GsonVersionDiagnosticsTest.java b/gson/src/test/java/com/google/gson/functional/GsonVersionDiagnosticsTest.java
new file mode 100644
index 0000000..aa6f4cc
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/GsonVersionDiagnosticsTest.java
@@ -0,0 +1,97 @@
+/*
+ * Copyright (C) 2018 Gson Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.functional;
+
+import java.io.IOException;
+import java.util.regex.Pattern;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.TypeAdapter;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonWriter;
+
+import junit.framework.TestCase;
+
+/**
+ * Functional tests to validate printing of Gson version on AssertionErrors
+ *
+ * @author Inderjeet Singh
+ */
+public class GsonVersionDiagnosticsTest extends TestCase {
+  private static final Pattern GSON_VERSION_PATTERN = Pattern.compile("(\\(GSON \\d\\.\\d\\.\\d)(?:[-.][A-Z]+)?\\)$");
+
+  private Gson gson;
+
+  @Before
+  @Override
+  public void setUp() {
+    gson = new GsonBuilder().registerTypeAdapter(TestType.class, new TypeAdapter<TestType>() {
+      @Override public void write(JsonWriter out, TestType value) {
+        throw new AssertionError("Expected during serialization");
+      }
+      @Override public TestType read(JsonReader in) throws IOException {
+        throw new AssertionError("Expected during deserialization");
+      }
+    }).create();
+  }
+
+  @Test
+  public void testVersionPattern() {
+    assertTrue(GSON_VERSION_PATTERN.matcher("(GSON 2.8.5)").matches());
+    assertTrue(GSON_VERSION_PATTERN.matcher("(GSON 2.8.5-SNAPSHOT)").matches());
+  }
+
+  @Test
+  public void testAssertionErrorInSerializationPrintsVersion() {
+    try {
+      gson.toJson(new TestType());
+      fail();
+    } catch (AssertionError expected) {
+      ensureAssertionErrorPrintsGsonVersion(expected);
+    }
+  }
+
+  @Test
+  public void testAssertionErrorInDeserializationPrintsVersion() {
+    try {
+      gson.fromJson("{'a':'abc'}", TestType.class);
+      fail();
+    } catch (AssertionError expected) {
+      ensureAssertionErrorPrintsGsonVersion(expected);
+    }
+  }
+
+  private void ensureAssertionErrorPrintsGsonVersion(AssertionError expected) {
+    String msg = expected.getMessage();
+    // System.err.println(msg);
+    int start = msg.indexOf("(GSON");
+    assertTrue(start > 0);
+    int end = msg.indexOf("):") + 1;
+    assertTrue(end > 0 && end > start + 6);
+    String version = msg.substring(start, end);
+    // System.err.println(version);
+    assertTrue(GSON_VERSION_PATTERN.matcher(version).matches());
+  }
+
+  private static final class TestType {
+    @SuppressWarnings("unused")
+    String a;
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/InheritanceTest.java b/gson/src/test/java/com/google/gson/functional/InheritanceTest.java
new file mode 100644
index 0000000..84de37d
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/InheritanceTest.java
@@ -0,0 +1,277 @@
+/*
+ * Copyright (C) 2009 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.functional;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.common.TestTypes.BagOfPrimitives;
+import com.google.gson.common.TestTypes.Base;
+import com.google.gson.common.TestTypes.ClassWithBaseArrayField;
+import com.google.gson.common.TestTypes.ClassWithBaseCollectionField;
+import com.google.gson.common.TestTypes.ClassWithBaseField;
+import com.google.gson.common.TestTypes.Nested;
+import com.google.gson.common.TestTypes.Sub;
+
+import junit.framework.TestCase;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Queue;
+import java.util.Set;
+import java.util.SortedSet;
+import java.util.TreeSet;
+
+/**
+ * Functional tests for Json serialization and deserialization of classes with 
+ * inheritance hierarchies.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public class InheritanceTest extends TestCase {
+  private Gson gson;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    gson = new Gson();
+  }
+
+  public void testSubClassSerialization() throws Exception {
+    SubTypeOfNested target = new SubTypeOfNested(new BagOfPrimitives(10, 20, false, "stringValue"),
+        new BagOfPrimitives(30, 40, true, "stringValue"));
+    assertEquals(target.getExpectedJson(), gson.toJson(target));
+  }
+
+  public void testSubClassDeserialization() throws Exception {
+    String json = "{\"value\":5,\"primitive1\":{\"longValue\":10,\"intValue\":20,"
+        + "\"booleanValue\":false,\"stringValue\":\"stringValue\"},\"primitive2\":"
+        + "{\"longValue\":30,\"intValue\":40,\"booleanValue\":true,"
+        + "\"stringValue\":\"stringValue\"}}";
+    SubTypeOfNested target = gson.fromJson(json, SubTypeOfNested.class);
+    assertEquals(json, target.getExpectedJson());
+  }
+
+  public void testClassWithBaseFieldSerialization() {
+    ClassWithBaseField sub = new ClassWithBaseField(new Sub());
+    JsonObject json = (JsonObject) gson.toJsonTree(sub);
+    JsonElement base = json.getAsJsonObject().get(ClassWithBaseField.FIELD_KEY);
+    assertEquals(Sub.SUB_NAME, base.getAsJsonObject().get(Sub.SUB_FIELD_KEY).getAsString());
+  }
+
+  public void testClassWithBaseArrayFieldSerialization() {
+    Base[] baseClasses = new Base[]{ new Sub(), new Sub()};
+    ClassWithBaseArrayField sub = new ClassWithBaseArrayField(baseClasses);
+    JsonObject json = gson.toJsonTree(sub).getAsJsonObject();
+    JsonArray bases = json.get(ClassWithBaseArrayField.FIELD_KEY).getAsJsonArray();
+    for (JsonElement element : bases) { 
+      assertEquals(Sub.SUB_NAME, element.getAsJsonObject().get(Sub.SUB_FIELD_KEY).getAsString());
+    }
+  }
+
+  public void testClassWithBaseCollectionFieldSerialization() {
+    Collection<Base> baseClasses = new ArrayList<>();
+    baseClasses.add(new Sub());
+    baseClasses.add(new Sub());
+    ClassWithBaseCollectionField sub = new ClassWithBaseCollectionField(baseClasses);
+    JsonObject json = gson.toJsonTree(sub).getAsJsonObject();
+    JsonArray bases = json.get(ClassWithBaseArrayField.FIELD_KEY).getAsJsonArray();
+    for (JsonElement element : bases) { 
+      assertEquals(Sub.SUB_NAME, element.getAsJsonObject().get(Sub.SUB_FIELD_KEY).getAsString());
+    }
+  }
+
+  public void testBaseSerializedAsSub() {
+    Base base = new Sub();
+    JsonObject json = gson.toJsonTree(base).getAsJsonObject();
+    assertEquals(Sub.SUB_NAME, json.get(Sub.SUB_FIELD_KEY).getAsString());
+  }
+
+  public void testBaseSerializedAsSubForToJsonMethod() {
+    Base base = new Sub();
+    String json = gson.toJson(base);
+    assertTrue(json.contains(Sub.SUB_NAME));
+  }
+
+  public void testBaseSerializedAsBaseWhenSpecifiedWithExplicitType() {
+    Base base = new Sub();
+    JsonObject json = gson.toJsonTree(base, Base.class).getAsJsonObject();
+    assertEquals(Base.BASE_NAME, json.get(Base.BASE_FIELD_KEY).getAsString());
+    assertNull(json.get(Sub.SUB_FIELD_KEY));
+  }
+
+  public void testBaseSerializedAsBaseWhenSpecifiedWithExplicitTypeForToJsonMethod() {
+    Base base = new Sub();
+    String json = gson.toJson(base, Base.class);
+    assertTrue(json.contains(Base.BASE_NAME));
+    assertFalse(json.contains(Sub.SUB_FIELD_KEY));
+  }
+
+  public void testBaseSerializedAsSubWhenSpecifiedWithExplicitType() {
+    Base base = new Sub();
+    JsonObject json = gson.toJsonTree(base, Sub.class).getAsJsonObject();
+    assertEquals(Sub.SUB_NAME, json.get(Sub.SUB_FIELD_KEY).getAsString());
+  }
+
+  public void testBaseSerializedAsSubWhenSpecifiedWithExplicitTypeForToJsonMethod() {
+    Base base = new Sub();
+    String json = gson.toJson(base, Sub.class);
+    assertTrue(json.contains(Sub.SUB_NAME));
+  }
+
+  private static class SubTypeOfNested extends Nested {
+    private final long value = 5;
+
+    public SubTypeOfNested(BagOfPrimitives primitive1, BagOfPrimitives primitive2) {
+      super(primitive1, primitive2);
+    }
+
+    @Override
+    public void appendFields(StringBuilder sb) {
+      sb.append("\"value\":").append(value).append(",");
+      super.appendFields(sb);
+    }
+  }
+
+  public void testSubInterfacesOfCollectionSerialization() throws Exception {
+    List<Integer> list = new LinkedList<>();
+    list.add(0);
+    list.add(1);
+    list.add(2);
+    list.add(3);
+    Queue<Long> queue = new LinkedList<>();
+    queue.add(0L);
+    queue.add(1L);
+    queue.add(2L);
+    queue.add(3L);
+    Set<Float> set = new TreeSet<>();
+    set.add(0.1F);
+    set.add(0.2F);
+    set.add(0.3F);
+    set.add(0.4F);
+    SortedSet<Character> sortedSet = new TreeSet<>();
+    sortedSet.add('a');
+    sortedSet.add('b');
+    sortedSet.add('c');
+    sortedSet.add('d');
+    ClassWithSubInterfacesOfCollection target =
+        new ClassWithSubInterfacesOfCollection(list, queue, set, sortedSet);
+    assertEquals(target.getExpectedJson(), gson.toJson(target));
+  }
+
+  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],"
+        + "\"sortedSet\":[\"a\",\"b\",\"c\",\"d\"]"
+        + "}";
+    ClassWithSubInterfacesOfCollection target = 
+      gson.fromJson(json, ClassWithSubInterfacesOfCollection.class);
+    assertTrue(target.listContains(0, 1, 2, 3));
+    assertTrue(target.queueContains(0, 1, 2, 3));
+    assertTrue(target.setContains(0.1F, 0.2F, 0.3F, 0.4F));
+    assertTrue(target.sortedSetContains('a', 'b', 'c', 'd'));
+  }
+  
+  private static class ClassWithSubInterfacesOfCollection {
+    private List<Integer> list;
+    private Queue<Long> queue;
+    private Set<Float> set;
+    private SortedSet<Character> sortedSet;
+
+    public ClassWithSubInterfacesOfCollection(List<Integer> list, Queue<Long> queue, Set<Float> set,
+        SortedSet<Character> sortedSet) {
+      this.list = list;
+      this.queue = queue;
+      this.set = set;
+      this.sortedSet = sortedSet;
+    }
+
+    boolean listContains(int... values) {
+      for (int value : values) {
+        if (!list.contains(value)) {
+          return false;
+        }
+      }
+      return true;
+    }
+    
+    boolean queueContains(long... values) {
+      for (long value : values) {
+        if (!queue.contains(value)) {
+          return false;
+        }
+      }
+      return true;
+    }
+    
+    boolean setContains(float... values) {
+      for (float value : values) {
+        if (!set.contains(value)) {
+          return false;
+        }
+      }
+      return true;
+    }
+
+    boolean sortedSetContains(char... values) {
+      for (char value : values) {
+        if (!sortedSet.contains(value)) {
+          return false;
+        }
+      }
+      return true;
+    }
+    
+    public String getExpectedJson() {
+      StringBuilder sb = new StringBuilder();
+      sb.append("{");
+      sb.append("\"list\":");
+      append(sb, list).append(",");
+      sb.append("\"queue\":");
+      append(sb, queue).append(",");
+      sb.append("\"set\":");
+      append(sb, set).append(",");
+      sb.append("\"sortedSet\":");
+      append(sb, sortedSet);
+      sb.append("}");
+      return sb.toString();
+    }
+
+    private StringBuilder append(StringBuilder sb, Collection<?> c) {
+      sb.append("[");
+      boolean first = true;
+      for (Object o : c) {
+        if (!first) {
+          sb.append(",");
+        } else {
+          first = false;
+        }
+        if (o instanceof String || o instanceof Character) {
+          sb.append('\"');
+        }
+        sb.append(o.toString());
+        if (o instanceof String || o instanceof Character) {
+          sb.append('\"');
+        }
+      }
+      sb.append("]");
+      return sb;
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/InstanceCreatorTest.java b/gson/src/test/java/com/google/gson/functional/InstanceCreatorTest.java
new file mode 100644
index 0000000..95e3e3e
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/InstanceCreatorTest.java
@@ -0,0 +1,127 @@
+/*
+ * Copyright (C) 2009 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.functional;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.InstanceCreator;
+import com.google.gson.common.TestTypes.Base;
+import com.google.gson.common.TestTypes.ClassWithBaseField;
+import com.google.gson.common.TestTypes.Sub;
+
+import com.google.gson.reflect.TypeToken;
+import java.util.ArrayList;
+import java.util.List;
+import junit.framework.TestCase;
+
+import java.lang.reflect.Type;
+import java.util.SortedSet;
+import java.util.TreeSet;
+
+/**
+ * Functional Test exercising custom serialization only. When test applies to both
+ * serialization and deserialization then add it to CustomTypeAdapterTest.
+ *
+ * @author Inderjeet Singh
+ */
+public class InstanceCreatorTest extends TestCase {
+
+  public void testInstanceCreatorReturnsBaseType() {
+    Gson gson = new GsonBuilder()
+      .registerTypeAdapter(Base.class, new InstanceCreator<Base>() {
+        @Override public Base createInstance(Type type) {
+         return new Base();
+       }
+      })
+      .create();
+    String json = "{baseName:'BaseRevised',subName:'Sub'}";
+    Base base = gson.fromJson(json, Base.class);
+    assertEquals("BaseRevised", base.baseName);
+  }
+
+  public void testInstanceCreatorReturnsSubTypeForTopLevelObject() {
+    Gson gson = new GsonBuilder()
+    .registerTypeAdapter(Base.class, new InstanceCreator<Base>() {
+      @Override public Base createInstance(Type type) {
+        return new Sub();
+      }
+    })
+    .create();
+
+    String json = "{baseName:'Base',subName:'SubRevised'}";
+    Base base = gson.fromJson(json, Base.class);
+    assertTrue(base instanceof Sub);
+
+    Sub sub = (Sub) base;
+    assertFalse("SubRevised".equals(sub.subName));
+    assertEquals(Sub.SUB_NAME, sub.subName);
+  }
+
+  public void testInstanceCreatorReturnsSubTypeForField() {
+    Gson gson = new GsonBuilder()
+    .registerTypeAdapter(Base.class, new InstanceCreator<Base>() {
+      @Override public Base createInstance(Type type) {
+        return new Sub();
+      }
+    })
+    .create();
+    String json = "{base:{baseName:'Base',subName:'SubRevised'}}";
+    ClassWithBaseField target = gson.fromJson(json, ClassWithBaseField.class);
+    assertTrue(target.base instanceof Sub);
+    assertEquals(Sub.SUB_NAME, ((Sub)target.base).subName);
+  }
+
+  // This regressed in Gson 2.0 and 2.1
+  public void testInstanceCreatorForCollectionType() {
+    @SuppressWarnings("serial")
+    class SubArrayList<T> extends ArrayList<T> {}
+    InstanceCreator<List<String>> listCreator = new InstanceCreator<List<String>>() {
+      @Override public List<String> createInstance(Type type) {
+        return new SubArrayList<>();
+      }
+    };
+    Type listOfStringType = new TypeToken<List<String>>() {}.getType();
+    Gson gson = new GsonBuilder()
+        .registerTypeAdapter(listOfStringType, listCreator)
+        .create();
+    List<String> list = gson.fromJson("[\"a\"]", listOfStringType);
+    assertEquals(SubArrayList.class, list.getClass());
+  }
+
+  @SuppressWarnings({ "unchecked", "rawtypes" })
+  public void testInstanceCreatorForParametrizedType() throws Exception {
+    @SuppressWarnings("serial")
+    class SubTreeSet<T> extends TreeSet<T> {}
+    InstanceCreator<SortedSet> sortedSetCreator = new InstanceCreator<SortedSet>() {
+      @Override public SortedSet createInstance(Type type) {
+        return new SubTreeSet();
+      }
+    };
+    Gson gson = new GsonBuilder()
+        .registerTypeAdapter(SortedSet.class, sortedSetCreator)
+        .create();
+
+    Type sortedSetType = new TypeToken<SortedSet<String>>() {}.getType();
+    SortedSet<String> set = gson.fromJson("[\"a\"]", sortedSetType);
+    assertEquals(set.first(), "a");
+    assertEquals(SubTreeSet.class, set.getClass());
+
+    set = gson.fromJson("[\"b\"]", SortedSet.class);
+    assertEquals(set.first(), "b");
+    assertEquals(SubTreeSet.class, set.getClass());
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/InterfaceTest.java b/gson/src/test/java/com/google/gson/functional/InterfaceTest.java
new file mode 100644
index 0000000..6851f1e
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/InterfaceTest.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.functional;
+
+import com.google.gson.Gson;
+
+import junit.framework.TestCase;
+
+/**
+ * Functional tests involving interfaces.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public class InterfaceTest extends TestCase {
+  private static final String OBJ_JSON = "{\"someStringValue\":\"StringValue\"}";
+
+  private Gson gson;
+  private TestObject obj;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    gson = new Gson();
+    obj = new TestObject("StringValue");
+  }
+
+  public void testSerializingObjectImplementingInterface() throws Exception {
+    assertEquals(OBJ_JSON, gson.toJson(obj));
+  }
+  
+  public void testSerializingInterfaceObjectField() throws Exception {
+    TestObjectWrapper objWrapper = new TestObjectWrapper(obj);
+    assertEquals("{\"obj\":" + OBJ_JSON + "}", gson.toJson(objWrapper));
+  }
+
+  private static interface TestObjectInterface {
+    // Holder
+  }
+  
+  private static class TestObject implements TestObjectInterface {
+    @SuppressWarnings("unused")
+    private String someStringValue;
+    
+    private TestObject(String value) {
+      this.someStringValue = value;
+    }
+  }
+
+  private static class TestObjectWrapper {
+    @SuppressWarnings("unused")
+    private TestObjectInterface obj;
+    
+    private TestObjectWrapper(TestObjectInterface obj) {
+      this.obj = obj;
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/InternationalizationTest.java b/gson/src/test/java/com/google/gson/functional/InternationalizationTest.java
new file mode 100644
index 0000000..169c37a
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/InternationalizationTest.java
@@ -0,0 +1,71 @@
+/*

+ * Copyright (C) 2008 Google Inc.

+ *

+ * Licensed under the Apache License, Version 2.0 (the "License");

+ * you may not use this file except in compliance with the License.

+ * You may obtain a copy of the License at

+ *

+ * http://www.apache.org/licenses/LICENSE-2.0

+ *

+ * Unless required by applicable law or agreed to in writing, software

+ * distributed under the License is distributed on an "AS IS" BASIS,

+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

+ * See the License for the specific language governing permissions and

+ * limitations under the License.

+ */

+

+package com.google.gson.functional;

+

+import com.google.gson.Gson;

+

+import junit.framework.TestCase;

+

+/**

+ * Functional tests for internationalized strings.

+ *

+ * @author Inderjeet Singh

+ */

+public class InternationalizationTest extends TestCase {

+  private Gson gson;

+

+  @Override

+  protected void setUp() throws Exception {

+    super.setUp();

+    gson = new Gson();

+  }

+

+  /*

+  public void testStringsWithRawChineseCharactersSerialization() throws Exception {

+    String target = "好好好";

+    String json = gson.toJson(target);

+    String expected = "\"\\u597d\\u597d\\u597d\"";

+    assertEquals(expected, json);

+  }

+  */

+

+  public void testStringsWithRawChineseCharactersDeserialization() throws Exception {

+    String expected = "好好好";

+    String json = "\"" + expected + "\"";

+    String actual = gson.fromJson(json, String.class);

+    assertEquals(expected, actual);

+  }

+

+  public void testStringsWithUnicodeChineseCharactersSerialization() throws Exception {

+    String target = "\u597d\u597d\u597d";

+    String json = gson.toJson(target);

+    String expected = "\"\u597d\u597d\u597d\"";

+    assertEquals(expected, json);

+  }

+

+  public void testStringsWithUnicodeChineseCharactersDeserialization() throws Exception {

+    String expected = "\u597d\u597d\u597d";

+    String json = "\"" + expected + "\"";

+    String actual = gson.fromJson(json, String.class);

+    assertEquals(expected, actual);

+  }

+

+  public void testStringsWithUnicodeChineseCharactersEscapedDeserialization() throws Exception {

+    String actual = gson.fromJson("'\\u597d\\u597d\\u597d'", String.class);

+    assertEquals("\u597d\u597d\u597d", actual);

+  }

+}

diff --git a/gson/src/test/java/com/google/gson/functional/JavaUtilConcurrentAtomicTest.java b/gson/src/test/java/com/google/gson/functional/JavaUtilConcurrentAtomicTest.java
new file mode 100644
index 0000000..464892a
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/JavaUtilConcurrentAtomicTest.java
@@ -0,0 +1,110 @@
+/*
+ * Copyright (C) 2015 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.functional;
+
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicIntegerArray;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicLongArray;
+
+import com.google.gson.Gson;
+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
+ */
+public class JavaUtilConcurrentAtomicTest extends TestCase {
+  private Gson gson;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    gson = new Gson();
+  }
+
+  public void testAtomicBoolean() throws Exception {
+    AtomicBoolean target = gson.fromJson("true", AtomicBoolean.class);
+    assertTrue(target.get());
+    String json = gson.toJson(target);
+    assertEquals("true", json);
+  }
+
+  public void testAtomicInteger() throws Exception {
+    AtomicInteger target = gson.fromJson("10", AtomicInteger.class);
+    assertEquals(10, target.get());
+    String json = gson.toJson(target);
+    assertEquals("10", json);
+  }
+
+  public void testAtomicLong() throws Exception {
+    AtomicLong target = gson.fromJson("10", AtomicLong.class);
+    assertEquals(10, target.get());
+    String json = gson.toJson(target);
+    assertEquals("10", json);
+  }
+
+  public void testAtomicLongWithStringSerializationPolicy() throws Exception {
+    Gson gson = new GsonBuilder()
+        .setLongSerializationPolicy(LongSerializationPolicy.STRING)
+        .create();
+    AtomicLongHolder target = gson.fromJson("{'value':'10'}", AtomicLongHolder.class);
+    assertEquals(10, target.value.get());
+    String json = gson.toJson(target);
+    assertEquals("{\"value\":\"10\"}", json);
+  }
+
+  public void testAtomicIntegerArray() throws Exception {
+    AtomicIntegerArray target = gson.fromJson("[10, 13, 14]", AtomicIntegerArray.class);
+    assertEquals(3, target.length());
+    assertEquals(10, target.get(0));
+    assertEquals(13, target.get(1));
+    assertEquals(14, target.get(2));
+    String json = gson.toJson(target);
+    assertEquals("[10,13,14]", json);
+  }
+
+  public void testAtomicLongArray() throws Exception {
+    AtomicLongArray target = gson.fromJson("[10, 13, 14]", AtomicLongArray.class);
+    assertEquals(3, target.length());
+    assertEquals(10, target.get(0));
+    assertEquals(13, target.get(1));
+    assertEquals(14, target.get(2));
+    String json = gson.toJson(target);
+    assertEquals("[10,13,14]", json);
+  }
+
+  public void testAtomicLongArrayWithStringSerializationPolicy() throws Exception {
+    Gson gson = new GsonBuilder()
+        .setLongSerializationPolicy(LongSerializationPolicy.STRING)
+        .create();
+    AtomicLongArray target = gson.fromJson("['10', '13', '14']", AtomicLongArray.class);
+    assertEquals(3, target.length());
+    assertEquals(10, target.get(0));
+    assertEquals(13, target.get(1));
+    assertEquals(14, target.get(2));
+    String json = gson.toJson(target);
+    assertEquals("[\"10\",\"13\",\"14\"]", json);
+  }
+
+  private static class AtomicLongHolder {
+    AtomicLong value;
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/JavaUtilTest.java b/gson/src/test/java/com/google/gson/functional/JavaUtilTest.java
new file mode 100644
index 0000000..0520965
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/JavaUtilTest.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2015 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.functional;
+
+import java.util.Currency;
+import java.util.Properties;
+
+import com.google.gson.Gson;
+
+import junit.framework.TestCase;
+
+/**
+ * Functional test for Json serialization and deserialization for classes in java.util
+ */
+public class JavaUtilTest extends TestCase {
+  private Gson gson;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    gson = new Gson();
+  }
+
+  public void testCurrency() throws Exception {
+    CurrencyHolder target = gson.fromJson("{'value':'USD'}", CurrencyHolder.class);
+    assertEquals("USD", target.value.getCurrencyCode());
+    String json = gson.toJson(target);
+    assertEquals("{\"value\":\"USD\"}", json);
+
+    // null handling
+    target = gson.fromJson("{'value':null}", CurrencyHolder.class);
+    assertNull(target.value);
+    assertEquals("{}", gson.toJson(target));
+  }
+
+  private static class CurrencyHolder {
+    Currency value;
+  }
+
+  public void testProperties() {
+    Properties props = gson.fromJson("{'a':'v1','b':'v2'}", Properties.class);
+    assertEquals("v1", props.getProperty("a"));
+    assertEquals("v2", props.getProperty("b"));
+    String json = gson.toJson(props);
+    assertTrue(json.contains("\"a\":\"v1\""));
+    assertTrue(json.contains("\"b\":\"v2\""));
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnClassesTest.java b/gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnClassesTest.java
new file mode 100644
index 0000000..db939dc
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnClassesTest.java
@@ -0,0 +1,263 @@
+/*
+ * Copyright (C) 2014 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.functional;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonDeserializationContext;
+import com.google.gson.JsonDeserializer;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonParseException;
+import com.google.gson.JsonPrimitive;
+import com.google.gson.JsonSerializationContext;
+import com.google.gson.JsonSerializer;
+import com.google.gson.TypeAdapter;
+import com.google.gson.TypeAdapterFactory;
+import com.google.gson.annotations.JsonAdapter;
+import com.google.gson.reflect.TypeToken;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
+import java.lang.reflect.Type;
+import java.util.Locale;
+import junit.framework.TestCase;
+
+/**
+ * Functional tests for the {@link com.google.gson.annotations.JsonAdapter} annotation on classes.
+ */
+public final class JsonAdapterAnnotationOnClassesTest extends TestCase {
+
+  public void testJsonAdapterInvoked() {
+    Gson gson = new Gson();
+    String json = gson.toJson(new A("bar"));
+    assertEquals("\"jsonAdapter\"", json);
+
+   // Also invoke the JsonAdapter javadoc sample
+    json = gson.toJson(new User("Inderjeet", "Singh"));
+    assertEquals("{\"name\":\"Inderjeet Singh\"}", json);
+    User user = gson.fromJson("{'name':'Joel Leitch'}", User.class);
+    assertEquals("Joel", user.firstName);
+    assertEquals("Leitch", user.lastName);
+
+    json = gson.toJson(Foo.BAR);
+    assertEquals("\"bar\"", json);
+    Foo baz = gson.fromJson("\"baz\"", Foo.class);
+    assertEquals(Foo.BAZ, baz);
+  }
+
+  public void testJsonAdapterFactoryInvoked() {
+    Gson gson = new Gson();
+    String json = gson.toJson(new C("bar"));
+    assertEquals("\"jsonAdapterFactory\"", json);
+    C c = gson.fromJson("\"bar\"", C.class);
+    assertEquals("jsonAdapterFactory", c.value);
+  }
+
+  public void testRegisteredAdapterOverridesJsonAdapter() {
+    TypeAdapter<A> typeAdapter = new TypeAdapter<A>() {
+      @Override public void write(JsonWriter out, A value) throws IOException {
+        out.value("registeredAdapter");
+      }
+      @Override public A read(JsonReader in) throws IOException {
+        return new A(in.nextString());
+      }
+    };
+    Gson gson = new GsonBuilder()
+      .registerTypeAdapter(A.class, typeAdapter)
+      .create();
+    String json = gson.toJson(new A("abcd"));
+    assertEquals("\"registeredAdapter\"", json);
+  }
+
+  /**
+   * The serializer overrides field adapter, but for deserializer the fieldAdapter is used.
+   */
+  public void testRegisteredSerializerOverridesJsonAdapter() {
+    JsonSerializer<A> serializer = new JsonSerializer<A>() {
+      @Override public JsonElement serialize(A src, Type typeOfSrc,
+          JsonSerializationContext context) {
+        return new JsonPrimitive("registeredSerializer");
+      }
+    };
+    Gson gson = new GsonBuilder()
+      .registerTypeAdapter(A.class, serializer)
+      .create();
+    String json = gson.toJson(new A("abcd"));
+    assertEquals("\"registeredSerializer\"", json);
+    A target = gson.fromJson("abcd", A.class);
+    assertEquals("jsonAdapter", target.value);
+  }
+
+  /**
+   * The deserializer overrides Json adapter, but for serializer the jsonAdapter is used.
+   */
+  public void testRegisteredDeserializerOverridesJsonAdapter() {
+    JsonDeserializer<A> deserializer = new JsonDeserializer<A>() {
+      @Override public A deserialize(JsonElement json, Type typeOfT,
+          JsonDeserializationContext context) throws JsonParseException {
+        return new A("registeredDeserializer");
+      }
+    };
+    Gson gson = new GsonBuilder()
+      .registerTypeAdapter(A.class, deserializer)
+      .create();
+    String json = gson.toJson(new A("abcd"));
+    assertEquals("\"jsonAdapter\"", json);
+    A target = gson.fromJson("abcd", A.class);
+    assertEquals("registeredDeserializer", target.value);
+  }
+
+  public void testIncorrectTypeAdapterFails() {
+    try {
+      String json = new Gson().toJson(new ClassWithIncorrectJsonAdapter("bar"));
+      fail(json);
+    } catch (ClassCastException expected) {}
+  }
+
+  public void testSuperclassTypeAdapterNotInvoked() {
+    String json = new Gson().toJson(new B("bar"));
+    assertFalse(json.contains("jsonAdapter"));
+  }
+
+  public void testNullSafeObjectFromJson() {
+    Gson gson = new Gson();
+    NullableClass fromJson = gson.fromJson("null", NullableClass.class);
+    assertNull(fromJson);
+  }
+
+  @JsonAdapter(A.JsonAdapter.class)
+  private static class A {
+    final String value;
+    A(String value) {
+      this.value = value;
+    }
+    static final class JsonAdapter extends TypeAdapter<A> {
+      @Override public void write(JsonWriter out, A value) throws IOException {
+        out.value("jsonAdapter");
+      }
+      @Override public A read(JsonReader in) throws IOException {
+        in.nextString();
+        return new A("jsonAdapter");
+      }
+    }
+  }
+
+  @JsonAdapter(C.JsonAdapterFactory.class)
+  private static class C {
+    final String value;
+    C(String value) {
+      this.value = value;
+    }
+    static final class JsonAdapterFactory implements TypeAdapterFactory {
+      @Override public <T> TypeAdapter<T> create(Gson gson, final TypeToken<T> type) {
+        return new TypeAdapter<T>() {
+          @Override public void write(JsonWriter out, T value) throws IOException {
+            out.value("jsonAdapterFactory");
+          }
+          @SuppressWarnings("unchecked")
+          @Override public T read(JsonReader in) throws IOException {
+            in.nextString();
+            return (T) new C("jsonAdapterFactory");
+          }
+        };
+      }
+    }
+  }
+
+  private static final class B extends A {
+    B(String value) {
+      super(value);
+    }
+  }
+  // Note that the type is NOT TypeAdapter<ClassWithIncorrectJsonAdapter> so this
+  // should cause error
+  @JsonAdapter(A.JsonAdapter.class)
+  private static final class ClassWithIncorrectJsonAdapter {
+    @SuppressWarnings("unused") final String value;
+    ClassWithIncorrectJsonAdapter(String value) {
+      this.value = value;
+    }
+  }
+
+  // This class is used in JsonAdapter Javadoc as an example
+  @JsonAdapter(UserJsonAdapter.class)
+  private static class User {
+    final String firstName, lastName;
+    User(String firstName, String lastName) {
+      this.firstName = firstName;
+      this.lastName = lastName;
+    }
+  }
+  private static class UserJsonAdapter extends TypeAdapter<User> {
+    @Override public void write(JsonWriter out, User user) throws IOException {
+      // implement write: combine firstName and lastName into name
+      out.beginObject();
+      out.name("name");
+      out.value(user.firstName + " " + user.lastName);
+      out.endObject();
+      // implement the write method
+    }
+    @Override public User read(JsonReader in) throws IOException {
+      // implement read: split name into firstName and lastName
+      in.beginObject();
+      in.nextName();
+      String[] nameParts = in.nextString().split(" ");
+      in.endObject();
+      return new User(nameParts[0], nameParts[1]);
+    }
+  }
+
+  @JsonAdapter(value = NullableClassJsonAdapter.class)
+  private static class NullableClass {
+  }
+
+  private static class NullableClassJsonAdapter extends TypeAdapter<NullableClass> {
+    @Override
+    public void write(JsonWriter out, NullableClass value) throws IOException {
+      out.value("nullable");
+    }
+
+    @Override
+    public NullableClass read(JsonReader in) throws IOException {
+      in.nextString();
+      return new NullableClass();
+    }
+  }
+
+  @JsonAdapter(FooJsonAdapter.class)
+  private static enum Foo { BAR, BAZ }
+  private static class FooJsonAdapter extends TypeAdapter<Foo> {
+    @Override public void write(JsonWriter out, Foo value) throws IOException {
+      out.value(value.name().toLowerCase(Locale.US));
+    }
+
+    @Override public Foo read(JsonReader in) throws IOException {
+      return Foo.valueOf(in.nextString().toUpperCase(Locale.US));
+    }
+  }
+
+  public void testIncorrectJsonAdapterType() {
+    try {
+      new Gson().toJson(new D());
+      fail();
+    } catch (IllegalArgumentException expected) {}
+  }
+  @JsonAdapter(Integer.class)
+  private static final class D {
+    @SuppressWarnings("unused") final String value = "a";
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnFieldsTest.java b/gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnFieldsTest.java
new file mode 100644
index 0000000..706fe60
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnFieldsTest.java
@@ -0,0 +1,306 @@
+/*
+ * Copyright (C) 2014 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.functional;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.List;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.TypeAdapter;
+import com.google.gson.TypeAdapterFactory;
+import com.google.gson.annotations.JsonAdapter;
+import com.google.gson.reflect.TypeToken;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonWriter;
+
+import junit.framework.TestCase;
+
+/**
+ * Functional tests for the {@link com.google.gson.annotations.JsonAdapter} annotation on fields.
+ */
+public final class JsonAdapterAnnotationOnFieldsTest extends TestCase {
+  public void testClassAnnotationAdapterTakesPrecedenceOverDefault() {
+    Gson gson = new Gson();
+    String json = gson.toJson(new Computer(new User("Inderjeet Singh")));
+    assertEquals("{\"user\":\"UserClassAnnotationAdapter\"}", json);
+    Computer computer = gson.fromJson("{'user':'Inderjeet Singh'}", Computer.class);
+    assertEquals("UserClassAnnotationAdapter", computer.user.name);
+  }
+
+  public void testClassAnnotationAdapterFactoryTakesPrecedenceOverDefault() {
+    Gson gson = new Gson();
+    String json = gson.toJson(new Gizmo(new Part("Part")));
+    assertEquals("{\"part\":\"GizmoPartTypeAdapterFactory\"}", json);
+    Gizmo computer = gson.fromJson("{'part':'Part'}", Gizmo.class);
+    assertEquals("GizmoPartTypeAdapterFactory", computer.part.name);
+  }
+
+  public void testRegisteredTypeAdapterTakesPrecedenceOverClassAnnotationAdapter() {
+    Gson gson = new GsonBuilder()
+        .registerTypeAdapter(User.class, new RegisteredUserAdapter())
+        .create();
+    String json = gson.toJson(new Computer(new User("Inderjeet Singh")));
+    assertEquals("{\"user\":\"RegisteredUserAdapter\"}", json);
+    Computer computer = gson.fromJson("{'user':'Inderjeet Singh'}", Computer.class);
+    assertEquals("RegisteredUserAdapter", computer.user.name);
+  }
+
+  public void testFieldAnnotationTakesPrecedenceOverRegisteredTypeAdapter() {
+    Gson gson = new GsonBuilder()
+      .registerTypeAdapter(Part.class, new TypeAdapter<Part>() {
+        @Override public void write(JsonWriter out, Part part) throws IOException {
+          throw new AssertionError();
+        }
+        @Override public Part read(JsonReader in) throws IOException {
+          throw new AssertionError();
+        }
+      }).create();
+    String json = gson.toJson(new Gadget(new Part("screen")));
+    assertEquals("{\"part\":\"PartJsonFieldAnnotationAdapter\"}", json);
+    Gadget gadget = gson.fromJson("{'part':'screen'}", Gadget.class);
+    assertEquals("PartJsonFieldAnnotationAdapter", gadget.part.name);
+  }
+
+  public void testFieldAnnotationTakesPrecedenceOverClassAnnotation() {
+    Gson gson = new Gson();
+    String json = gson.toJson(new Computer2(new User("Inderjeet Singh")));
+    assertEquals("{\"user\":\"UserFieldAnnotationAdapter\"}", json);
+    Computer2 target = gson.fromJson("{'user':'Interjeet Singh'}", Computer2.class);
+    assertEquals("UserFieldAnnotationAdapter", target.user.name);
+  }
+
+  private static final class Gadget {
+    @JsonAdapter(PartJsonFieldAnnotationAdapter.class)
+    final Part part;
+    Gadget(Part part) {
+      this.part = part;
+    }
+  }
+
+  private static final class Gizmo {
+    @JsonAdapter(GizmoPartTypeAdapterFactory.class)
+    final Part part;
+    Gizmo(Part part) {
+      this.part = part;
+    }
+  }
+
+  private static final class Part {
+    final String name;
+    public Part(String name) {
+      this.name = name;
+    }
+  }
+
+  private static class PartJsonFieldAnnotationAdapter extends TypeAdapter<Part> {
+    @Override public void write(JsonWriter out, Part part) throws IOException {
+      out.value("PartJsonFieldAnnotationAdapter");
+    }
+    @Override public Part read(JsonReader in) throws IOException {
+      in.nextString();
+      return new Part("PartJsonFieldAnnotationAdapter");
+    }
+  }
+
+  private static class GizmoPartTypeAdapterFactory implements TypeAdapterFactory {
+    @Override public <T> TypeAdapter<T> create(Gson gson, final TypeToken<T> type) {
+      return new TypeAdapter<T>() {
+        @Override public void write(JsonWriter out, T value) throws IOException {
+          out.value("GizmoPartTypeAdapterFactory");
+        }
+        @SuppressWarnings("unchecked")
+        @Override public T read(JsonReader in) throws IOException {
+          in.nextString();
+          return (T) new Part("GizmoPartTypeAdapterFactory");
+        }
+      };
+    }
+  }
+
+  private static final class Computer {
+    final User user;
+    Computer(User user) {
+      this.user = user;
+    }
+  }
+
+  @JsonAdapter(UserClassAnnotationAdapter.class)
+  private static class User {
+    public final String name;
+    private User(String name) {
+      this.name = name;
+    }
+  }
+
+  private static class UserClassAnnotationAdapter extends TypeAdapter<User> {
+    @Override public void write(JsonWriter out, User user) throws IOException {
+      out.value("UserClassAnnotationAdapter");
+    }
+    @Override public User read(JsonReader in) throws IOException {
+      in.nextString();
+      return new User("UserClassAnnotationAdapter");
+    }
+  }
+
+  private static final class Computer2 {
+    // overrides the JsonAdapter annotation of User with this
+    @JsonAdapter(UserFieldAnnotationAdapter.class)
+    final User user;
+    Computer2(User user) {
+      this.user = user;
+    }
+  }
+
+  private static final class UserFieldAnnotationAdapter extends TypeAdapter<User> {
+    @Override public void write(JsonWriter out, User user) throws IOException {
+      out.value("UserFieldAnnotationAdapter");
+    }
+    @Override public User read(JsonReader in) throws IOException {
+      in.nextString();
+      return new User("UserFieldAnnotationAdapter");
+    }
+  }
+
+  private static final class RegisteredUserAdapter extends TypeAdapter<User> {
+    @Override public void write(JsonWriter out, User user) throws IOException {
+      out.value("RegisteredUserAdapter");
+    }
+    @Override public User read(JsonReader in) throws IOException {
+      in.nextString();
+      return new User("RegisteredUserAdapter");
+    }
+  }
+
+  public void testJsonAdapterInvokedOnlyForAnnotatedFields() {
+    Gson gson = new Gson();
+    String json = "{'part1':'name','part2':{'name':'name2'}}";
+    GadgetWithTwoParts gadget = gson.fromJson(json, GadgetWithTwoParts.class);
+    assertEquals("PartJsonFieldAnnotationAdapter", gadget.part1.name);
+    assertEquals("name2", gadget.part2.name);
+  }
+
+  private static final class GadgetWithTwoParts {
+    @JsonAdapter(PartJsonFieldAnnotationAdapter.class) final Part part1;
+    final Part part2; // Doesn't have the JsonAdapter annotation
+    @SuppressWarnings("unused") GadgetWithTwoParts(Part part1, Part part2) {
+      this.part1 = part1;
+      this.part2 = part2;
+    }
+  }
+
+  public void testJsonAdapterWrappedInNullSafeAsRequested() {
+    Gson gson = new Gson();
+    String fromJson = "{'part':null}";
+
+    GadgetWithOptionalPart gadget = gson.fromJson(fromJson, GadgetWithOptionalPart.class);
+    assertNull(gadget.part);
+
+    String toJson = gson.toJson(gadget);
+    assertFalse(toJson.contains("PartJsonFieldAnnotationAdapter"));
+  }
+
+  private static final class GadgetWithOptionalPart {
+    @JsonAdapter(value = PartJsonFieldAnnotationAdapter.class)
+    final Part part;
+
+    private GadgetWithOptionalPart(Part part) {
+      this.part = part;
+    }
+  }
+
+  /** Regression test contributed through https://github.com/google/gson/issues/831 */
+  public void testNonPrimitiveFieldAnnotationTakesPrecedenceOverDefault() {
+    Gson gson = new Gson();
+    String json = gson.toJson(new GadgetWithOptionalPart(new Part("foo")));
+    assertEquals("{\"part\":\"PartJsonFieldAnnotationAdapter\"}", json);
+    GadgetWithOptionalPart gadget = gson.fromJson("{'part':'foo'}", GadgetWithOptionalPart.class);
+    assertEquals("PartJsonFieldAnnotationAdapter", gadget.part.name);
+  }
+
+  /** Regression test contributed through https://github.com/google/gson/issues/831 */
+  public void testPrimitiveFieldAnnotationTakesPrecedenceOverDefault() {
+    Gson gson = new Gson();
+    String json = gson.toJson(new GadgetWithPrimitivePart(42));
+    assertEquals("{\"part\":\"42\"}", json);
+    GadgetWithPrimitivePart gadget = gson.fromJson(json, GadgetWithPrimitivePart.class);
+    assertEquals(42, gadget.part);
+  }
+
+  private static final class GadgetWithPrimitivePart {
+    @JsonAdapter(LongToStringTypeAdapterFactory.class)
+    final long part;
+
+    private GadgetWithPrimitivePart(long part) {
+      this.part = part;
+    }
+  }
+
+  private static final class LongToStringTypeAdapterFactory implements TypeAdapterFactory {
+    static final TypeAdapter<Long> ADAPTER = new TypeAdapter<Long>() {
+      @Override public void write(JsonWriter out, Long value) throws IOException {
+        out.value(value.toString());
+      }
+      @Override public Long read(JsonReader in) throws IOException {
+        return in.nextLong();
+      }
+    };
+    @SuppressWarnings("unchecked")
+    @Override public <T> TypeAdapter<T> create(Gson gson, final TypeToken<T> type) {
+      Class<?> cls = type.getRawType();
+      if (Long.class.isAssignableFrom(cls)) {
+        return (TypeAdapter<T>) ADAPTER;
+      } else if (long.class.isAssignableFrom(cls)) {
+        return (TypeAdapter<T>) ADAPTER;
+      }
+      throw new IllegalStateException("Non-long field of type " + type
+          + " annotated with @JsonAdapter(LongToStringTypeAdapterFactory.class)");
+    }
+  }
+
+  public void testFieldAnnotationWorksForParameterizedType() {
+    Gson gson = new Gson();
+    String json = gson.toJson(new Gizmo2(Arrays.asList(new Part("Part"))));
+    assertEquals("{\"part\":\"GizmoPartTypeAdapterFactory\"}", json);
+    Gizmo2 computer = gson.fromJson("{'part':'Part'}", Gizmo2.class);
+    assertEquals("GizmoPartTypeAdapterFactory", computer.part.get(0).name);
+  }
+
+  private static final class Gizmo2 {
+    @JsonAdapter(Gizmo2PartTypeAdapterFactory.class)
+    List<Part> part;
+    Gizmo2(List<Part> part) {
+      this.part = part;
+    }
+  }
+
+  private static class Gizmo2PartTypeAdapterFactory implements TypeAdapterFactory {
+    @Override public <T> TypeAdapter<T> create(Gson gson, final TypeToken<T> type) {
+      return new TypeAdapter<T>() {
+        @Override public void write(JsonWriter out, T value) throws IOException {
+          out.value("GizmoPartTypeAdapterFactory");
+        }
+        @SuppressWarnings("unchecked")
+        @Override public T read(JsonReader in) throws IOException {
+          in.nextString();
+          return (T) Arrays.asList(new Part("GizmoPartTypeAdapterFactory"));
+        }
+      };
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/JsonAdapterSerializerDeserializerTest.java b/gson/src/test/java/com/google/gson/functional/JsonAdapterSerializerDeserializerTest.java
new file mode 100644
index 0000000..e6cb6dc
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/JsonAdapterSerializerDeserializerTest.java
@@ -0,0 +1,164 @@
+/*
+ * Copyright (C) 2016 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.functional;
+
+import java.lang.reflect.Type;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonDeserializationContext;
+import com.google.gson.JsonDeserializer;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonParseException;
+import com.google.gson.JsonPrimitive;
+import com.google.gson.JsonSerializationContext;
+import com.google.gson.JsonSerializer;
+import com.google.gson.annotations.JsonAdapter;
+
+import junit.framework.TestCase;
+
+/**
+ * Functional tests for the {@link JsonAdapter} annotation on fields where the value is of
+ * type {@link JsonSerializer} or {@link JsonDeserializer}.
+ */
+public final class JsonAdapterSerializerDeserializerTest extends TestCase {
+
+  public void testJsonSerializerDeserializerBasedJsonAdapterOnFields() {
+    Gson gson = new Gson();
+    String json = gson.toJson(new Computer(new User("Inderjeet Singh"), null, new User("Jesse Wilson")));
+    assertEquals("{\"user1\":\"UserSerializer\",\"user3\":\"UserSerializerDeserializer\"}", json);
+    Computer computer = gson.fromJson("{'user2':'Jesse Wilson','user3':'Jake Wharton'}", Computer.class);
+    assertEquals("UserSerializer", computer.user2.name);
+    assertEquals("UserSerializerDeserializer", computer.user3.name);
+  }
+
+  private static final class Computer {
+    @JsonAdapter(UserSerializer.class) final User user1;
+    @JsonAdapter(UserDeserializer.class) final User user2;
+    @JsonAdapter(UserSerializerDeserializer.class) final User user3;
+    Computer(User user1, User user2, User user3) {
+      this.user1 = user1;
+      this.user2 = user2;
+      this.user3 = user3;
+    }
+  }
+
+  private static final class User {
+    public final String name;
+    private User(String name) {
+      this.name = name;
+    }
+  }
+
+  private static final class UserSerializer implements JsonSerializer<User> {
+    @Override
+    public JsonElement serialize(User src, Type typeOfSrc, JsonSerializationContext context) {
+      return new JsonPrimitive("UserSerializer");
+    }
+  }
+
+  private static final class UserDeserializer implements JsonDeserializer<User> {
+    @Override
+    public User deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
+        throws JsonParseException {
+      return new User("UserSerializer");
+    }
+  }
+
+  private static final class UserSerializerDeserializer implements JsonSerializer<User>, JsonDeserializer<User> {
+    @Override
+    public JsonElement serialize(User src, Type typeOfSrc, JsonSerializationContext context) {
+      return new JsonPrimitive("UserSerializerDeserializer");
+    }
+    @Override
+    public User deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
+        throws JsonParseException {
+      return new User("UserSerializerDeserializer");
+    }
+  }
+
+  public void testJsonSerializerDeserializerBasedJsonAdapterOnClass() {
+    Gson gson = new Gson();
+    String json = gson.toJson(new Computer2(new User2("Inderjeet Singh")));
+    assertEquals("{\"user\":\"UserSerializerDeserializer2\"}", json);
+    Computer2 computer = gson.fromJson("{'user':'Inderjeet Singh'}", Computer2.class);
+    assertEquals("UserSerializerDeserializer2", computer.user.name);
+  }
+
+  private static final class Computer2 {
+    final User2 user;
+    Computer2(User2 user) {
+      this.user = user;
+    }
+  }
+
+  @JsonAdapter(UserSerializerDeserializer2.class)
+  private static final class User2 {
+    public final String name;
+    private User2(String name) {
+      this.name = name;
+    }
+  }
+
+  private static final class UserSerializerDeserializer2 implements JsonSerializer<User2>, JsonDeserializer<User2> {
+    @Override
+    public JsonElement serialize(User2 src, Type typeOfSrc, JsonSerializationContext context) {
+      return new JsonPrimitive("UserSerializerDeserializer2");
+    }
+    @Override
+    public User2 deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
+        throws JsonParseException {
+      return new User2("UserSerializerDeserializer2");
+    }
+  }
+
+  public void testDifferentJsonAdaptersForGenericFieldsOfSameRawType() {
+    Container c = new Container("Foo", 10);
+    Gson gson = new Gson();
+    String json = gson.toJson(c);
+    assertTrue(json.contains("\"a\":\"BaseStringAdapter\""));
+    assertTrue(json.contains("\"b\":\"BaseIntegerAdapter\""));
+  }
+
+  private static final class Container {
+    @JsonAdapter(BaseStringAdapter.class) Base<String> a;
+    @JsonAdapter(BaseIntegerAdapter.class) Base<Integer> b;
+    Container(String a, int b) {
+      this.a = new Base<>(a);
+      this.b = new Base<>(b);
+    }
+  }
+
+  private static final class Base<T> {
+    @SuppressWarnings("unused")
+    T value;
+    Base(T value) {
+      this.value = value;
+    }
+  }
+
+  private static final class BaseStringAdapter implements JsonSerializer<Base<String>> {
+    @Override public JsonElement serialize(Base<String> src, Type typeOfSrc, JsonSerializationContext context) {
+      return new JsonPrimitive("BaseStringAdapter");
+    }
+  }
+
+  private static final class BaseIntegerAdapter implements JsonSerializer<Base<Integer>> {
+    @Override public JsonElement serialize(Base<Integer> src, Type typeOfSrc, JsonSerializationContext context) {
+      return new JsonPrimitive("BaseIntegerAdapter");
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/JsonArrayTest.java b/gson/src/test/java/com/google/gson/functional/JsonArrayTest.java
new file mode 100644
index 0000000..22a479b
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/JsonArrayTest.java
@@ -0,0 +1,162 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.functional;
+
+import com.google.gson.JsonArray;
+import junit.framework.TestCase;
+
+import java.math.BigInteger;
+
+/**
+ * Functional tests for adding primitives to a JsonArray.
+ *
+ * @author Dillon Dixon
+ */
+public class JsonArrayTest extends TestCase {
+
+  public void testStringPrimitiveAddition() {
+    JsonArray jsonArray = new JsonArray();
+
+    jsonArray.add("Hello");
+    jsonArray.add("Goodbye");
+    jsonArray.add("Thank you");
+    jsonArray.add((String) null);
+    jsonArray.add("Yes");
+
+    assertEquals("[\"Hello\",\"Goodbye\",\"Thank you\",null,\"Yes\"]", jsonArray.toString());
+  }
+
+  public void testIntegerPrimitiveAddition() {
+    JsonArray jsonArray = new JsonArray();
+
+    int x = 1;
+    jsonArray.add(x);
+
+    x = 2;
+    jsonArray.add(x);
+
+    x = -3;
+    jsonArray.add(x);
+
+    jsonArray.add((Integer) null);
+
+    x = 4;
+    jsonArray.add(x);
+
+    x = 0;
+    jsonArray.add(x);
+
+    assertEquals("[1,2,-3,null,4,0]", jsonArray.toString());
+  }
+
+  public void testDoublePrimitiveAddition() {
+    JsonArray jsonArray = new JsonArray();
+
+    double x = 1.0;
+    jsonArray.add(x);
+
+    x = 2.13232;
+    jsonArray.add(x);
+
+    x = 0.121;
+    jsonArray.add(x);
+
+    jsonArray.add((Double) null);
+
+    x = -0.00234;
+    jsonArray.add(x);
+
+    jsonArray.add((Double) null);
+
+    assertEquals("[1.0,2.13232,0.121,null,-0.00234,null]", jsonArray.toString());
+  }
+
+  public void testBooleanPrimitiveAddition() {
+    JsonArray jsonArray = new JsonArray();
+
+    jsonArray.add(true);
+    jsonArray.add(true);
+    jsonArray.add(false);
+    jsonArray.add(false);
+    jsonArray.add((Boolean) null);
+    jsonArray.add(true);
+
+    assertEquals("[true,true,false,false,null,true]", jsonArray.toString());
+  }
+
+  public void testCharPrimitiveAddition() {
+    JsonArray jsonArray = new JsonArray();
+
+    jsonArray.add('a');
+    jsonArray.add('e');
+    jsonArray.add('i');
+    jsonArray.add((char) 111);
+    jsonArray.add((Character) null);
+    jsonArray.add('u');
+    jsonArray.add("and sometimes Y");
+
+    assertEquals("[\"a\",\"e\",\"i\",\"o\",null,\"u\",\"and sometimes Y\"]", jsonArray.toString());
+  }
+
+  public void testMixedPrimitiveAddition() {
+    JsonArray jsonArray = new JsonArray();
+
+    jsonArray.add('a');
+    jsonArray.add("apple");
+    jsonArray.add(12121);
+    jsonArray.add((char) 111);
+    jsonArray.add((Boolean) null);
+    jsonArray.add((Character) null);
+    jsonArray.add(12.232);
+    jsonArray.add(BigInteger.valueOf(2323));
+
+    assertEquals("[\"a\",\"apple\",12121,\"o\",null,null,12.232,2323]", jsonArray.toString());
+  }
+
+  public void testNullPrimitiveAddition() {
+    JsonArray jsonArray = new JsonArray();
+
+    jsonArray.add((Character) null);
+    jsonArray.add((Boolean) null);
+    jsonArray.add((Integer) null);
+    jsonArray.add((Double) null);
+    jsonArray.add((Float) null);
+    jsonArray.add((BigInteger) null);
+    jsonArray.add((String) null);
+    jsonArray.add((Boolean) null);
+    jsonArray.add((Number) null);
+
+    assertEquals("[null,null,null,null,null,null,null,null,null]", jsonArray.toString());
+  }
+
+  public void testSameAddition() {
+    JsonArray jsonArray = new JsonArray();
+
+    jsonArray.add('a');
+    jsonArray.add('a');
+    jsonArray.add(true);
+    jsonArray.add(true);
+    jsonArray.add(1212);
+    jsonArray.add(1212);
+    jsonArray.add(34.34);
+    jsonArray.add(34.34);
+    jsonArray.add((Boolean) null);
+    jsonArray.add((Boolean) null);
+
+    assertEquals("[\"a\",\"a\",true,true,1212,1212,34.34,34.34,null,null]", jsonArray.toString());
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/JsonParserTest.java b/gson/src/test/java/com/google/gson/functional/JsonParserTest.java
new file mode 100644
index 0000000..965140b
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/JsonParserTest.java
@@ -0,0 +1,139 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.functional;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParseException;
+import com.google.gson.JsonParser;
+import com.google.gson.JsonPrimitive;
+import com.google.gson.JsonSyntaxException;
+import com.google.gson.common.TestTypes.BagOfPrimitives;
+import com.google.gson.common.TestTypes.Nested;
+import com.google.gson.reflect.TypeToken;
+
+import junit.framework.TestCase;
+
+import java.io.StringReader;
+import java.lang.reflect.Type;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Functional tests for that use JsonParser and related Gson methods
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public class JsonParserTest extends TestCase {
+  private Gson gson;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    gson = new Gson();
+  }
+
+  public void testParseInvalidJson() {
+    try {
+      gson.fromJson("[[]", Object[].class);
+      fail();
+    } catch (JsonSyntaxException expected) { }
+  }
+
+  public void testDeserializingCustomTree() {
+    JsonObject obj = new JsonObject();
+    obj.addProperty("stringValue", "foo");
+    obj.addProperty("intValue", 11);
+    BagOfPrimitives target = gson.fromJson(obj, BagOfPrimitives.class);
+    assertEquals(11, target.intValue);
+    assertEquals("foo", target.stringValue);
+  }
+
+  public void testBadTypeForDeserializingCustomTree() {
+    JsonObject obj = new JsonObject();
+    obj.addProperty("stringValue", "foo");
+    obj.addProperty("intValue", 11);
+    JsonArray array = new JsonArray();
+    array.add(obj);
+    try {
+      gson.fromJson(array, BagOfPrimitives.class);
+      fail("BagOfPrimitives is not an array");
+    } catch (JsonParseException expected) { }
+  }
+
+  public void testBadFieldTypeForCustomDeserializerCustomTree() {
+    JsonArray array = new JsonArray();
+    array.add(new JsonPrimitive("blah"));
+    JsonObject obj = new JsonObject();
+    obj.addProperty("stringValue", "foo");
+    obj.addProperty("intValue", 11);
+    obj.add("longValue", array);
+
+    try {
+      gson.fromJson(obj, BagOfPrimitives.class);
+      fail("BagOfPrimitives is not an array");
+    } catch (JsonParseException expected) { }
+  }
+
+  public void testBadFieldTypeForDeserializingCustomTree() {
+    JsonArray array = new JsonArray();
+    array.add(new JsonPrimitive("blah"));
+    JsonObject primitive1 = new JsonObject();
+    primitive1.addProperty("string", "foo");
+    primitive1.addProperty("intValue", 11);
+
+    JsonObject obj = new JsonObject();
+    obj.add("primitive1", primitive1);
+    obj.add("primitive2", array);
+
+    try {
+      gson.fromJson(obj, Nested.class);
+      fail("Nested has field BagOfPrimitives which is not an array");
+    } catch (JsonParseException expected) { }
+  }
+
+  public void testChangingCustomTreeAndDeserializing() {
+    StringReader json =
+      new StringReader("{'stringValue':'no message','intValue':10,'longValue':20}");
+    JsonObject obj = (JsonObject) JsonParser.parseReader(json);
+    obj.remove("stringValue");
+    obj.addProperty("stringValue", "fooBar");
+    BagOfPrimitives target = gson.fromJson(obj, BagOfPrimitives.class);
+    assertEquals(10, target.intValue);
+    assertEquals(20, target.longValue);
+    assertEquals("fooBar", target.stringValue);
+  }
+
+  public void testExtraCommasInArrays() {
+    Type type = new TypeToken<List<String>>() {}.getType();
+    assertEquals(Arrays.asList("a", null, "b", null, null), gson.fromJson("[a,,b,,]", type));
+    assertEquals(Arrays.asList(null, null), gson.fromJson("[,]", type));
+    assertEquals(Arrays.asList("a", null), gson.fromJson("[a,]", type));
+  }
+
+  public void testExtraCommasInMaps() {
+    Type type = new TypeToken<Map<String, String>>() {}.getType();
+    try {
+      gson.fromJson("{a:b,}", type);
+      fail();
+    } catch (JsonSyntaxException expected) {
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/JsonTreeTest.java b/gson/src/test/java/com/google/gson/functional/JsonTreeTest.java
new file mode 100644
index 0000000..a647940
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/JsonTreeTest.java
@@ -0,0 +1,89 @@
+package com.google.gson.functional;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonPrimitive;
+import com.google.gson.common.TestTypes.BagOfPrimitives;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import junit.framework.TestCase;
+
+/**
+ * Functional tests for {@link Gson#toJsonTree(Object)} and 
+ * {@link Gson#toJsonTree(Object, java.lang.reflect.Type)}
+ * 
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public class JsonTreeTest extends TestCase {
+  private Gson gson;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    gson = new Gson();
+  }
+
+  public void testToJsonTree() {
+    BagOfPrimitives bag = new BagOfPrimitives(10L, 5, false, "foo");
+    JsonElement json = gson.toJsonTree(bag);
+    assertTrue(json.isJsonObject());
+    JsonObject obj = json.getAsJsonObject();
+    Set<Entry<String, JsonElement>> children = obj.entrySet();
+    assertEquals(4, children.size());
+    assertContains(obj, new JsonPrimitive(10L));
+    assertContains(obj, new JsonPrimitive(5));
+    assertContains(obj, new JsonPrimitive(false));
+    assertContains(obj, new JsonPrimitive("foo"));
+  }
+
+  public void testToJsonTreeObjectType() {
+    SubTypeOfBagOfPrimitives bag = new SubTypeOfBagOfPrimitives(10L, 5, false, "foo", 1.4F);
+    JsonElement json = gson.toJsonTree(bag, BagOfPrimitives.class);
+    assertTrue(json.isJsonObject());
+    JsonObject obj = json.getAsJsonObject();
+    Set<Entry<String, JsonElement>> children = obj.entrySet();
+    assertEquals(4, children.size());
+    assertContains(obj, new JsonPrimitive(10L));
+    assertContains(obj, new JsonPrimitive(5));
+    assertContains(obj, new JsonPrimitive(false));
+    assertContains(obj, new JsonPrimitive("foo"));
+  }
+
+  public void testJsonTreeToString() {
+    SubTypeOfBagOfPrimitives bag = new SubTypeOfBagOfPrimitives(10L, 5, false, "foo", 1.4F);
+    String json1 = gson.toJson(bag);
+    JsonElement jsonElement = gson.toJsonTree(bag, SubTypeOfBagOfPrimitives.class);
+    String json2 = gson.toJson(jsonElement);
+    assertEquals(json1, json2);
+  }
+
+  public void testJsonTreeNull() {
+    BagOfPrimitives bag = new BagOfPrimitives(10L, 5, false, null);
+    JsonObject jsonElement = (JsonObject) gson.toJsonTree(bag, BagOfPrimitives.class);
+    assertFalse(jsonElement.has("stringValue"));
+  }
+
+  private void assertContains(JsonObject json, JsonPrimitive child) {
+    for (Map.Entry<String, JsonElement> entry : json.entrySet()) {
+      JsonElement node = entry.getValue();
+      if (node.isJsonPrimitive()) {
+        if (node.getAsJsonPrimitive().equals(child)) {
+          return;
+        }
+      }
+    }
+    fail();
+  }
+  
+  private static class SubTypeOfBagOfPrimitives extends BagOfPrimitives {
+    @SuppressWarnings("unused")
+    float f = 1.2F;
+    public SubTypeOfBagOfPrimitives(long l, int i, boolean b, String string, float f) {
+      super(l, i, b, string);
+      this.f = f;
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/LeniencyTest.java b/gson/src/test/java/com/google/gson/functional/LeniencyTest.java
new file mode 100644
index 0000000..6b5375e
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/LeniencyTest.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright (C) 2016 The Gson Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.functional;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.reflect.TypeToken;
+import java.util.List;
+import junit.framework.TestCase;
+
+import static java.util.Collections.singletonList;
+
+/**
+ * Functional tests for leniency option.
+ */
+public class LeniencyTest extends TestCase {
+
+  private Gson gson;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    gson = new GsonBuilder().setLenient().create();
+  }
+
+  public void testLenientFromJson() {
+    List<String> json = gson.fromJson(""
+        + "[ # One!\n"
+        + "  'Hi' #Element!\n"
+        + "] # Array!", new TypeToken<List<String>>() {}.getType());
+    assertEquals(singletonList("Hi"), json);
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/MapAsArrayTypeAdapterTest.java b/gson/src/test/java/com/google/gson/functional/MapAsArrayTypeAdapterTest.java
new file mode 100644
index 0000000..114c94e
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/MapAsArrayTypeAdapterTest.java
@@ -0,0 +1,141 @@
+/*
+ * Copyright (C) 2010 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.functional;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonSyntaxException;
+import com.google.gson.reflect.TypeToken;
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import junit.framework.TestCase;
+
+public class MapAsArrayTypeAdapterTest extends TestCase {
+
+  public void testSerializeComplexMapWithTypeAdapter() {
+    Type type = new TypeToken<Map<Point, String>>() {}.getType();
+    Gson gson = new GsonBuilder()
+        .enableComplexMapKeySerialization()
+        .create();
+
+    Map<Point, String> original = new LinkedHashMap<>();
+    original.put(new Point(5, 5), "a");
+    original.put(new Point(8, 8), "b");
+    String json = gson.toJson(original, type);
+    assertEquals("[[{\"x\":5,\"y\":5},\"a\"],[{\"x\":8,\"y\":8},\"b\"]]", json);
+    assertEquals(original, gson.<Map<Point, String>>fromJson(json, type));
+
+    // test that registering a type adapter for one map doesn't interfere with others
+    Map<String, Boolean> otherMap = new LinkedHashMap<>();
+    otherMap.put("t", true);
+    otherMap.put("f", false);
+    assertEquals("{\"t\":true,\"f\":false}",
+        gson.toJson(otherMap, Map.class));
+    assertEquals("{\"t\":true,\"f\":false}",
+        gson.toJson(otherMap, new TypeToken<Map<String, Boolean>>() {}.getType()));
+    assertEquals(otherMap, gson.<Object>fromJson("{\"t\":true,\"f\":false}",
+        new TypeToken<Map<String, Boolean>>() {}.getType()));
+  }
+
+  public void disabled_testTwoTypesCollapseToOneSerialize() {
+    Gson gson = new GsonBuilder()
+        .enableComplexMapKeySerialization()
+        .create();
+
+    Map<Number, String> original = new LinkedHashMap<>();
+    original.put(1.0D, "a");
+    original.put(1.0F, "b");
+    try {
+      gson.toJson(original, new TypeToken<Map<Number, String>>() {}.getType());
+      fail(); // we no longer hash keys at serialization time
+    } catch (JsonSyntaxException expected) {
+    }
+  }
+
+  public void testTwoTypesCollapseToOneDeserialize() {
+    Gson gson = new GsonBuilder()
+        .enableComplexMapKeySerialization()
+        .create();
+
+    String s = "[[\"1.00\",\"a\"],[\"1.0\",\"b\"]]";
+    try {
+      gson.fromJson(s, new TypeToken<Map<Double, String>>() {}.getType());
+      fail();
+    } catch (JsonSyntaxException expected) {
+    }
+  }
+
+  public void testMultipleEnableComplexKeyRegistrationHasNoEffect() throws Exception {
+    Type type = new TypeToken<Map<Point, String>>() {}.getType();
+    Gson gson = new GsonBuilder()
+        .enableComplexMapKeySerialization()
+        .enableComplexMapKeySerialization()
+        .create();
+
+    Map<Point, String> original = new LinkedHashMap<>();
+    original.put(new Point(6, 5), "abc");
+    original.put(new Point(1, 8), "def");
+    String json = gson.toJson(original, type);
+    assertEquals("[[{\"x\":6,\"y\":5},\"abc\"],[{\"x\":1,\"y\":8},\"def\"]]", json);
+    assertEquals(original, gson.<Map<Point, String>>fromJson(json, type));
+  }
+
+  public void testMapWithTypeVariableSerialization() {
+    Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
+    PointWithProperty<Point> map = new PointWithProperty<>();
+    map.map.put(new Point(2, 3), new Point(4, 5));
+    Type type = new TypeToken<PointWithProperty<Point>>(){}.getType();
+    String json = gson.toJson(map, type);
+    assertEquals("{\"map\":[[{\"x\":2,\"y\":3},{\"x\":4,\"y\":5}]]}", json);
+  }
+
+  public void testMapWithTypeVariableDeserialization() {
+    Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
+    String json = "{map:[[{x:2,y:3},{x:4,y:5}]]}";
+    Type type = new TypeToken<PointWithProperty<Point>>(){}.getType();
+    PointWithProperty<Point> map = gson.fromJson(json, type);
+    Point key = map.map.keySet().iterator().next();
+    Point value = map.map.values().iterator().next();
+    assertEquals(new Point(2, 3), key);
+    assertEquals(new Point(4, 5), value);
+  }
+
+  static class Point {
+    int x;
+    int y;
+    Point(int x, int y) {
+      this.x = x;
+      this.y = y;
+    }
+    Point() {}
+    @Override public boolean equals(Object o) {
+      return o instanceof Point && ((Point) o).x == x && ((Point) o).y == y;
+    }
+    @Override public int hashCode() {
+      return x * 37 + y;
+    }
+    @Override public String toString() {
+      return "(" + x + "," + y + ")";
+    }
+  }
+
+  static class PointWithProperty<T> {
+    Map<Point, T> map = new HashMap<>();
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/MapTest.java b/gson/src/test/java/com/google/gson/functional/MapTest.java
new file mode 100644
index 0000000..ef9eae2
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/MapTest.java
@@ -0,0 +1,653 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.functional;
+
+import java.lang.reflect.Type;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.SortedMap;
+import java.util.TreeMap;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.ConcurrentNavigableMap;
+import java.util.concurrent.ConcurrentSkipListMap;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.InstanceCreator;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonParseException;
+import com.google.gson.JsonParser;
+import com.google.gson.JsonPrimitive;
+import com.google.gson.JsonSerializationContext;
+import com.google.gson.JsonSerializer;
+import com.google.gson.JsonSyntaxException;
+import com.google.gson.common.TestTypes;
+import com.google.gson.internal.$Gson$Types;
+import com.google.gson.reflect.TypeToken;
+
+import junit.framework.TestCase;
+
+/**
+ * Functional test for Json serialization and deserialization for Maps
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public class MapTest extends TestCase {
+  private Gson gson;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    gson = new Gson();
+  }
+
+  public void testMapSerialization() {
+    Map<String, Integer> map = new LinkedHashMap<>();
+    map.put("a", 1);
+    map.put("b", 2);
+    Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
+    String json = gson.toJson(map, typeOfMap);
+    assertTrue(json.contains("\"a\":1"));
+    assertTrue(json.contains("\"b\":2"));
+  }
+
+  public void testMapDeserialization() {
+    String json = "{\"a\":1,\"b\":2}";
+    Type typeOfMap = new TypeToken<Map<String,Integer>>(){}.getType();
+    Map<String, Integer> target = gson.fromJson(json, typeOfMap);
+    assertEquals(1, target.get("a").intValue());
+    assertEquals(2, target.get("b").intValue());
+  }
+
+  @SuppressWarnings({"unchecked", "rawtypes"})
+  public void testRawMapSerialization() {
+    Map map = new LinkedHashMap();
+    map.put("a", 1);
+    map.put("b", "string");
+    String json = gson.toJson(map);
+    assertTrue(json.contains("\"a\":1"));
+    assertTrue(json.contains("\"b\":\"string\""));
+  }
+
+  public void testMapSerializationEmpty() {
+    Map<String, Integer> map = new LinkedHashMap<>();
+    Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
+    String json = gson.toJson(map, typeOfMap);
+    assertEquals("{}", json);
+  }
+
+  public void testMapDeserializationEmpty() {
+    Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
+    Map<String, Integer> map = gson.fromJson("{}", typeOfMap);
+    assertTrue(map.isEmpty());
+  }
+
+  public void testMapSerializationWithNullValue() {
+    Map<String, Integer> map = new LinkedHashMap<>();
+    map.put("abc", null);
+    Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
+    String json = gson.toJson(map, typeOfMap);
+
+    // Maps are represented as JSON objects, so ignoring null field
+    assertEquals("{}", json);
+  }
+
+  public void testMapDeserializationWithNullValue() {
+    Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
+    Map<String, Integer> map = gson.fromJson("{\"abc\":null}", typeOfMap);
+    assertEquals(1, map.size());
+    assertNull(map.get("abc"));
+  }
+
+  public void testMapSerializationWithNullValueButSerializeNulls() {
+    gson = new GsonBuilder().serializeNulls().create();
+    Map<String, Integer> map = new LinkedHashMap<>();
+    map.put("abc", null);
+    Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
+    String json = gson.toJson(map, typeOfMap);
+
+    assertEquals("{\"abc\":null}", json);
+  }
+
+  public void testMapSerializationWithNullKey() {
+    Map<String, Integer> map = new LinkedHashMap<>();
+    map.put(null, 123);
+    Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
+    String json = gson.toJson(map, typeOfMap);
+
+    assertEquals("{\"null\":123}", json);
+  }
+
+  public void testMapDeserializationWithNullKey() {
+    Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
+    Map<String, Integer> map = gson.fromJson("{\"null\":123}", typeOfMap);
+    assertEquals(1, map.size());
+    assertEquals(123, map.get("null").intValue());
+    assertNull(map.get(null));
+
+    map = gson.fromJson("{null:123}", typeOfMap);
+    assertEquals(1, map.size());
+    assertEquals(123, map.get("null").intValue());
+    assertNull(map.get(null));
+  }
+
+  public void testMapSerializationWithIntegerKeys() {
+    Map<Integer, String> map = new LinkedHashMap<>();
+    map.put(123, "456");
+    Type typeOfMap = new TypeToken<Map<Integer, String>>() {}.getType();
+    String json = gson.toJson(map, typeOfMap);
+
+    assertEquals("{\"123\":\"456\"}", json);
+  }
+
+  public void testMapDeserializationWithIntegerKeys() {
+    Type typeOfMap = new TypeToken<Map<Integer, String>>() {}.getType();
+    Map<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap);
+    assertEquals(1, map.size());
+    assertTrue(map.containsKey(123));
+    assertEquals("456", map.get(123));
+  }
+
+  public void testMapDeserializationWithUnquotedIntegerKeys() {
+    Type typeOfMap = new TypeToken<Map<Integer, String>>() {}.getType();
+    Map<Integer, String> map = gson.fromJson("{123:\"456\"}", typeOfMap);
+    assertEquals(1, map.size());
+    assertTrue(map.containsKey(123));
+    assertEquals("456", map.get(123));
+  }
+
+  public void testMapDeserializationWithLongKeys() {
+    long longValue = 9876543210L;
+    String json = String.format("{\"%d\":\"456\"}", longValue);
+    Type typeOfMap = new TypeToken<Map<Long, String>>() {}.getType();
+    Map<Long, String> map = gson.fromJson(json, typeOfMap);
+    assertEquals(1, map.size());
+    assertTrue(map.containsKey(longValue));
+    assertEquals("456", map.get(longValue));
+  }
+
+  public void testMapDeserializationWithUnquotedLongKeys() {
+    long longKey = 9876543210L;
+    String json = String.format("{%d:\"456\"}", longKey);
+    Type typeOfMap = new TypeToken<Map<Long, String>>() {}.getType();
+    Map<Long, String> map = gson.fromJson(json, typeOfMap);
+    assertEquals(1, map.size());
+    assertTrue(map.containsKey(longKey));
+    assertEquals("456", map.get(longKey));
+  }
+
+  public void testHashMapDeserialization() throws Exception {
+    Type typeOfMap = new TypeToken<HashMap<Integer, String>>() {}.getType();
+    HashMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap);
+    assertEquals(1, map.size());
+    assertTrue(map.containsKey(123));
+    assertEquals("456", map.get(123));
+  }
+
+  public void testSortedMap() throws Exception {
+    Type typeOfMap = new TypeToken<SortedMap<Integer, String>>() {}.getType();
+    SortedMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap);
+    assertEquals(1, map.size());
+    assertTrue(map.containsKey(123));
+    assertEquals("456", map.get(123));
+  }
+
+  public void testConcurrentMap() throws Exception {
+    Type typeOfMap = new TypeToken<ConcurrentMap<Integer, String>>() {}.getType();
+    ConcurrentMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap);
+    assertEquals(1, map.size());
+    assertTrue(map.containsKey(123));
+    assertEquals("456", map.get(123));
+    String json = gson.toJson(map);
+    assertEquals("{\"123\":\"456\"}", json);
+  }
+
+  public void testConcurrentHashMap() throws Exception {
+    Type typeOfMap = new TypeToken<ConcurrentHashMap<Integer, String>>() {}.getType();
+    ConcurrentHashMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap);
+    assertEquals(1, map.size());
+    assertTrue(map.containsKey(123));
+    assertEquals("456", map.get(123));
+    String json = gson.toJson(map);
+    assertEquals("{\"123\":\"456\"}", json);
+  }
+
+  public void testConcurrentNavigableMap() throws Exception {
+    Type typeOfMap = new TypeToken<ConcurrentNavigableMap<Integer, String>>() {}.getType();
+    ConcurrentNavigableMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap);
+    assertEquals(1, map.size());
+    assertTrue(map.containsKey(123));
+    assertEquals("456", map.get(123));
+    String json = gson.toJson(map);
+    assertEquals("{\"123\":\"456\"}", json);
+  }
+
+  public void testConcurrentSkipListMap() throws Exception {
+    Type typeOfMap = new TypeToken<ConcurrentSkipListMap<Integer, String>>() {}.getType();
+    ConcurrentSkipListMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap);
+    assertEquals(1, map.size());
+    assertTrue(map.containsKey(123));
+    assertEquals("456", map.get(123));
+    String json = gson.toJson(map);
+    assertEquals("{\"123\":\"456\"}", json);
+  }
+
+  public void testParameterizedMapSubclassSerialization() {
+    MyParameterizedMap<String, String> map = new MyParameterizedMap<>(10);
+    map.put("a", "b");
+    Type type = new TypeToken<MyParameterizedMap<String, String>>() {}.getType();
+    String json = gson.toJson(map, type);
+    assertTrue(json.contains("\"a\":\"b\""));
+  }
+
+  @SuppressWarnings({ "unused", "serial" })
+  private static class MyParameterizedMap<K, V> extends LinkedHashMap<K, V> {
+    final int foo;
+    MyParameterizedMap(int foo) {
+      this.foo = foo;
+    }
+  }
+
+  public void testMapSubclassSerialization() {
+    MyMap map = new MyMap();
+    map.put("a", "b");
+    String json = gson.toJson(map, MyMap.class);
+    assertTrue(json.contains("\"a\":\"b\""));
+  }
+
+  public void testMapStandardSubclassDeserialization() {
+    String json = "{a:'1',b:'2'}";
+    Type type = new TypeToken<LinkedHashMap<String, String>>() {}.getType();
+    LinkedHashMap<String, Integer> map = gson.fromJson(json, type);
+    assertEquals("1", map.get("a"));
+    assertEquals("2", map.get("b"));
+  }
+
+  public void testMapSubclassDeserialization() {
+    Gson gson = new GsonBuilder().registerTypeAdapter(MyMap.class, new InstanceCreator<MyMap>() {
+      @Override public MyMap createInstance(Type type) {
+        return new MyMap();
+      }
+    }).create();
+    String json = "{\"a\":1,\"b\":2}";
+    MyMap map = gson.fromJson(json, MyMap.class);
+    assertEquals("1", map.get("a"));
+    assertEquals("2", map.get("b"));
+  }
+
+  public void testCustomSerializerForSpecificMapType() {
+    Type type = $Gson$Types.newParameterizedTypeWithOwner(
+        null, Map.class, String.class, Long.class);
+    Gson gson = new GsonBuilder()
+        .registerTypeAdapter(type, new JsonSerializer<Map<String, Long>>() {
+          @Override public JsonElement serialize(Map<String, Long> src, Type typeOfSrc,
+              JsonSerializationContext context) {
+            JsonArray array = new JsonArray();
+            for (long value : src.values()) {
+              array.add(new JsonPrimitive(value));
+            }
+            return array;
+          }
+        }).create();
+
+    Map<String, Long> src = new LinkedHashMap<>();
+    src.put("one", 1L);
+    src.put("two", 2L);
+    src.put("three", 3L);
+
+    assertEquals("[1,2,3]", gson.toJson(src, type));
+  }
+
+  /**
+   * Created in response to http://code.google.com/p/google-gson/issues/detail?id=99
+   */
+  private static class ClassWithAMap {
+    Map<String, String> map = new TreeMap<>();
+  }
+
+  /**
+   * Created in response to http://code.google.com/p/google-gson/issues/detail?id=99
+   */
+  public void testMapSerializationWithNullValues() {
+    ClassWithAMap target = new ClassWithAMap();
+    target.map.put("name1", null);
+    target.map.put("name2", "value2");
+    String json = gson.toJson(target);
+    assertFalse(json.contains("name1"));
+    assertTrue(json.contains("name2"));
+  }
+
+  /**
+   * Created in response to http://code.google.com/p/google-gson/issues/detail?id=99
+   */
+  public void testMapSerializationWithNullValuesSerialized() {
+    Gson gson = new GsonBuilder().serializeNulls().create();
+    ClassWithAMap target = new ClassWithAMap();
+    target.map.put("name1", null);
+    target.map.put("name2", "value2");
+    String json = gson.toJson(target);
+    assertTrue(json.contains("name1"));
+    assertTrue(json.contains("name2"));
+  }
+
+  public void testMapSerializationWithWildcardValues() {
+    Map<String, ? extends Collection<? extends Integer>> map = new LinkedHashMap<>();
+    map.put("test", null);
+    Type typeOfMap =
+        new TypeToken<Map<String, ? extends Collection<? extends Integer>>>() {}.getType();
+    String json = gson.toJson(map, typeOfMap);
+
+    assertEquals("{}", json);
+  }
+
+  public void testMapDeserializationWithWildcardValues() {
+    Type typeOfMap = new TypeToken<Map<String, ? extends Long>>() {}.getType();
+    Map<String, ? extends Long> map = gson.fromJson("{\"test\":123}", typeOfMap);
+    assertEquals(1, map.size());
+    assertEquals(Long.valueOf(123L), map.get("test"));
+  }
+
+
+  private static class MyMap extends LinkedHashMap<String, String> {
+    private static final long serialVersionUID = 1L;
+
+    @SuppressWarnings("unused")
+    int foo = 10;
+  }
+
+  /**
+   * From bug report http://code.google.com/p/google-gson/issues/detail?id=95
+   */
+  public void testMapOfMapSerialization() {
+    Map<String, Map<String, String>> map = new HashMap<>();
+    Map<String, String> nestedMap = new HashMap<>();
+    nestedMap.put("1", "1");
+    nestedMap.put("2", "2");
+    map.put("nestedMap", nestedMap);
+    String json = gson.toJson(map);
+    assertTrue(json.contains("nestedMap"));
+    assertTrue(json.contains("\"1\":\"1\""));
+    assertTrue(json.contains("\"2\":\"2\""));
+  }
+
+  /**
+   * From bug report http://code.google.com/p/google-gson/issues/detail?id=95
+   */
+  public void testMapOfMapDeserialization() {
+    String json = "{nestedMap:{'2':'2','1':'1'}}";
+    Type type = new TypeToken<Map<String, Map<String, String>>>(){}.getType();
+    Map<String, Map<String, String>> map = gson.fromJson(json, type);
+    Map<String, String> nested = map.get("nestedMap");
+    assertEquals("1", nested.get("1"));
+    assertEquals("2", nested.get("2"));
+  }
+
+  /**
+   * From bug report http://code.google.com/p/google-gson/issues/detail?id=178
+   */
+  public void testMapWithQuotes() {
+    Map<String, String> map = new HashMap<>();
+    map.put("a\"b", "c\"d");
+    String json = gson.toJson(map);
+    assertEquals("{\"a\\\"b\":\"c\\\"d\"}", json);
+  }
+
+  /**
+   * From issue 227.
+   */
+  public void testWriteMapsWithEmptyStringKey() {
+    Map<String, Boolean> map = new HashMap<>();
+    map.put("", true);
+    assertEquals("{\"\":true}", gson.toJson(map));
+
+  }
+
+  public void testReadMapsWithEmptyStringKey() {
+    Map<String, Boolean> map = gson.fromJson("{\"\":true}", new TypeToken<Map<String, Boolean>>() {}.getType());
+    assertEquals(Boolean.TRUE, map.get(""));
+  }
+
+  /**
+   * From bug report http://code.google.com/p/google-gson/issues/detail?id=204
+   */
+  public void testSerializeMaps() {
+    Map<String, Object> map = new LinkedHashMap<>();
+    map.put("a", 12);
+    map.put("b", null);
+
+    LinkedHashMap<String, Object> innerMap = new LinkedHashMap<>();
+    innerMap.put("test", 1);
+    innerMap.put("TestStringArray", new String[] { "one", "two" });
+    map.put("c", innerMap);
+
+    assertEquals("{\"a\":12,\"b\":null,\"c\":{\"test\":1,\"TestStringArray\":[\"one\",\"two\"]}}",
+        new GsonBuilder().serializeNulls().create().toJson(map));
+    assertEquals("{\n  \"a\": 12,\n  \"b\": null,\n  \"c\": "
+        + "{\n    \"test\": 1,\n    \"TestStringArray\": "
+        + "[\n      \"one\",\n      \"two\"\n    ]\n  }\n}",
+        new GsonBuilder().setPrettyPrinting().serializeNulls().create().toJson(map));
+    assertEquals("{\"a\":12,\"c\":{\"test\":1,\"TestStringArray\":[\"one\",\"two\"]}}",
+        new GsonBuilder().create().toJson(map));
+    assertEquals("{\n  \"a\": 12,\n  \"c\": "
+        + "{\n    \"test\": 1,\n    \"TestStringArray\": "
+        + "[\n      \"one\",\n      \"two\"\n    ]\n  }\n}",
+        new GsonBuilder().setPrettyPrinting().create().toJson(map));
+
+    innerMap.put("d", "e");
+    assertEquals("{\"a\":12,\"c\":{\"test\":1,\"TestStringArray\":[\"one\",\"two\"],\"d\":\"e\"}}",
+        new Gson().toJson(map));
+  }
+
+  public final void testInterfaceTypeMap() {
+    MapClass element = new MapClass();
+    TestTypes.Sub subType = new TestTypes.Sub();
+    element.addBase("Test", subType);
+    element.addSub("Test", subType);
+
+    String subTypeJson = new Gson().toJson(subType);
+    String expected = "{\"bases\":{\"Test\":" + subTypeJson + "},"
+      + "\"subs\":{\"Test\":" + subTypeJson + "}}";
+
+    Gson gsonWithComplexKeys = new GsonBuilder()
+        .enableComplexMapKeySerialization()
+        .create();
+    String json = gsonWithComplexKeys.toJson(element);
+    assertEquals(expected, json);
+
+    Gson gson = new Gson();
+    json = gson.toJson(element);
+    assertEquals(expected, json);
+  }
+
+  public final void testInterfaceTypeMapWithSerializer() {
+    MapClass element = new MapClass();
+    TestTypes.Sub subType = new TestTypes.Sub();
+    element.addBase("Test", subType);
+    element.addSub("Test", subType);
+
+    Gson tempGson = new Gson();
+    String subTypeJson = tempGson.toJson(subType);
+    final JsonElement baseTypeJsonElement = tempGson.toJsonTree(subType, TestTypes.Base.class);
+    String baseTypeJson = tempGson.toJson(baseTypeJsonElement);
+    String expected = "{\"bases\":{\"Test\":" + baseTypeJson + "},"
+        + "\"subs\":{\"Test\":" + subTypeJson + "}}";
+
+    JsonSerializer<TestTypes.Base> baseTypeAdapter = new JsonSerializer<TestTypes.Base>() {
+      @Override public JsonElement serialize(TestTypes.Base src, Type typeOfSrc,
+          JsonSerializationContext context) {
+        return baseTypeJsonElement;
+      }
+    };
+
+    Gson gson = new GsonBuilder()
+        .enableComplexMapKeySerialization()
+        .registerTypeAdapter(TestTypes.Base.class, baseTypeAdapter)
+        .create();
+    String json = gson.toJson(element);
+    assertEquals(expected, json);
+
+    gson = new GsonBuilder()
+        .registerTypeAdapter(TestTypes.Base.class, baseTypeAdapter)
+        .create();
+    json = gson.toJson(element);
+    assertEquals(expected, json);
+  }
+
+  public void testGeneralMapField() throws Exception {
+    MapWithGeneralMapParameters map = new MapWithGeneralMapParameters();
+    map.map.put("string", "testString");
+    map.map.put("stringArray", new String[]{"one", "two"});
+    map.map.put("objectArray", new Object[]{1, 2L, "three"});
+
+    String expected = "{\"map\":{\"string\":\"testString\",\"stringArray\":"
+        + "[\"one\",\"two\"],\"objectArray\":[1,2,\"three\"]}}";
+    assertEquals(expected, gson.toJson(map));
+
+    gson = new GsonBuilder()
+        .enableComplexMapKeySerialization()
+        .create();
+    assertEquals(expected, gson.toJson(map));
+  }
+
+  public void testComplexKeysSerialization() {
+    Map<Point, String> map = new LinkedHashMap<>();
+    map.put(new Point(2, 3), "a");
+    map.put(new Point(5, 7), "b");
+    String json = "{\"2,3\":\"a\",\"5,7\":\"b\"}";
+    assertEquals(json, gson.toJson(map, new TypeToken<Map<Point, String>>() {}.getType()));
+    assertEquals(json, gson.toJson(map, Map.class));
+  }
+
+  public void testComplexKeysDeserialization() {
+    String json = "{'2,3':'a','5,7':'b'}";
+    try {
+      gson.fromJson(json, new TypeToken<Map<Point, String>>() {}.getType());
+      fail();
+    } catch (JsonParseException expected) {
+    }
+  }
+
+  public void testStringKeyDeserialization() {
+    String json = "{'2,3':'a','5,7':'b'}";
+    Map<String, String> map = new LinkedHashMap<>();
+    map.put("2,3", "a");
+    map.put("5,7", "b");
+    assertEquals(map, gson.fromJson(json, new TypeToken<Map<String, String>>() {}.getType()));
+  }
+
+  public void testNumberKeyDeserialization() {
+    String json = "{'2.3':'a','5.7':'b'}";
+    Map<Double, String> map = new LinkedHashMap<>();
+    map.put(2.3, "a");
+    map.put(5.7, "b");
+    assertEquals(map, gson.fromJson(json, new TypeToken<Map<Double, String>>() {}.getType()));
+  }
+
+  public void testBooleanKeyDeserialization() {
+    String json = "{'true':'a','false':'b'}";
+    Map<Boolean, String> map = new LinkedHashMap<>();
+    map.put(true, "a");
+    map.put(false, "b");
+    assertEquals(map, gson.fromJson(json, new TypeToken<Map<Boolean, String>>() {}.getType()));
+  }
+
+  public void testMapDeserializationWithDuplicateKeys() {
+    try {
+      gson.fromJson("{'a':1,'a':2}", new TypeToken<Map<String, Integer>>() {}.getType());
+      fail();
+    } catch (JsonSyntaxException expected) {
+    }
+  }
+
+  public void testSerializeMapOfMaps() {
+    Type type = new TypeToken<Map<String, Map<String, String>>>() {}.getType();
+    Map<String, Map<String, String>> map = newMap(
+        "a", newMap("ka1", "va1", "ka2", "va2"),
+        "b", newMap("kb1", "vb1", "kb2", "vb2"));
+    assertEquals("{'a':{'ka1':'va1','ka2':'va2'},'b':{'kb1':'vb1','kb2':'vb2'}}",
+        gson.toJson(map, type).replace('"', '\''));
+  }
+
+  public void testDeerializeMapOfMaps() {
+    Type type = new TypeToken<Map<String, Map<String, String>>>() {}.getType();
+    Map<String, Map<String, String>> map = newMap(
+        "a", newMap("ka1", "va1", "ka2", "va2"),
+        "b", newMap("kb1", "vb1", "kb2", "vb2"));
+    String json = "{'a':{'ka1':'va1','ka2':'va2'},'b':{'kb1':'vb1','kb2':'vb2'}}";
+    assertEquals(map, gson.fromJson(json, type));
+  }
+
+  private <K, V> Map<K, V> newMap(K key1, V value1, K key2, V value2) {
+    Map<K, V> result = new LinkedHashMap<>();
+    result.put(key1, value1);
+    result.put(key2, value2);
+    return result;
+  }
+
+  public void testMapNamePromotionWithJsonElementReader() {
+    String json = "{'2.3':'a'}";
+    Map<Double, String> map = new LinkedHashMap<>();
+    map.put(2.3, "a");
+    JsonElement tree = JsonParser.parseString(json);
+    assertEquals(map, gson.fromJson(tree, new TypeToken<Map<Double, String>>() {}.getType()));
+  }
+
+  static class Point {
+    private final int x;
+    private final int y;
+
+    Point(int x, int y) {
+      this.x = x;
+      this.y = y;
+    }
+
+    @Override public boolean equals(Object o) {
+      return o instanceof Point && x == ((Point) o).x && y == ((Point) o).y;
+    }
+
+    @Override public int hashCode() {
+      return x * 37 + y;
+    }
+
+    @Override public String toString() {
+      return x + "," + y;
+    }
+  }
+
+  static final class MapClass {
+    private final Map<String, TestTypes.Base> bases = new HashMap<>();
+    private final Map<String, TestTypes.Sub> subs = new HashMap<>();
+
+    public final void addBase(String name, TestTypes.Base value) {
+      bases.put(name, value);
+    }
+
+    public final void addSub(String name, TestTypes.Sub value) {
+      subs.put(name, value);
+    }
+  }
+
+  static final class MapWithGeneralMapParameters {
+    @SuppressWarnings({"rawtypes", "unchecked"})
+    final Map<String, Object> map = new LinkedHashMap();
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/MoreSpecificTypeSerializationTest.java b/gson/src/test/java/com/google/gson/functional/MoreSpecificTypeSerializationTest.java
new file mode 100644
index 0000000..a179fa8
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/MoreSpecificTypeSerializationTest.java
@@ -0,0 +1,178 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.functional;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonObject;
+
+import junit.framework.TestCase;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Tests for Gson serialization of a sub-class object while encountering a base-class type
+ *
+ * @author Inderjeet Singh
+ */
+@SuppressWarnings("unused")
+public class MoreSpecificTypeSerializationTest extends TestCase {
+  private Gson gson;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    gson = new Gson();
+  }
+
+  public void testSubclassFields() {
+    ClassWithBaseFields target = new ClassWithBaseFields(new Sub(1, 2));
+    String json = gson.toJson(target);
+    assertTrue(json.contains("\"b\":1"));
+    assertTrue(json.contains("\"s\":2"));
+  }
+
+  public void testListOfSubclassFields() {
+    Collection<Base> list = new ArrayList<>();
+    list.add(new Base(1));
+    list.add(new Sub(2, 3));
+    ClassWithContainersOfBaseFields target = new ClassWithContainersOfBaseFields(list, null);
+    String json = gson.toJson(target);
+    assertTrue(json, json.contains("{\"b\":1}"));
+    assertTrue(json, json.contains("{\"s\":3,\"b\":2}"));
+  }
+
+  public void testMapOfSubclassFields() {
+    Map<String, Base> map = new HashMap<>();
+    map.put("base", new Base(1));
+    map.put("sub", new Sub(2, 3));
+    ClassWithContainersOfBaseFields target = new ClassWithContainersOfBaseFields(null, map);
+    JsonObject json = gson.toJsonTree(target).getAsJsonObject().get("map").getAsJsonObject();
+    assertEquals(1, json.get("base").getAsJsonObject().get("b").getAsInt());
+    JsonObject sub = json.get("sub").getAsJsonObject();
+    assertEquals(2, sub.get("b").getAsInt());
+    assertEquals(3, sub.get("s").getAsInt());
+  }
+
+  /**
+   * For parameterized type, Gson ignores the more-specific type and sticks to the declared type
+   */
+  public void testParameterizedSubclassFields() {
+    ClassWithParameterizedBaseFields target = new ClassWithParameterizedBaseFields(
+        new ParameterizedSub<>("one", "two"));
+    String json = gson.toJson(target);
+    assertTrue(json.contains("\"t\":\"one\""));
+    assertFalse(json.contains("\"s\""));
+  }
+
+  /**
+   * For parameterized type in a List, Gson ignores the more-specific type and sticks to
+   * the declared type
+   */
+  public void testListOfParameterizedSubclassFields() {
+    Collection<ParameterizedBase<String>> list = new ArrayList<>();
+    list.add(new ParameterizedBase<>("one"));
+    list.add(new ParameterizedSub<>("two", "three"));
+    ClassWithContainersOfParameterizedBaseFields target =
+      new ClassWithContainersOfParameterizedBaseFields(list, null);
+    String json = gson.toJson(target);
+    assertTrue(json, json.contains("{\"t\":\"one\"}"));
+    assertFalse(json, json.contains("\"s\":"));
+  }
+
+  /**
+   * For parameterized type in a map, Gson ignores the more-specific type and sticks to the
+   * declared type
+   */
+  public void testMapOfParameterizedSubclassFields() {
+    Map<String, ParameterizedBase<String>> map = new HashMap<>();
+    map.put("base", new ParameterizedBase<>("one"));
+    map.put("sub", new ParameterizedSub<>("two", "three"));
+    ClassWithContainersOfParameterizedBaseFields target =
+      new ClassWithContainersOfParameterizedBaseFields(null, map);
+    JsonObject json = gson.toJsonTree(target).getAsJsonObject().get("map").getAsJsonObject();
+    assertEquals("one", json.get("base").getAsJsonObject().get("t").getAsString());
+    JsonObject sub = json.get("sub").getAsJsonObject();
+    assertEquals("two", sub.get("t").getAsString());
+    assertNull(sub.get("s"));
+  }
+
+  private static class Base {
+    int b;
+    Base(int b) {
+      this.b = b;
+    }
+  }
+
+  private static class Sub extends Base {
+    int s;
+    Sub(int b, int s) {
+      super(b);
+      this.s = s;
+    }
+  }
+
+  private static class ClassWithBaseFields {
+    Base b;
+    ClassWithBaseFields(Base b) {
+      this.b = b;
+    }
+  }
+
+  private static class ClassWithContainersOfBaseFields {
+    Collection<Base> collection;
+    Map<String, Base> map;
+    ClassWithContainersOfBaseFields(Collection<Base> collection, Map<String, Base> map) {
+      this.collection = collection;
+      this.map = map;
+    }
+  }
+
+  private static class ParameterizedBase<T> {
+    T t;
+    ParameterizedBase(T t) {
+      this.t = t;
+    }
+  }
+
+  private static class ParameterizedSub<T> extends ParameterizedBase<T> {
+    T s;
+    ParameterizedSub(T t, T s) {
+      super(t);
+      this.s = s;
+    }
+  }
+
+  private static class ClassWithParameterizedBaseFields {
+    ParameterizedBase<String> b;
+    ClassWithParameterizedBaseFields(ParameterizedBase<String> b) {
+      this.b = b;
+    }
+  }
+
+  private static class ClassWithContainersOfParameterizedBaseFields {
+    Collection<ParameterizedBase<String>> collection;
+    Map<String, ParameterizedBase<String>> map;
+    ClassWithContainersOfParameterizedBaseFields(Collection<ParameterizedBase<String>> collection,
+        Map<String, ParameterizedBase<String>> map) {
+      this.collection = collection;
+      this.map = map;
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/NamingPolicyTest.java b/gson/src/test/java/com/google/gson/functional/NamingPolicyTest.java
new file mode 100644
index 0000000..ab76e64
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/NamingPolicyTest.java
@@ -0,0 +1,219 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.functional;
+
+import com.google.gson.FieldNamingPolicy;
+import com.google.gson.FieldNamingStrategy;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.annotations.SerializedName;
+import com.google.gson.common.TestTypes.ClassWithSerializedNameFields;
+import com.google.gson.common.TestTypes.StringWrapper;
+
+import junit.framework.TestCase;
+
+import java.lang.reflect.Field;
+
+/**
+ * Functional tests for naming policies.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public class NamingPolicyTest extends TestCase {
+  private GsonBuilder builder;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    builder = new GsonBuilder();
+  }
+
+  public void testGsonWithNonDefaultFieldNamingPolicySerialization() {
+    Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
+    StringWrapper target = new StringWrapper("blah");
+    assertEquals("{\"SomeConstantStringInstanceField\":\""
+        + target.someConstantStringInstanceField + "\"}", gson.toJson(target));
+  }
+
+  public void testGsonWithNonDefaultFieldNamingPolicyDeserialiation() {
+    Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
+    String target = "{\"SomeConstantStringInstanceField\":\"someValue\"}";
+    StringWrapper deserializedObject = gson.fromJson(target, StringWrapper.class);
+    assertEquals("someValue", deserializedObject.someConstantStringInstanceField);
+  }
+
+  public void testGsonWithLowerCaseDashPolicySerialization() {
+    Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES).create();
+    StringWrapper target = new StringWrapper("blah");
+    assertEquals("{\"some-constant-string-instance-field\":\""
+        + target.someConstantStringInstanceField + "\"}", gson.toJson(target));
+  }
+
+  public void testGsonWithLowerCaseDotPolicySerialization() {
+    Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DOTS).create();
+    StringWrapper target = new StringWrapper("blah");
+    assertEquals("{\"some.constant.string.instance.field\":\""
+          + target.someConstantStringInstanceField + "\"}", gson.toJson(target));
+  }
+
+  public void testGsonWithLowerCaseDotPolicyDeserialiation() {
+    Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DOTS).create();
+    String target = "{\"some.constant.string.instance.field\":\"someValue\"}";
+    StringWrapper deserializedObject = gson.fromJson(target, StringWrapper.class);
+    assertEquals("someValue", deserializedObject.someConstantStringInstanceField);
+  }
+
+  public void testGsonWithLowerCaseDashPolicyDeserialiation() {
+    Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES).create();
+    String target = "{\"some-constant-string-instance-field\":\"someValue\"}";
+    StringWrapper deserializedObject = gson.fromJson(target, StringWrapper.class);
+    assertEquals("someValue", deserializedObject.someConstantStringInstanceField);
+  }
+
+  public void testGsonWithLowerCaseUnderscorePolicySerialization() {
+    Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
+        .create();
+    StringWrapper target = new StringWrapper("blah");
+    assertEquals("{\"some_constant_string_instance_field\":\""
+        + target.someConstantStringInstanceField + "\"}", gson.toJson(target));
+  }
+
+  public void testGsonWithLowerCaseUnderscorePolicyDeserialiation() {
+    Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
+        .create();
+    String target = "{\"some_constant_string_instance_field\":\"someValue\"}";
+    StringWrapper deserializedObject = gson.fromJson(target, StringWrapper.class);
+    assertEquals("someValue", deserializedObject.someConstantStringInstanceField);
+  }
+
+  public void testGsonWithSerializedNameFieldNamingPolicySerialization() {
+    Gson gson = builder.create();
+    ClassWithSerializedNameFields expected = new ClassWithSerializedNameFields(5, 6);
+    String actual = gson.toJson(expected);
+    assertEquals(expected.getExpectedJson(), actual);
+  }
+
+  public void testGsonWithSerializedNameFieldNamingPolicyDeserialization() {
+    Gson gson = builder.create();
+    ClassWithSerializedNameFields expected = new ClassWithSerializedNameFields(5, 7);
+    ClassWithSerializedNameFields actual =
+        gson.fromJson(expected.getExpectedJson(), ClassWithSerializedNameFields.class);
+    assertEquals(expected.f, actual.f);
+  }
+
+  public void testGsonDuplicateNameUsingSerializedNameFieldNamingPolicySerialization() {
+    Gson gson = builder.create();
+    try {
+      ClassWithDuplicateFields target = new ClassWithDuplicateFields(10);
+      gson.toJson(target);
+      fail();
+    } catch (IllegalArgumentException expected) {
+    }
+  }
+
+  public void testGsonWithUpperCamelCaseSpacesPolicySerialiation() {
+    Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES)
+        .create();
+    StringWrapper target = new StringWrapper("blah");
+    assertEquals("{\"Some Constant String Instance Field\":\""
+        + target.someConstantStringInstanceField + "\"}", gson.toJson(target));
+  }
+
+  public void testGsonWithUpperCamelCaseSpacesPolicyDeserialiation() {
+    Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES)
+        .create();
+    String target = "{\"Some Constant String Instance Field\":\"someValue\"}";
+    StringWrapper deserializedObject = gson.fromJson(target, StringWrapper.class);
+    assertEquals("someValue", deserializedObject.someConstantStringInstanceField);
+  }
+
+  public void testGsonWithUpperCaseUnderscorePolicySerialization() {
+    Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CASE_WITH_UNDERSCORES)
+        .create();
+    StringWrapper target = new StringWrapper("blah");
+    assertEquals("{\"SOME_CONSTANT_STRING_INSTANCE_FIELD\":\""
+        + target.someConstantStringInstanceField + "\"}", gson.toJson(target));
+  }
+
+  public void testGsonWithUpperCaseUnderscorePolicyDeserialiation() {
+    Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CASE_WITH_UNDERSCORES)
+        .create();
+    String target = "{\"SOME_CONSTANT_STRING_INSTANCE_FIELD\":\"someValue\"}";
+    StringWrapper deserializedObject = gson.fromJson(target, StringWrapper.class);
+    assertEquals("someValue", deserializedObject.someConstantStringInstanceField);
+  }
+
+  public void testDeprecatedNamingStrategy() throws Exception {
+    Gson gson = builder.setFieldNamingStrategy(new UpperCaseNamingStrategy()).create();
+    ClassWithDuplicateFields target = new ClassWithDuplicateFields(10);
+    String actual = gson.toJson(target);
+    assertEquals("{\"A\":10}", actual);
+  }
+
+  public void testComplexFieldNameStrategy() throws Exception {
+    Gson gson = new Gson();
+    String json = gson.toJson(new ClassWithComplexFieldName(10));
+    String escapedFieldName = "@value\\\"_s$\\\\";
+    assertEquals("{\"" + escapedFieldName + "\":10}", json);
+
+    ClassWithComplexFieldName obj = gson.fromJson(json, ClassWithComplexFieldName.class);
+    assertEquals(10, obj.value);
+  }
+
+  /** http://code.google.com/p/google-gson/issues/detail?id=349 */
+  public void testAtSignInSerializedName() {
+    assertEquals("{\"@foo\":\"bar\"}", new Gson().toJson(new AtName()));
+  }
+
+  static final class AtName {
+    @SerializedName("@foo") String f = "bar";
+  }
+
+  private static final class UpperCaseNamingStrategy implements FieldNamingStrategy {
+    @Override
+    public String translateName(Field f) {
+      return f.getName().toUpperCase();
+    }
+  }
+
+  @SuppressWarnings("unused")
+  private static class ClassWithDuplicateFields {
+    public Integer a;
+    @SerializedName("a") public Double b;
+
+    public ClassWithDuplicateFields(Integer a) {
+      this(a, null);
+    }
+
+    public ClassWithDuplicateFields(Double b) {
+      this(null, b);
+    }
+
+    public ClassWithDuplicateFields(Integer a, Double b) {
+      this.a = a;
+      this.b = b;
+    }
+  }
+
+  private static class ClassWithComplexFieldName {
+    @SerializedName("@value\"_s$\\") public final long value;
+
+    ClassWithComplexFieldName(long value) {
+      this.value = value;
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/NullObjectAndFieldTest.java b/gson/src/test/java/com/google/gson/functional/NullObjectAndFieldTest.java
new file mode 100644
index 0000000..a9b77f1
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/NullObjectAndFieldTest.java
@@ -0,0 +1,240 @@
+/*

+ * Copyright (C) 2008 Google Inc.

+ *

+ * Licensed under the Apache License, Version 2.0 (the "License");

+ * you may not use this file except in compliance with the License.

+ * You may obtain a copy of the License at

+ *

+ * http://www.apache.org/licenses/LICENSE-2.0

+ *

+ * Unless required by applicable law or agreed to in writing, software

+ * distributed under the License is distributed on an "AS IS" BASIS,

+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

+ * See the License for the specific language governing permissions and

+ * limitations under the License.

+ */

+

+package com.google.gson.functional;

+

+import com.google.gson.Gson;

+import com.google.gson.GsonBuilder;

+import com.google.gson.JsonElement;

+import com.google.gson.JsonNull;

+import com.google.gson.JsonObject;

+import com.google.gson.JsonDeserializationContext;

+import com.google.gson.JsonDeserializer;

+import com.google.gson.JsonSerializationContext;

+import com.google.gson.JsonSerializer;

+import com.google.gson.common.TestTypes.BagOfPrimitives;

+import com.google.gson.common.TestTypes.ClassWithObjects;

+

+import junit.framework.TestCase;

+

+import java.lang.reflect.Type;

+import java.util.Collection;

+

+/**

+ * Functional tests for the different cases for serializing (or ignoring) null fields and object.

+ *

+ * @author Inderjeet Singh

+ * @author Joel Leitch

+ */

+public class NullObjectAndFieldTest extends TestCase {

+  private GsonBuilder gsonBuilder;

+

+  @Override

+  protected void setUp() throws Exception {

+    super.setUp();

+    gsonBuilder = new GsonBuilder().serializeNulls();

+  }

+

+  public void testTopLevelNullObjectSerialization() {

+    Gson gson = gsonBuilder.create();

+    String actual = gson.toJson(null);

+    assertEquals("null", actual);

+

+    actual = gson.toJson(null, String.class);

+    assertEquals("null", actual);

+  }

+

+  public void testTopLevelNullObjectDeserialization() throws Exception {

+    Gson gson = gsonBuilder.create();

+    String actual = gson.fromJson("null", String.class);

+    assertNull(actual);

+  }

+

+  public void testExplicitSerializationOfNulls() {

+    Gson gson = gsonBuilder.create();

+    ClassWithObjects target = new ClassWithObjects(null);

+    String actual = gson.toJson(target);

+    String expected = "{\"bag\":null}";

+    assertEquals(expected, actual);

+  }

+

+  public void testExplicitDeserializationOfNulls() throws Exception {

+    Gson gson = gsonBuilder.create();

+    ClassWithObjects target = gson.fromJson("{\"bag\":null}", ClassWithObjects.class);

+    assertNull(target.bag);

+  }

+  

+  public void testExplicitSerializationOfNullArrayMembers() {

+    Gson gson = gsonBuilder.create();

+    ClassWithMembers target = new ClassWithMembers();

+    String json = gson.toJson(target);

+    assertTrue(json.contains("\"array\":null"));

+  }

+  

+  /** 

+   * Added to verify http://code.google.com/p/google-gson/issues/detail?id=68

+   */

+  public void testNullWrappedPrimitiveMemberSerialization() {

+    Gson gson = gsonBuilder.serializeNulls().create();

+    ClassWithNullWrappedPrimitive target = new ClassWithNullWrappedPrimitive();

+    String json = gson.toJson(target);

+    assertTrue(json.contains("\"value\":null"));

+  }

+  

+  /** 

+   * Added to verify http://code.google.com/p/google-gson/issues/detail?id=68

+   */

+  public void testNullWrappedPrimitiveMemberDeserialization() {

+    Gson gson = gsonBuilder.create();

+    String json = "{'value':null}";

+    ClassWithNullWrappedPrimitive target = gson.fromJson(json, ClassWithNullWrappedPrimitive.class);

+    assertNull(target.value);

+  }

+  

+  public void testExplicitSerializationOfNullCollectionMembers() {

+    Gson gson = gsonBuilder.create();

+    ClassWithMembers target = new ClassWithMembers();

+    String json = gson.toJson(target);

+    assertTrue(json.contains("\"col\":null"));

+  }

+  

+  public void testExplicitSerializationOfNullStringMembers() {

+    Gson gson = gsonBuilder.create();

+    ClassWithMembers target = new ClassWithMembers();

+    String json = gson.toJson(target);

+    assertTrue(json.contains("\"str\":null"));

+  }

+

+  public void testCustomSerializationOfNulls() {

+    gsonBuilder.registerTypeAdapter(ClassWithObjects.class, new ClassWithObjectsSerializer());

+    Gson gson = gsonBuilder.create();

+    ClassWithObjects target = new ClassWithObjects(new BagOfPrimitives());

+    String actual = gson.toJson(target);

+    String expected = "{\"bag\":null}";

+    assertEquals(expected, actual);

+  }

+  

+  public void testPrintPrintingObjectWithNulls() throws Exception {

+    gsonBuilder = new GsonBuilder();

+    Gson gson = gsonBuilder.create();

+    String result = gson.toJson(new ClassWithMembers());

+    assertEquals("{}", result);

+

+    gson = gsonBuilder.serializeNulls().create();

+    result = gson.toJson(new ClassWithMembers());

+    assertTrue(result.contains("\"str\":null"));

+  }

+  

+  public void testPrintPrintingArraysWithNulls() throws Exception {

+    gsonBuilder = new GsonBuilder();

+    Gson gson = gsonBuilder.create();

+    String result = gson.toJson(new String[] { "1", null, "3" });

+    assertEquals("[\"1\",null,\"3\"]", result);

+

+    gson = gsonBuilder.serializeNulls().create();

+    result = gson.toJson(new String[] { "1", null, "3" });

+    assertEquals("[\"1\",null,\"3\"]", result);

+  }

+

+  // test for issue 389

+  public void testAbsentJsonElementsAreSetToNull() {

+    Gson gson = new Gson();

+    ClassWithInitializedMembers target =

+        gson.fromJson("{array:[1,2,3]}", ClassWithInitializedMembers.class);

+    assertTrue(target.array.length == 3 && target.array[1] == 2);

+    assertEquals(ClassWithInitializedMembers.MY_STRING_DEFAULT, target.str1);

+    assertNull(target.str2);

+    assertEquals(ClassWithInitializedMembers.MY_INT_DEFAULT, target.int1);

+    assertEquals(0, target.int2); // test the default value of a primitive int field per JVM spec

+    assertEquals(ClassWithInitializedMembers.MY_BOOLEAN_DEFAULT, target.bool1);

+    assertFalse(target.bool2); // test the default value of a primitive boolean field per JVM spec

+  }

+

+  public static class ClassWithInitializedMembers {

+    // Using a mix of no-args constructor and field initializers

+    // Also, some fields are intialized and some are not (so initialized per JVM spec)

+    public static final String MY_STRING_DEFAULT = "string";

+    private static final int MY_INT_DEFAULT = 2;

+    private static final boolean MY_BOOLEAN_DEFAULT = true;

+    int[] array;

+    String str1, str2;

+    int int1 = MY_INT_DEFAULT;

+    int int2;

+    boolean bool1 = MY_BOOLEAN_DEFAULT;

+    boolean bool2;

+    public ClassWithInitializedMembers() {

+      str1 = MY_STRING_DEFAULT;

+    }

+  }

+

+  private static class ClassWithNullWrappedPrimitive {

+    private Long value;

+  }

+

+  @SuppressWarnings("unused")

+  private static class ClassWithMembers {

+    String str;

+    int[] array;

+    Collection<String> col;

+  }

+  

+  private static class ClassWithObjectsSerializer implements JsonSerializer<ClassWithObjects> {

+    @Override public JsonElement serialize(ClassWithObjects src, Type typeOfSrc,

+        JsonSerializationContext context) {

+      JsonObject obj = new JsonObject();

+      obj.add("bag", JsonNull.INSTANCE);

+      return obj;

+    }

+  }

+

+  public void testExplicitNullSetsFieldToNullDuringDeserialization() {

+    Gson gson = new Gson();

+    String json = "{value:null}";

+    ObjectWithField obj = gson.fromJson(json, ObjectWithField.class);

+    assertNull(obj.value);

+  }

+

+  public void testCustomTypeAdapterPassesNullSerialization() {

+    Gson gson = new GsonBuilder()

+        .registerTypeAdapter(ObjectWithField.class, new JsonSerializer<ObjectWithField>() {

+          @Override public JsonElement serialize(ObjectWithField src, Type typeOfSrc,

+              JsonSerializationContext context) {

+            return context.serialize(null);

+          }

+        }).create();

+    ObjectWithField target = new ObjectWithField();

+    target.value = "value1";

+    String json = gson.toJson(target);

+    assertFalse(json.contains("value1"));

+  }

+

+  public void testCustomTypeAdapterPassesNullDesrialization() {

+    Gson gson = new GsonBuilder()

+        .registerTypeAdapter(ObjectWithField.class, new JsonDeserializer<ObjectWithField>() {

+          @Override public ObjectWithField deserialize(JsonElement json, Type type,

+              JsonDeserializationContext context) {

+            return context.deserialize(null, type);

+          }

+        }).create();

+    String json = "{value:'value1'}";

+    ObjectWithField target = gson.fromJson(json, ObjectWithField.class);

+    assertNull(target);

+  }

+

+  private static class ObjectWithField {

+    String value = "";

+  }

+}

diff --git a/gson/src/test/java/com/google/gson/functional/ObjectTest.java b/gson/src/test/java/com/google/gson/functional/ObjectTest.java
new file mode 100644
index 0000000..e9aa15b
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/ObjectTest.java
@@ -0,0 +1,512 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.functional;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.InstanceCreator;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParseException;
+import com.google.gson.JsonSerializationContext;
+import com.google.gson.JsonSerializer;
+import com.google.gson.common.TestTypes.ArrayOfObjects;
+import com.google.gson.common.TestTypes.BagOfPrimitiveWrappers;
+import com.google.gson.common.TestTypes.BagOfPrimitives;
+import com.google.gson.common.TestTypes.ClassWithArray;
+import com.google.gson.common.TestTypes.ClassWithNoFields;
+import com.google.gson.common.TestTypes.ClassWithObjects;
+import com.google.gson.common.TestTypes.ClassWithTransientFields;
+import com.google.gson.common.TestTypes.Nested;
+import com.google.gson.common.TestTypes.PrimitiveArray;
+import com.google.gson.internal.JavaVersion;
+import com.google.gson.reflect.TypeToken;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.TimeZone;
+
+import junit.framework.TestCase;
+
+/**
+ * Functional tests for Json serialization and deserialization of regular classes.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public class ObjectTest extends TestCase {
+  private Gson gson;
+  private TimeZone oldTimeZone;
+  private Locale oldLocale;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    gson = new Gson();
+
+    oldTimeZone = TimeZone.getDefault();
+    TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles"));
+    oldLocale = Locale.getDefault();
+    Locale.setDefault(Locale.US);
+  }
+
+  @Override
+  protected void tearDown() throws Exception {
+    TimeZone.setDefault(oldTimeZone);
+    Locale.setDefault(oldLocale);
+    super.tearDown();
+  }
+
+  public void testJsonInSingleQuotesDeserialization() {
+    String json = "{'stringValue':'no message','intValue':10,'longValue':20}";
+    BagOfPrimitives target = gson.fromJson(json, BagOfPrimitives.class);
+    assertEquals("no message", target.stringValue);
+    assertEquals(10, target.intValue);
+    assertEquals(20, target.longValue);
+  }
+
+  public void testJsonInMixedQuotesDeserialization() {
+    String json = "{\"stringValue\":'no message','intValue':10,'longValue':20}";
+    BagOfPrimitives target = gson.fromJson(json, BagOfPrimitives.class);
+    assertEquals("no message", target.stringValue);
+    assertEquals(10, target.intValue);
+    assertEquals(20, target.longValue);
+  }
+
+  public void testBagOfPrimitivesSerialization() throws Exception {
+    BagOfPrimitives target = new BagOfPrimitives(10, 20, false, "stringValue");
+    assertEquals(target.getExpectedJson(), gson.toJson(target));
+  }
+
+  public void testBagOfPrimitivesDeserialization() throws Exception {
+    BagOfPrimitives src = new BagOfPrimitives(10, 20, false, "stringValue");
+    String json = src.getExpectedJson();
+    BagOfPrimitives target = gson.fromJson(json, BagOfPrimitives.class);
+    assertEquals(json, target.getExpectedJson());
+  }
+
+  public void testBagOfPrimitiveWrappersSerialization() throws Exception {
+    BagOfPrimitiveWrappers target = new BagOfPrimitiveWrappers(10L, 20, false);
+    assertEquals(target.getExpectedJson(), gson.toJson(target));
+  }
+
+  public void testBagOfPrimitiveWrappersDeserialization() throws Exception {
+    BagOfPrimitiveWrappers target = new BagOfPrimitiveWrappers(10L, 20, false);
+    String jsonString = target.getExpectedJson();
+    target = gson.fromJson(jsonString, BagOfPrimitiveWrappers.class);
+    assertEquals(jsonString, target.getExpectedJson());
+  }
+
+  public void testClassWithTransientFieldsSerialization() throws Exception {
+    ClassWithTransientFields<Long> target = new ClassWithTransientFields<>(1L);
+    assertEquals(target.getExpectedJson(), gson.toJson(target));
+  }
+
+  @SuppressWarnings("rawtypes")
+  public void testClassWithTransientFieldsDeserialization() throws Exception {
+    String json = "{\"longValue\":[1]}";
+    ClassWithTransientFields target = gson.fromJson(json, ClassWithTransientFields.class);
+    assertEquals(json, target.getExpectedJson());
+  }
+
+  @SuppressWarnings("rawtypes")
+  public void testClassWithTransientFieldsDeserializationTransientFieldsPassedInJsonAreIgnored()
+      throws Exception {
+    String json = "{\"transientLongValue\":1,\"longValue\":[1]}";
+    ClassWithTransientFields target = gson.fromJson(json, ClassWithTransientFields.class);
+    assertFalse(target.transientLongValue != 1);
+  }
+
+  public void testClassWithNoFieldsSerialization() throws Exception {
+    assertEquals("{}", gson.toJson(new ClassWithNoFields()));
+  }
+
+  public void testClassWithNoFieldsDeserialization() throws Exception {
+    String json = "{}";
+    ClassWithNoFields target = gson.fromJson(json, ClassWithNoFields.class);
+    ClassWithNoFields expected = new ClassWithNoFields();
+    assertEquals(expected, target);
+  }
+
+  public void testNestedSerialization() throws Exception {
+    Nested target = new Nested(new BagOfPrimitives(10, 20, false, "stringValue"),
+       new BagOfPrimitives(30, 40, true, "stringValue"));
+    assertEquals(target.getExpectedJson(), gson.toJson(target));
+  }
+
+  public void testNestedDeserialization() throws Exception {
+    String json = "{\"primitive1\":{\"longValue\":10,\"intValue\":20,\"booleanValue\":false,"
+        + "\"stringValue\":\"stringValue\"},\"primitive2\":{\"longValue\":30,\"intValue\":40,"
+        + "\"booleanValue\":true,\"stringValue\":\"stringValue\"}}";
+    Nested target = gson.fromJson(json, Nested.class);
+    assertEquals(json, target.getExpectedJson());
+  }
+  public void testNullSerialization() throws Exception {
+    assertEquals("null", gson.toJson(null));
+  }
+
+  public void testEmptyStringDeserialization() throws Exception {
+    Object object = gson.fromJson("", Object.class);
+    assertNull(object);
+  }
+
+  public void testTruncatedDeserialization() {
+    try {
+      gson.fromJson("[\"a\", \"b\",", new TypeToken<List<String>>() {}.getType());
+      fail();
+    } catch (JsonParseException expected) {
+    }
+  }
+
+  public void testNullDeserialization() throws Exception {
+    String myNullObject = null;
+    Object object = gson.fromJson(myNullObject, Object.class);
+    assertNull(object);
+  }
+
+  public void testNullFieldsSerialization() throws Exception {
+    Nested target = new Nested(new BagOfPrimitives(10, 20, false, "stringValue"), null);
+    assertEquals(target.getExpectedJson(), gson.toJson(target));
+  }
+
+  public void testNullFieldsDeserialization() throws Exception {
+    String json = "{\"primitive1\":{\"longValue\":10,\"intValue\":20,\"booleanValue\":false"
+        + ",\"stringValue\":\"stringValue\"}}";
+    Nested target = gson.fromJson(json, Nested.class);
+    assertEquals(json, target.getExpectedJson());
+  }
+
+  public void testArrayOfObjectsSerialization() throws Exception {
+    ArrayOfObjects target = new ArrayOfObjects();
+    assertEquals(target.getExpectedJson(), gson.toJson(target));
+  }
+
+  public void testArrayOfObjectsDeserialization() throws Exception {
+    String json = new ArrayOfObjects().getExpectedJson();
+    ArrayOfObjects target = gson.fromJson(json, ArrayOfObjects.class);
+    assertEquals(json, target.getExpectedJson());
+  }
+
+  public void testArrayOfArraysSerialization() throws Exception {
+    ArrayOfArrays target = new ArrayOfArrays();
+    assertEquals(target.getExpectedJson(), gson.toJson(target));
+  }
+
+  public void testArrayOfArraysDeserialization() throws Exception {
+    String json = new ArrayOfArrays().getExpectedJson();
+    ArrayOfArrays target = gson.fromJson(json, ArrayOfArrays.class);
+    assertEquals(json, target.getExpectedJson());
+  }
+
+  public void testArrayOfObjectsAsFields() throws Exception {
+    ClassWithObjects classWithObjects = new ClassWithObjects();
+    BagOfPrimitives bagOfPrimitives = new BagOfPrimitives();
+    String stringValue = "someStringValueInArray";
+    String classWithObjectsJson = gson.toJson(classWithObjects);
+    String bagOfPrimitivesJson = gson.toJson(bagOfPrimitives);
+
+    ClassWithArray classWithArray = new ClassWithArray(
+        new Object[] { stringValue, classWithObjects, bagOfPrimitives });
+    String json = gson.toJson(classWithArray);
+
+    assertTrue(json.contains(classWithObjectsJson));
+    assertTrue(json.contains(bagOfPrimitivesJson));
+    assertTrue(json.contains("\"" + stringValue + "\""));
+  }
+
+  /**
+   * Created in response to Issue 14: http://code.google.com/p/google-gson/issues/detail?id=14
+   */
+  public void testNullArraysDeserialization() throws Exception {
+    String json = "{\"array\": null}";
+    ClassWithArray target = gson.fromJson(json, ClassWithArray.class);
+    assertNull(target.array);
+  }
+
+  /**
+   * Created in response to Issue 14: http://code.google.com/p/google-gson/issues/detail?id=14
+   */
+  public void testNullObjectFieldsDeserialization() throws Exception {
+    String json = "{\"bag\": null}";
+    ClassWithObjects target = gson.fromJson(json, ClassWithObjects.class);
+    assertNull(target.bag);
+  }
+
+  public void testEmptyCollectionInAnObjectDeserialization() throws Exception {
+    String json = "{\"children\":[]}";
+    ClassWithCollectionField target = gson.fromJson(json, ClassWithCollectionField.class);
+    assertNotNull(target);
+    assertTrue(target.children.isEmpty());
+  }
+
+  private static class ClassWithCollectionField {
+    Collection<String> children = new ArrayList<>();
+  }
+
+  public void testPrimitiveArrayInAnObjectDeserialization() throws Exception {
+    String json = "{\"longArray\":[0,1,2,3,4,5,6,7,8,9]}";
+    PrimitiveArray target = gson.fromJson(json, PrimitiveArray.class);
+    assertEquals(json, target.getExpectedJson());
+  }
+
+  /**
+   * Created in response to Issue 14: http://code.google.com/p/google-gson/issues/detail?id=14
+   */
+  public void testNullPrimitiveFieldsDeserialization() throws Exception {
+    String json = "{\"longValue\":null}";
+    BagOfPrimitives target = gson.fromJson(json, BagOfPrimitives.class);
+    assertEquals(BagOfPrimitives.DEFAULT_VALUE, target.longValue);
+  }
+
+  public void testEmptyCollectionInAnObjectSerialization() throws Exception {
+    ClassWithCollectionField target = new ClassWithCollectionField();
+    assertEquals("{\"children\":[]}", gson.toJson(target));
+  }
+
+  public void testPrivateNoArgConstructorDeserialization() throws Exception {
+    ClassWithPrivateNoArgsConstructor target =
+      gson.fromJson("{\"a\":20}", ClassWithPrivateNoArgsConstructor.class);
+    assertEquals(20, target.a);
+  }
+
+  public void testAnonymousLocalClassesSerialization() throws Exception {
+    assertEquals("null", gson.toJson(new ClassWithNoFields() {
+      // empty anonymous class
+    }));
+  }
+
+  public void testAnonymousLocalClassesCustomSerialization() throws Exception {
+    gson = new GsonBuilder()
+        .registerTypeHierarchyAdapter(ClassWithNoFields.class,
+            new JsonSerializer<ClassWithNoFields>() {
+              @Override public JsonElement serialize(
+                  ClassWithNoFields src, Type typeOfSrc, JsonSerializationContext context) {
+                return new JsonObject();
+              }
+            }).create();
+
+    assertEquals("null", gson.toJson(new ClassWithNoFields() {
+      // empty anonymous class
+    }));
+  }
+
+  public void testPrimitiveArrayFieldSerialization() {
+    PrimitiveArray target = new PrimitiveArray(new long[] { 1L, 2L, 3L });
+    assertEquals(target.getExpectedJson(), gson.toJson(target));
+  }
+
+  /**
+   * Tests that a class field with type Object can be serialized properly.
+   * See issue 54
+   */
+  public void testClassWithObjectFieldSerialization() {
+    ClassWithObjectField obj = new ClassWithObjectField();
+    obj.member = "abc";
+    String json = gson.toJson(obj);
+    assertTrue(json.contains("abc"));
+  }
+
+  private static class ClassWithObjectField {
+    @SuppressWarnings("unused")
+    Object member;
+  }
+
+  public void testInnerClassSerialization() {
+    Parent p = new Parent();
+    Parent.Child c = p.new Child();
+    String json = gson.toJson(c);
+    assertTrue(json.contains("value2"));
+    assertFalse(json.contains("value1"));
+  }
+
+  public void testInnerClassDeserialization() {
+    final Parent p = new Parent();
+    Gson gson = new GsonBuilder().registerTypeAdapter(
+        Parent.Child.class, new InstanceCreator<Parent.Child>() {
+      @Override public Parent.Child createInstance(Type type) {
+        return p.new Child();
+      }
+    }).create();
+    String json = "{'value2':3}";
+    Parent.Child c = gson.fromJson(json, Parent.Child.class);
+    assertEquals(3, c.value2);
+  }
+
+  private static class Parent {
+    @SuppressWarnings("unused")
+    int value1 = 1;
+    private class Child {
+      int value2 = 2;
+    }
+  }
+
+  private static class ArrayOfArrays {
+    private final BagOfPrimitives[][] elements;
+    public ArrayOfArrays() {
+      elements = new BagOfPrimitives[3][2];
+      for (int i = 0; i < elements.length; ++i) {
+        BagOfPrimitives[] row = elements[i];
+        for (int j = 0; j < row.length; ++j) {
+          row[j] = new BagOfPrimitives(i+j, i*j, false, i+"_"+j);
+        }
+      }
+    }
+    public String getExpectedJson() {
+      StringBuilder sb = new StringBuilder("{\"elements\":[");
+      boolean first = true;
+      for (BagOfPrimitives[] row : elements) {
+        if (first) {
+          first = false;
+        } else {
+          sb.append(",");
+        }
+        boolean firstOfRow = true;
+        sb.append("[");
+        for (BagOfPrimitives element : row) {
+          if (firstOfRow) {
+            firstOfRow = false;
+          } else {
+            sb.append(",");
+          }
+          sb.append(element.getExpectedJson());
+        }
+        sb.append("]");
+      }
+      sb.append("]}");
+      return sb.toString();
+    }
+  }
+
+  private static class ClassWithPrivateNoArgsConstructor {
+    public int a;
+    private ClassWithPrivateNoArgsConstructor() {
+      a = 10;
+    }
+  }
+
+  /**
+   * In response to Issue 41 http://code.google.com/p/google-gson/issues/detail?id=41
+   */
+  public void testObjectFieldNamesWithoutQuotesDeserialization() {
+    String json = "{longValue:1,'booleanValue':true,\"stringValue\":'bar'}";
+    BagOfPrimitives bag = gson.fromJson(json, BagOfPrimitives.class);
+    assertEquals(1, bag.longValue);
+    assertTrue(bag.booleanValue);
+    assertEquals("bar", bag.stringValue);
+  }
+
+  public void testStringFieldWithNumberValueDeserialization() {
+    String json = "{\"stringValue\":1}";
+    BagOfPrimitives bag = gson.fromJson(json, BagOfPrimitives.class);
+    assertEquals("1", bag.stringValue);
+
+    json = "{\"stringValue\":1.5E+6}";
+    bag = gson.fromJson(json, BagOfPrimitives.class);
+    assertEquals("1.5E+6", bag.stringValue);
+
+    json = "{\"stringValue\":true}";
+    bag = gson.fromJson(json, BagOfPrimitives.class);
+    assertEquals("true", bag.stringValue);
+  }
+
+  /**
+   * Created to reproduce issue 140
+   */
+  public void testStringFieldWithEmptyValueSerialization() {
+    ClassWithEmptyStringFields target = new ClassWithEmptyStringFields();
+    target.a = "5794749";
+    String json = gson.toJson(target);
+    assertTrue(json.contains("\"a\":\"5794749\""));
+    assertTrue(json.contains("\"b\":\"\""));
+    assertTrue(json.contains("\"c\":\"\""));
+  }
+
+  /**
+   * Created to reproduce issue 140
+   */
+  public void testStringFieldWithEmptyValueDeserialization() {
+    String json = "{a:\"5794749\",b:\"\",c:\"\"}";
+    ClassWithEmptyStringFields target = gson.fromJson(json, ClassWithEmptyStringFields.class);
+    assertEquals("5794749", target.a);
+    assertEquals("", target.b);
+    assertEquals("", target.c);
+  }
+
+  private static class ClassWithEmptyStringFields {
+    String a = "";
+    String b = "";
+    String c = "";
+  }
+
+  public void testJsonObjectSerialization() {
+    Gson gson = new GsonBuilder().serializeNulls().create();
+    JsonObject obj = new JsonObject();
+    String json = gson.toJson(obj);
+    assertEquals("{}", json);
+  }
+
+  /**
+   * Test for issue 215.
+   */
+  public void testSingletonLists() {
+    Gson gson = new Gson();
+    Product product = new Product();
+    assertEquals("{\"attributes\":[],\"departments\":[]}",
+        gson.toJson(product));
+    gson.fromJson(gson.toJson(product), Product.class);
+
+    product.departments.add(new Department());
+    assertEquals("{\"attributes\":[],\"departments\":[{\"name\":\"abc\",\"code\":\"123\"}]}",
+        gson.toJson(product));
+    gson.fromJson(gson.toJson(product), Product.class);
+
+    product.attributes.add("456");
+    assertEquals("{\"attributes\":[\"456\"],\"departments\":[{\"name\":\"abc\",\"code\":\"123\"}]}",
+        gson.toJson(product));
+    gson.fromJson(gson.toJson(product), Product.class);
+  }
+
+  // http://code.google.com/p/google-gson/issues/detail?id=270
+  public void testDateAsMapObjectField() {
+    HasObjectMap a = new HasObjectMap();
+    a.map.put("date", new Date(0));
+    if (JavaVersion.isJava9OrLater()) {
+      assertEquals("{\"map\":{\"date\":\"Dec 31, 1969, 4:00:00 PM\"}}", gson.toJson(a));
+    } else {
+      assertEquals("{\"map\":{\"date\":\"Dec 31, 1969 4:00:00 PM\"}}", gson.toJson(a));
+    }
+  }
+
+  public class HasObjectMap {
+    Map<String, Object> map = new HashMap<>();
+  }
+
+  static final class Department {
+    public String name = "abc";
+    public String code = "123";
+  }
+
+  static final class Product {
+    private List<String> attributes = new ArrayList<>();
+    private List<Department> departments = new ArrayList<>();
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/ParameterizedTypesTest.java b/gson/src/test/java/com/google/gson/functional/ParameterizedTypesTest.java
new file mode 100644
index 0000000..8decc64
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/ParameterizedTypesTest.java
@@ -0,0 +1,500 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.functional;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.ParameterizedTypeFixtures.MyParameterizedType;
+import com.google.gson.ParameterizedTypeFixtures.MyParameterizedTypeAdapter;
+import com.google.gson.ParameterizedTypeFixtures.MyParameterizedTypeInstanceCreator;
+import com.google.gson.common.TestTypes.BagOfPrimitives;
+import com.google.gson.reflect.TypeToken;
+
+import junit.framework.TestCase;
+
+import java.io.Reader;
+import java.io.Serializable;
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.io.Writer;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * Functional tests for the serialization and deserialization of parameterized types in Gson.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public class ParameterizedTypesTest extends TestCase {
+  private Gson gson;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    gson = new Gson();
+  }
+
+  public void testParameterizedTypesSerialization() throws Exception {
+    MyParameterizedType<Integer> src = new MyParameterizedType<>(10);
+    Type typeOfSrc = new TypeToken<MyParameterizedType<Integer>>() {}.getType();
+    String json = gson.toJson(src, typeOfSrc);
+    assertEquals(src.getExpectedJson(), json);
+  }
+
+  public void testParameterizedTypeDeserialization() throws Exception {
+    BagOfPrimitives bag = new BagOfPrimitives();
+    MyParameterizedType<BagOfPrimitives> expected = new MyParameterizedType<>(bag);
+    Type expectedType = new TypeToken<MyParameterizedType<BagOfPrimitives>>() {}.getType();
+    BagOfPrimitives bagDefaultInstance = new BagOfPrimitives();
+    Gson gson = new GsonBuilder().registerTypeAdapter(
+        expectedType, new MyParameterizedTypeInstanceCreator<>(bagDefaultInstance))
+        .create();
+
+    String json = expected.getExpectedJson();
+    MyParameterizedType<BagOfPrimitives> actual = gson.fromJson(json, expectedType);
+    assertEquals(expected, actual);
+  }
+
+  public void testTypesWithMultipleParametersSerialization() throws Exception {
+    MultiParameters<Integer, Float, Double, String, BagOfPrimitives> src =
+        new MultiParameters<>(10, 1.0F, 2.1D, "abc", new BagOfPrimitives());
+    Type typeOfSrc = new TypeToken<MultiParameters<Integer, Float, Double, String,
+        BagOfPrimitives>>() {}.getType();
+    String json = gson.toJson(src, typeOfSrc);
+    String expected = "{\"a\":10,\"b\":1.0,\"c\":2.1,\"d\":\"abc\","
+        + "\"e\":{\"longValue\":0,\"intValue\":0,\"booleanValue\":false,\"stringValue\":\"\"}}";
+    assertEquals(expected, json);
+  }
+
+  public void testTypesWithMultipleParametersDeserialization() throws Exception {
+    Type typeOfTarget = new TypeToken<MultiParameters<Integer, Float, Double, String,
+        BagOfPrimitives>>() {}.getType();
+    String json = "{\"a\":10,\"b\":1.0,\"c\":2.1,\"d\":\"abc\","
+        + "\"e\":{\"longValue\":0,\"intValue\":0,\"booleanValue\":false,\"stringValue\":\"\"}}";
+    MultiParameters<Integer, Float, Double, String, BagOfPrimitives> target =
+        gson.fromJson(json, typeOfTarget);
+    MultiParameters<Integer, Float, Double, String, BagOfPrimitives> expected =
+        new MultiParameters<>(10, 1.0F, 2.1D, "abc", new BagOfPrimitives());
+    assertEquals(expected, target);
+  }
+
+  public void testParameterizedTypeWithCustomSerializer() {
+    Type ptIntegerType = new TypeToken<MyParameterizedType<Integer>>() {}.getType();
+    Type ptStringType = new TypeToken<MyParameterizedType<String>>() {}.getType();
+    Gson gson = new GsonBuilder()
+        .registerTypeAdapter(ptIntegerType, new MyParameterizedTypeAdapter<Integer>())
+        .registerTypeAdapter(ptStringType, new MyParameterizedTypeAdapter<String>())
+        .create();
+    MyParameterizedType<Integer> intTarget = new MyParameterizedType<>(10);
+    String json = gson.toJson(intTarget, ptIntegerType);
+    assertEquals(MyParameterizedTypeAdapter.<Integer>getExpectedJson(intTarget), json);
+
+    MyParameterizedType<String> stringTarget = new MyParameterizedType<>("abc");
+    json = gson.toJson(stringTarget, ptStringType);
+    assertEquals(MyParameterizedTypeAdapter.<String>getExpectedJson(stringTarget), json);
+  }
+
+  public void testParameterizedTypesWithCustomDeserializer() {
+    Type ptIntegerType = new TypeToken<MyParameterizedType<Integer>>() {}.getType();
+    Type ptStringType = new TypeToken<MyParameterizedType<String>>() {}.getType();
+    Gson gson = new GsonBuilder().registerTypeAdapter(
+        ptIntegerType, new MyParameterizedTypeAdapter<Integer>())
+        .registerTypeAdapter(ptStringType, new MyParameterizedTypeAdapter<String>())
+        .registerTypeAdapter(ptStringType, new MyParameterizedTypeInstanceCreator<>(""))
+        .registerTypeAdapter(ptIntegerType, new MyParameterizedTypeInstanceCreator<>(0))
+        .create();
+
+    MyParameterizedType<Integer> src = new MyParameterizedType<>(10);
+    String json = MyParameterizedTypeAdapter.<Integer>getExpectedJson(src);
+    MyParameterizedType<Integer> intTarget = gson.fromJson(json, ptIntegerType);
+    assertEquals(10, intTarget.value.intValue());
+
+    MyParameterizedType<String> srcStr = new MyParameterizedType<>("abc");
+    json = MyParameterizedTypeAdapter.<String>getExpectedJson(srcStr);
+    MyParameterizedType<String> stringTarget = gson.fromJson(json, ptStringType);
+    assertEquals("abc", stringTarget.value);
+  }
+
+  public void testParameterizedTypesWithWriterSerialization() throws Exception {
+    Writer writer = new StringWriter();
+    MyParameterizedType<Integer> src = new MyParameterizedType<>(10);
+    Type typeOfSrc = new TypeToken<MyParameterizedType<Integer>>() {}.getType();
+    gson.toJson(src, typeOfSrc, writer);
+    assertEquals(src.getExpectedJson(), writer.toString());
+  }
+
+  public void testParameterizedTypeWithReaderDeserialization() throws Exception {
+    BagOfPrimitives bag = new BagOfPrimitives();
+    MyParameterizedType<BagOfPrimitives> expected = new MyParameterizedType<>(bag);
+    Type expectedType = new TypeToken<MyParameterizedType<BagOfPrimitives>>() {}.getType();
+    BagOfPrimitives bagDefaultInstance = new BagOfPrimitives();
+    Gson gson = new GsonBuilder().registerTypeAdapter(
+        expectedType, new MyParameterizedTypeInstanceCreator<>(bagDefaultInstance))
+        .create();
+
+    Reader json = new StringReader(expected.getExpectedJson());
+    MyParameterizedType<Integer> actual = gson.fromJson(json, expectedType);
+    assertEquals(expected, actual);
+  }
+
+  @SuppressWarnings("unchecked")
+  public void testVariableTypeFieldsAndGenericArraysSerialization() throws Exception {
+    Integer obj = 0;
+    Integer[] array = { 1, 2, 3 };
+    List<Integer> list = new ArrayList<>();
+    list.add(4);
+    list.add(5);
+    List<Integer>[] arrayOfLists = new List[] { list, list };
+
+    Type typeOfSrc = new TypeToken<ObjectWithTypeVariables<Integer>>() {}.getType();
+    ObjectWithTypeVariables<Integer> objToSerialize =
+        new ObjectWithTypeVariables<>(obj, array, list, arrayOfLists, list, arrayOfLists);
+    String json = gson.toJson(objToSerialize, typeOfSrc);
+
+    assertEquals(objToSerialize.getExpectedJson(), json);
+  }
+
+  @SuppressWarnings("unchecked")
+  public void testVariableTypeFieldsAndGenericArraysDeserialization() throws Exception {
+    Integer obj = 0;
+    Integer[] array = { 1, 2, 3 };
+    List<Integer> list = new ArrayList<>();
+    list.add(4);
+    list.add(5);
+    List<Integer>[] arrayOfLists = new List[] { list, list };
+
+    Type typeOfSrc = new TypeToken<ObjectWithTypeVariables<Integer>>() {}.getType();
+    ObjectWithTypeVariables<Integer> objToSerialize =
+        new ObjectWithTypeVariables<>(obj, array, list, arrayOfLists, list, arrayOfLists);
+    String json = gson.toJson(objToSerialize, typeOfSrc);
+    ObjectWithTypeVariables<Integer> objAfterDeserialization = gson.fromJson(json, typeOfSrc);
+
+    assertEquals(objAfterDeserialization.getExpectedJson(), json);
+  }
+
+  public void testVariableTypeDeserialization() throws Exception {
+    Type typeOfSrc = new TypeToken<ObjectWithTypeVariables<Integer>>() {}.getType();
+    ObjectWithTypeVariables<Integer> objToSerialize =
+        new ObjectWithTypeVariables<>(0, null, null, null, null, null);
+    String json = gson.toJson(objToSerialize, typeOfSrc);
+    ObjectWithTypeVariables<Integer> objAfterDeserialization = gson.fromJson(json, typeOfSrc);
+
+    assertEquals(objAfterDeserialization.getExpectedJson(), json);
+  }
+
+  public void testVariableTypeArrayDeserialization() throws Exception {
+    Integer[] array = { 1, 2, 3 };
+
+    Type typeOfSrc = new TypeToken<ObjectWithTypeVariables<Integer>>() {}.getType();
+    ObjectWithTypeVariables<Integer> objToSerialize =
+        new ObjectWithTypeVariables<>(null, array, null, null, null, null);
+    String json = gson.toJson(objToSerialize, typeOfSrc);
+    ObjectWithTypeVariables<Integer> objAfterDeserialization = gson.fromJson(json, typeOfSrc);
+
+    assertEquals(objAfterDeserialization.getExpectedJson(), json);
+  }
+
+  public void testParameterizedTypeWithVariableTypeDeserialization() throws Exception {
+    List<Integer> list = new ArrayList<>();
+    list.add(4);
+    list.add(5);
+
+    Type typeOfSrc = new TypeToken<ObjectWithTypeVariables<Integer>>() {}.getType();
+    ObjectWithTypeVariables<Integer> objToSerialize =
+        new ObjectWithTypeVariables<>(null, null, list, null, null, null);
+    String json = gson.toJson(objToSerialize, typeOfSrc);
+    ObjectWithTypeVariables<Integer> objAfterDeserialization = gson.fromJson(json, typeOfSrc);
+
+    assertEquals(objAfterDeserialization.getExpectedJson(), json);
+  }
+
+  @SuppressWarnings("unchecked")
+  public void testParameterizedTypeGenericArraysSerialization() throws Exception {
+    List<Integer> list = new ArrayList<>();
+    list.add(1);
+    list.add(2);
+    List<Integer>[] arrayOfLists = new List[] { list, list };
+
+    Type typeOfSrc = new TypeToken<ObjectWithTypeVariables<Integer>>() {}.getType();
+    ObjectWithTypeVariables<Integer> objToSerialize =
+        new ObjectWithTypeVariables<>(null, null, null, arrayOfLists, null, null);
+    String json = gson.toJson(objToSerialize, typeOfSrc);
+    assertEquals("{\"arrayOfListOfTypeParameters\":[[1,2],[1,2]]}", json);
+  }
+
+  @SuppressWarnings("unchecked")
+  public void testParameterizedTypeGenericArraysDeserialization() throws Exception {
+    List<Integer> list = new ArrayList<>();
+    list.add(1);
+    list.add(2);
+    List<Integer>[] arrayOfLists = new List[] { list, list };
+
+    Type typeOfSrc = new TypeToken<ObjectWithTypeVariables<Integer>>() {}.getType();
+    ObjectWithTypeVariables<Integer> objToSerialize =
+        new ObjectWithTypeVariables<>(null, null, null, arrayOfLists, null, null);
+    String json = gson.toJson(objToSerialize, typeOfSrc);
+    ObjectWithTypeVariables<Integer> objAfterDeserialization = gson.fromJson(json, typeOfSrc);
+
+    assertEquals(objAfterDeserialization.getExpectedJson(), json);
+  }
+
+  /**
+   * An test object that has fields that are type variables.
+   *
+   * @param <T> Enforce T to be a string to make writing the "toExpectedJson" method easier.
+   */
+  private static class ObjectWithTypeVariables<T extends Number> {
+    private final T typeParameterObj;
+    private final T[] typeParameterArray;
+    private final List<T> listOfTypeParameters;
+    private final List<T>[] arrayOfListOfTypeParameters;
+    private final List<? extends T> listOfWildcardTypeParameters;
+    private final List<? extends T>[] arrayOfListOfWildcardTypeParameters;
+
+    // For use by Gson
+    @SuppressWarnings("unused")
+    private ObjectWithTypeVariables() {
+      this(null, null, null, null, null, null);
+    }
+
+    public ObjectWithTypeVariables(T obj, T[] array, List<T> list, List<T>[] arrayOfList,
+        List<? extends T> wildcardList, List<? extends T>[] arrayOfWildcardList) {
+      this.typeParameterObj = obj;
+      this.typeParameterArray = array;
+      this.listOfTypeParameters = list;
+      this.arrayOfListOfTypeParameters = arrayOfList;
+      this.listOfWildcardTypeParameters = wildcardList;
+      this.arrayOfListOfWildcardTypeParameters = arrayOfWildcardList;
+    }
+
+    public String getExpectedJson() {
+      StringBuilder sb = new StringBuilder().append("{");
+
+      boolean needsComma = false;
+      if (typeParameterObj != null) {
+        sb.append("\"typeParameterObj\":").append(toString(typeParameterObj));
+        needsComma = true;
+      }
+
+      if (typeParameterArray != null) {
+        if (needsComma) {
+          sb.append(',');
+        }
+        sb.append("\"typeParameterArray\":[");
+        appendObjectsToBuilder(sb, Arrays.asList(typeParameterArray));
+        sb.append(']');
+        needsComma = true;
+      }
+
+      if (listOfTypeParameters != null) {
+        if (needsComma) {
+          sb.append(',');
+        }
+        sb.append("\"listOfTypeParameters\":[");
+        appendObjectsToBuilder(sb, listOfTypeParameters);
+        sb.append(']');
+        needsComma = true;
+      }
+
+      if (arrayOfListOfTypeParameters != null) {
+        if (needsComma) {
+          sb.append(',');
+        }
+        sb.append("\"arrayOfListOfTypeParameters\":[");
+        appendObjectsToBuilder(sb, arrayOfListOfTypeParameters);
+        sb.append(']');
+        needsComma = true;
+      }
+
+      if (listOfWildcardTypeParameters != null) {
+        if (needsComma) {
+          sb.append(',');
+        }
+        sb.append("\"listOfWildcardTypeParameters\":[");
+        appendObjectsToBuilder(sb, listOfWildcardTypeParameters);
+        sb.append(']');
+        needsComma = true;
+      }
+
+      if (arrayOfListOfWildcardTypeParameters != null) {
+        if (needsComma) {
+          sb.append(',');
+        }
+        sb.append("\"arrayOfListOfWildcardTypeParameters\":[");
+        appendObjectsToBuilder(sb, arrayOfListOfWildcardTypeParameters);
+        sb.append(']');
+        needsComma = true;
+      }
+      sb.append('}');
+      return sb.toString();
+    }
+
+    private void appendObjectsToBuilder(StringBuilder sb, Iterable<? extends T> iterable) {
+      boolean isFirst = true;
+      for (T obj : iterable) {
+        if (!isFirst) {
+          sb.append(',');
+        }
+        isFirst = false;
+        sb.append(toString(obj));
+      }
+    }
+
+    private void appendObjectsToBuilder(StringBuilder sb, List<? extends T>[] arrayOfList) {
+      boolean isFirst = true;
+      for (List<? extends T> list : arrayOfList) {
+        if (!isFirst) {
+          sb.append(',');
+        }
+        isFirst = false;
+        if (list != null) {
+          sb.append('[');
+          appendObjectsToBuilder(sb, list);
+          sb.append(']');
+        } else {
+          sb.append("null");
+        }
+      }
+    }
+
+    public String toString(T obj) {
+      return obj.toString();
+    }
+  }
+
+  private static class MultiParameters<A, B, C, D, E> {
+    A a;
+    B b;
+    C c;
+    D d;
+    E e;
+    // For use by Gson
+    @SuppressWarnings("unused")
+    private MultiParameters() {
+    }
+    MultiParameters(A a, B b, C c, D d, E e) {
+      super();
+      this.a = a;
+      this.b = b;
+      this.c = c;
+      this.d = d;
+      this.e = e;
+    }
+    @Override
+    public int hashCode() {
+      final int prime = 31;
+      int result = 1;
+      result = prime * result + ((a == null) ? 0 : a.hashCode());
+      result = prime * result + ((b == null) ? 0 : b.hashCode());
+      result = prime * result + ((c == null) ? 0 : c.hashCode());
+      result = prime * result + ((d == null) ? 0 : d.hashCode());
+      result = prime * result + ((e == null) ? 0 : e.hashCode());
+      return result;
+    }
+    @Override
+    @SuppressWarnings("unchecked")
+    public boolean equals(Object obj) {
+      if (this == obj) {
+        return true;
+      }
+      if (obj == null) {
+        return false;
+      }
+      if (getClass() != obj.getClass()) {
+        return false;
+      }
+      MultiParameters<A, B, C, D, E> other = (MultiParameters<A, B, C, D, E>) obj;
+      if (a == null) {
+        if (other.a != null) {
+          return false;
+        }
+      } else if (!a.equals(other.a)) {
+        return false;
+      }
+      if (b == null) {
+        if (other.b != null) {
+          return false;
+        }
+      } else if (!b.equals(other.b)) {
+        return false;
+      }
+      if (c == null) {
+        if (other.c != null) {
+          return false;
+        }
+      } else if (!c.equals(other.c)) {
+        return false;
+      }
+      if (d == null) {
+        if (other.d != null) {
+          return false;
+        }
+      } else if (!d.equals(other.d)) {
+        return false;
+      }
+      if (e == null) {
+        if (other.e != null) {
+          return false;
+        }
+      } else if (!e.equals(other.e)) {
+        return false;
+      }
+      return true;
+    }
+  }
+  
+  // Begin: tests to reproduce issue 103
+  private static class Quantity {
+    @SuppressWarnings("unused")
+    int q = 10;
+  }
+  private static class MyQuantity extends Quantity {
+    @SuppressWarnings("unused")
+    int q2 = 20;
+  }
+  private interface Measurable<T> {
+  }
+  private interface Field<T> {
+  }
+  private interface Immutable {
+  }
+  
+  public static final class Amount<Q extends Quantity> 
+      implements Measurable<Q>, Field<Amount<?>>, Serializable, Immutable {
+    private static final long serialVersionUID = -7560491093120970437L;
+
+    int value = 30;
+  }
+  
+  public void testDeepParameterizedTypeSerialization() {
+    Amount<MyQuantity> amount = new Amount<>();
+    String json = gson.toJson(amount);
+    assertTrue(json.contains("value"));
+    assertTrue(json.contains("30"));
+  }
+  
+  public void testDeepParameterizedTypeDeserialization() {
+    String json = "{value:30}";
+    Type type = new TypeToken<Amount<MyQuantity>>() {}.getType();
+    Amount<MyQuantity> amount = gson.fromJson(json, type);
+    assertEquals(30, amount.value);
+  }
+  // End: tests to reproduce issue 103
+}
diff --git a/gson/src/test/java/com/google/gson/functional/PrettyPrintingTest.java b/gson/src/test/java/com/google/gson/functional/PrettyPrintingTest.java
new file mode 100644
index 0000000..58827b4
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/PrettyPrintingTest.java
@@ -0,0 +1,123 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.functional;
+
+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 junit.framework.TestCase;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.common.TestTypes.ArrayOfObjects;
+import com.google.gson.common.TestTypes.BagOfPrimitives;
+import com.google.gson.reflect.TypeToken;
+
+/**
+ * Functional tests for pretty printing option.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public class PrettyPrintingTest extends TestCase {
+
+  private static final boolean DEBUG = false;
+
+  private Gson gson;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    gson = new GsonBuilder().setPrettyPrinting().create();
+  }
+
+  public void testPrettyPrintList() {
+    BagOfPrimitives b = new BagOfPrimitives();
+    List<BagOfPrimitives> listOfB = new LinkedList<>();
+    for (int i = 0; i < 15; ++i) {
+      listOfB.add(b);
+    }
+    Type typeOfSrc = new TypeToken<List<BagOfPrimitives>>() {}.getType();
+    String json = gson.toJson(listOfB, typeOfSrc);
+    print(json);
+  }
+
+  public void testPrettyPrintArrayOfObjects() {
+    ArrayOfObjects target = new ArrayOfObjects();
+    String json = gson.toJson(target);
+    print(json);
+  }
+
+  public void testPrettyPrintArrayOfPrimitives() {
+    int[] ints = new int[] { 1, 2, 3, 4, 5 };
+    String json = gson.toJson(ints);
+    assertEquals("[\n  1,\n  2,\n  3,\n  4,\n  5\n]", json);
+  }
+
+  public void testPrettyPrintArrayOfPrimitiveArrays() {
+    int[][] ints = new int[][] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 },
+        { 9, 0 }, { 10 } };
+    String json = gson.toJson(ints);
+    assertEquals("[\n  [\n    1,\n    2\n  ],\n  [\n    3,\n    4\n  ],\n  [\n    5,\n    6\n  ],"
+        + "\n  [\n    7,\n    8\n  ],\n  [\n    9,\n    0\n  ],\n  [\n    10\n  ]\n]", json);
+  }
+
+  public void testPrettyPrintListOfPrimitiveArrays() {
+    List<Integer[]> list = Arrays.asList(new Integer[][] { { 1, 2 }, { 3, 4 },
+        { 5, 6 }, { 7, 8 }, { 9, 0 }, { 10 } });
+    String json = gson.toJson(list);
+    assertEquals("[\n  [\n    1,\n    2\n  ],\n  [\n    3,\n    4\n  ],\n  [\n    5,\n    6\n  ],"
+        + "\n  [\n    7,\n    8\n  ],\n  [\n    9,\n    0\n  ],\n  [\n    10\n  ]\n]", json);
+  }
+  
+  public void testMap() {
+    Map<String, Integer> map = new LinkedHashMap<>();
+    map.put("abc", 1);
+    map.put("def", 5);
+    String json = gson.toJson(map);
+    assertEquals("{\n  \"abc\": 1,\n  \"def\": 5\n}", json);
+  }
+
+  // In response to bug 153
+  public void testEmptyMapField() {
+    ClassWithMap obj = new ClassWithMap();
+    obj.map = new LinkedHashMap<>();
+    String json = gson.toJson(obj);
+    assertTrue(json.contains("{\n  \"map\": {},\n  \"value\": 2\n}"));
+  }
+
+  @SuppressWarnings("unused")
+  private static class ClassWithMap {
+    Map<String, Integer> map;
+    int value = 2;
+  }
+
+  public void testMultipleArrays() {
+    int[][][] ints = new int[][][] { { { 1 }, { 2 } } };
+    String json = gson.toJson(ints);
+    assertEquals("[\n  [\n    [\n      1\n    ],\n    [\n      2\n    ]\n  ]\n]", json);
+  }
+
+  private void print(String msg) {
+    if (DEBUG) {
+      System.out.println(msg);
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/PrimitiveCharacterTest.java b/gson/src/test/java/com/google/gson/functional/PrimitiveCharacterTest.java
new file mode 100644
index 0000000..69ff1f3
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/PrimitiveCharacterTest.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.functional;
+
+import junit.framework.TestCase;
+
+import com.google.gson.Gson;
+
+/**
+ * Functional tests for Java Character values.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public class PrimitiveCharacterTest extends TestCase {
+  private Gson gson;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    gson = new Gson();
+  }
+
+  public void testPrimitiveCharacterAutoboxedSerialization() {
+    assertEquals("\"A\"", gson.toJson('A'));
+    assertEquals("\"A\"", gson.toJson('A', char.class));
+    assertEquals("\"A\"", gson.toJson('A', Character.class));
+  }
+
+  public void testPrimitiveCharacterAutoboxedDeserialization() {
+    char expected = 'a';
+    char actual = gson.fromJson("a", char.class);
+    assertEquals(expected, actual);
+
+    actual = gson.fromJson("\"a\"", char.class);
+    assertEquals(expected, actual);
+
+    actual = gson.fromJson("a", Character.class);
+    assertEquals(expected, actual);
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/PrimitiveTest.java b/gson/src/test/java/com/google/gson/functional/PrimitiveTest.java
new file mode 100644
index 0000000..6d74cc2
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/PrimitiveTest.java
@@ -0,0 +1,900 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.functional;
+
+import static org.junit.Assert.assertArrayEquals;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonPrimitive;
+import com.google.gson.JsonSyntaxException;
+import com.google.gson.LongSerializationPolicy;
+import com.google.gson.internal.LazilyParsedNumber;
+import com.google.gson.reflect.TypeToken;
+import java.io.Serializable;
+import java.io.StringReader;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.util.Arrays;
+import java.util.List;
+import junit.framework.TestCase;
+
+/**
+ * Functional tests for Json primitive values: integers, and floating point numbers.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public class PrimitiveTest extends TestCase {
+  private Gson gson;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    gson = new Gson();
+  }
+
+  public void testPrimitiveIntegerAutoboxedSerialization() {
+    assertEquals("1", gson.toJson(1));
+  }
+
+  public void testPrimitiveIntegerAutoboxedDeserialization() {
+    int expected = 1;
+    int actual = gson.fromJson("1", int.class);
+    assertEquals(expected, actual);
+
+    actual = gson.fromJson("1", Integer.class);
+    assertEquals(expected, actual);
+  }
+
+  public void testByteSerialization() {
+    assertEquals("1", gson.toJson(1, byte.class));
+    assertEquals("1", gson.toJson(1, Byte.class));
+  }
+
+  public void testByteDeserialization() {
+    Byte boxed = gson.fromJson("1", Byte.class);
+    assertEquals(1, (byte)boxed);
+    byte primitive = gson.fromJson("1", byte.class);
+    assertEquals(1, primitive);
+
+    byte[] bytes = gson.fromJson("[-128, 0, 127, 255]", byte[].class);
+    assertArrayEquals(new byte[] {-128, 0, 127, -1}, bytes);
+  }
+
+  public void testByteDeserializationLossy() {
+    try {
+      gson.fromJson("-129", byte.class);
+      fail();
+    } catch (JsonSyntaxException e) {
+      assertEquals("Lossy conversion from -129 to byte; at path $", e.getMessage());
+    }
+
+    try {
+      gson.fromJson("256", byte.class);
+      fail();
+    } catch (JsonSyntaxException e) {
+      assertEquals("Lossy conversion from 256 to byte; at path $", e.getMessage());
+    }
+
+    try {
+      gson.fromJson("2147483648", byte.class);
+      fail();
+    } catch (JsonSyntaxException e) {
+      assertEquals("java.lang.NumberFormatException: Expected an int but was 2147483648 at line 1 column 11 path $", e.getMessage());
+    }
+  }
+
+  public void testShortSerialization() {
+    assertEquals("1", gson.toJson(1, short.class));
+    assertEquals("1", gson.toJson(1, Short.class));
+  }
+
+  public void testShortDeserialization() {
+    Short boxed = gson.fromJson("1", Short.class);
+    assertEquals(1, (short)boxed);
+    short primitive = gson.fromJson("1", short.class);
+    assertEquals(1, primitive);
+
+    short[] shorts = gson.fromJson("[-32768, 0, 32767, 65535]", short[].class);
+    assertArrayEquals(new short[] {-32768, 0, 32767, -1}, shorts);
+  }
+
+  public void testShortDeserializationLossy() {
+    try {
+      gson.fromJson("-32769", short.class);
+      fail();
+    } catch (JsonSyntaxException e) {
+      assertEquals("Lossy conversion from -32769 to short; at path $", e.getMessage());
+    }
+
+    try {
+      gson.fromJson("65536", short.class);
+      fail();
+    } catch (JsonSyntaxException e) {
+      assertEquals("Lossy conversion from 65536 to short; at path $", e.getMessage());
+    }
+
+    try {
+      gson.fromJson("2147483648", short.class);
+      fail();
+    } catch (JsonSyntaxException e) {
+      assertEquals("java.lang.NumberFormatException: Expected an int but was 2147483648 at line 1 column 11 path $", e.getMessage());
+    }
+  }
+
+  public void testPrimitiveIntegerAutoboxedInASingleElementArraySerialization() {
+    int target[] = {-9332};
+    assertEquals("[-9332]", gson.toJson(target));
+    assertEquals("[-9332]", gson.toJson(target, int[].class));
+    assertEquals("[-9332]", gson.toJson(target, Integer[].class));
+  }
+
+  public void testReallyLongValuesSerialization() {
+    long value = 333961828784581L;
+    assertEquals("333961828784581", gson.toJson(value));
+  }
+
+  public void testReallyLongValuesDeserialization() {
+    String json = "333961828784581";
+    long value = gson.fromJson(json, Long.class);
+    assertEquals(333961828784581L, value);
+  }
+
+  public void testPrimitiveLongAutoboxedSerialization() {
+    assertEquals("1", gson.toJson(1L, long.class));
+    assertEquals("1", gson.toJson(1L, Long.class));
+  }
+
+  public void testPrimitiveLongAutoboxedDeserialization() {
+    long expected = 1L;
+    long actual = gson.fromJson("1", long.class);
+    assertEquals(expected, actual);
+
+    actual = gson.fromJson("1", Long.class);
+    assertEquals(expected, actual);
+  }
+
+  public void testPrimitiveLongAutoboxedInASingleElementArraySerialization() {
+    long[] target = {-23L};
+    assertEquals("[-23]", gson.toJson(target));
+    assertEquals("[-23]", gson.toJson(target, long[].class));
+    assertEquals("[-23]", gson.toJson(target, Long[].class));
+  }
+
+  public void testPrimitiveBooleanAutoboxedSerialization() {
+    assertEquals("true", gson.toJson(true));
+    assertEquals("false", gson.toJson(false));
+  }
+
+  public void testBooleanDeserialization() {
+    boolean value = gson.fromJson("false", boolean.class);
+    assertEquals(false, value);
+    value = gson.fromJson("true", boolean.class);
+    assertEquals(true, value);
+  }
+
+  public void testPrimitiveBooleanAutoboxedInASingleElementArraySerialization() {
+    boolean target[] = {false};
+    assertEquals("[false]", gson.toJson(target));
+    assertEquals("[false]", gson.toJson(target, boolean[].class));
+    assertEquals("[false]", gson.toJson(target, Boolean[].class));
+  }
+
+  public void testNumberSerialization() {
+    Number expected = 1L;
+    String json = gson.toJson(expected);
+    assertEquals(expected.toString(), json);
+
+    json = gson.toJson(expected, Number.class);
+    assertEquals(expected.toString(), json);
+  }
+
+  public void testNumberDeserialization() {
+    String json = "1";
+    Number expected = Integer.valueOf(json);
+    Number actual = gson.fromJson(json, Number.class);
+    assertEquals(expected.intValue(), actual.intValue());
+
+    json = String.valueOf(Long.MAX_VALUE);
+    expected = Long.valueOf(json);
+    actual = gson.fromJson(json, Number.class);
+    assertEquals(expected.longValue(), actual.longValue());
+
+    json = "1.0";
+    actual = gson.fromJson(json, Number.class);
+    assertEquals(1L, actual.longValue());
+  }
+
+  public void testNumberAsStringDeserialization() {
+    Number value = gson.fromJson("\"18\"", Number.class);
+    assertEquals(18, value.intValue());
+  }
+
+  public void testPrimitiveDoubleAutoboxedSerialization() {
+    assertEquals("-122.08234335", gson.toJson(-122.08234335D));
+    assertEquals("122.08112002", gson.toJson(122.08112002D));
+  }
+
+  public void testPrimitiveDoubleAutoboxedDeserialization() {
+    double actual = gson.fromJson("-122.08858585", double.class);
+    assertEquals(-122.08858585D, actual);
+
+    actual = gson.fromJson("122.023900008000", Double.class);
+    assertEquals(122.023900008D, actual);
+  }
+
+  public void testPrimitiveDoubleAutoboxedInASingleElementArraySerialization() {
+    double[] target = {-122.08D};
+    assertEquals("[-122.08]", gson.toJson(target));
+    assertEquals("[-122.08]", gson.toJson(target, double[].class));
+    assertEquals("[-122.08]", gson.toJson(target, Double[].class));
+  }
+
+  public void testDoubleAsStringRepresentationDeserialization() {
+    String doubleValue = "1.0043E+5";
+    Double expected = Double.valueOf(doubleValue);
+    Double actual = gson.fromJson(doubleValue, Double.class);
+    assertEquals(expected, actual);
+
+    double actual1 = gson.fromJson(doubleValue, double.class);
+    assertEquals(expected.doubleValue(), actual1);
+  }
+
+  public void testDoubleNoFractAsStringRepresentationDeserialization() {
+    String doubleValue = "1E+5";
+    Double expected = Double.valueOf(doubleValue);
+    Double actual = gson.fromJson(doubleValue, Double.class);
+    assertEquals(expected, actual);
+
+    double actual1 = gson.fromJson(doubleValue, double.class);
+    assertEquals(expected.doubleValue(), actual1);
+  }
+
+  public void testDoubleArrayDeserialization() {
+      String json = "[0.0, 0.004761904761904762, 3.4013606962703525E-4, 7.936508173034305E-4,"
+              + "0.0011904761904761906, 0.0]";
+      double[] values = gson.fromJson(json, double[].class);
+      assertEquals(6, values.length);
+      assertEquals(0.0, values[0]);
+      assertEquals(0.004761904761904762, values[1]);
+      assertEquals(3.4013606962703525E-4, values[2]);
+      assertEquals(7.936508173034305E-4, values[3]);
+      assertEquals(0.0011904761904761906, values[4]);
+      assertEquals(0.0, values[5]);
+  }
+
+  public void testLargeDoubleDeserialization() {
+    String doubleValue = "1.234567899E8";
+    Double expected = Double.valueOf(doubleValue);
+    Double actual = gson.fromJson(doubleValue, Double.class);
+    assertEquals(expected, actual);
+
+    double actual1 = gson.fromJson(doubleValue, double.class);
+    assertEquals(expected.doubleValue(), actual1);
+  }
+
+  public void testBigDecimalSerialization() {
+    BigDecimal target = new BigDecimal("-122.0e-21");
+    String json = gson.toJson(target);
+    assertEquals(target, new BigDecimal(json));
+  }
+
+  public void testBigDecimalDeserialization() {
+    BigDecimal target = new BigDecimal("-122.0e-21");
+    String json = "-122.0e-21";
+    assertEquals(target, gson.fromJson(json, BigDecimal.class));
+  }
+
+  public void testBigDecimalInASingleElementArraySerialization() {
+    BigDecimal[] target = {new BigDecimal("-122.08e-21")};
+    String json = gson.toJson(target);
+    String actual = extractElementFromArray(json);
+    assertEquals(target[0], new BigDecimal(actual));
+
+    json = gson.toJson(target, BigDecimal[].class);
+    actual = extractElementFromArray(json);
+    assertEquals(target[0], new BigDecimal(actual));
+  }
+
+  public void testSmallValueForBigDecimalSerialization() {
+    BigDecimal target = new BigDecimal("1.55");
+    String actual = gson.toJson(target);
+    assertEquals(target.toString(), actual);
+  }
+
+  public void testSmallValueForBigDecimalDeserialization() {
+    BigDecimal expected = new BigDecimal("1.55");
+    BigDecimal actual = gson.fromJson("1.55", BigDecimal.class);
+    assertEquals(expected, actual);
+  }
+
+  public void testBigDecimalPreservePrecisionSerialization() {
+    String expectedValue = "1.000";
+    BigDecimal obj = new BigDecimal(expectedValue);
+    String actualValue = gson.toJson(obj);
+
+    assertEquals(expectedValue, actualValue);
+  }
+
+  public void testBigDecimalPreservePrecisionDeserialization() {
+    String json = "1.000";
+    BigDecimal expected = new BigDecimal(json);
+    BigDecimal actual = gson.fromJson(json, BigDecimal.class);
+
+    assertEquals(expected, actual);
+  }
+
+  public void testBigDecimalAsStringRepresentationDeserialization() {
+    String doubleValue = "0.05E+5";
+    BigDecimal expected = new BigDecimal(doubleValue);
+    BigDecimal actual = gson.fromJson(doubleValue, BigDecimal.class);
+    assertEquals(expected, actual);
+  }
+
+  public void testBigDecimalNoFractAsStringRepresentationDeserialization() {
+    String doubleValue = "5E+5";
+    BigDecimal expected = new BigDecimal(doubleValue);
+    BigDecimal actual = gson.fromJson(doubleValue, BigDecimal.class);
+    assertEquals(expected, actual);
+  }
+
+  public void testBigIntegerSerialization() {
+    BigInteger target = new BigInteger("12121211243123245845384534687435634558945453489543985435");
+    assertEquals(target.toString(), gson.toJson(target));
+  }
+
+  public void testBigIntegerDeserialization() {
+    String json = "12121211243123245845384534687435634558945453489543985435";
+    BigInteger target = new BigInteger(json);
+    assertEquals(target, gson.fromJson(json, BigInteger.class));
+  }
+
+  public void testBigIntegerInASingleElementArraySerialization() {
+    BigInteger[] target = {new BigInteger("1212121243434324323254365345367456456456465464564564")};
+    String json = gson.toJson(target);
+    String actual = extractElementFromArray(json);
+    assertEquals(target[0], new BigInteger(actual));
+
+    json = gson.toJson(target, BigInteger[].class);
+    actual = extractElementFromArray(json);
+    assertEquals(target[0], new BigInteger(actual));
+  }
+
+  public void testSmallValueForBigIntegerSerialization() {
+    BigInteger target = new BigInteger("15");
+    String actual = gson.toJson(target);
+    assertEquals(target.toString(), actual);
+  }
+
+  public void testSmallValueForBigIntegerDeserialization() {
+    BigInteger expected = new BigInteger("15");
+    BigInteger actual = gson.fromJson("15", BigInteger.class);
+    assertEquals(expected, actual);
+  }
+
+  public void testBadValueForBigIntegerDeserialization() {
+    try {
+      gson.fromJson("15.099", BigInteger.class);
+      fail("BigInteger can not be decimal values.");
+    } catch (JsonSyntaxException expected) { }
+  }
+
+  public void testLazilyParsedNumberSerialization() {
+    LazilyParsedNumber target = new LazilyParsedNumber("1.5");
+    String actual = gson.toJson(target);
+    assertEquals("1.5", actual);
+  }
+
+  public void testLazilyParsedNumberDeserialization() {
+    LazilyParsedNumber expected = new LazilyParsedNumber("1.5");
+    LazilyParsedNumber actual = gson.fromJson("1.5", LazilyParsedNumber.class);
+    assertEquals(expected, actual);
+  }
+
+  public void testMoreSpecificSerialization() {
+    Gson gson = new Gson();
+    String expected = "This is a string";
+    String expectedJson = gson.toJson(expected);
+
+    Serializable serializableString = expected;
+    String actualJson = gson.toJson(serializableString, Serializable.class);
+    assertFalse(expectedJson.equals(actualJson));
+  }
+
+  private String extractElementFromArray(String json) {
+    return json.substring(json.indexOf('[') + 1, json.indexOf(']'));
+  }
+
+  public void testDoubleNaNSerializationNotSupportedByDefault() {
+    try {
+      double nan = Double.NaN;
+      gson.toJson(nan);
+      fail("Gson should not accept NaN for serialization");
+    } catch (IllegalArgumentException expected) {
+    }
+    try {
+      gson.toJson(Double.NaN);
+      fail("Gson should not accept NaN for serialization");
+    } catch (IllegalArgumentException expected) {
+    }
+  }
+
+  public void testDoubleNaNSerialization() {
+    Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create();
+    double nan = Double.NaN;
+    assertEquals("NaN", gson.toJson(nan));
+    assertEquals("NaN", gson.toJson(Double.NaN));
+  }
+
+  public void testDoubleNaNDeserialization() {
+    assertTrue(Double.isNaN(gson.fromJson("NaN", Double.class)));
+    assertTrue(Double.isNaN(gson.fromJson("NaN", double.class)));
+  }
+
+  public void testFloatNaNSerializationNotSupportedByDefault() {
+    try {
+      float nan = Float.NaN;
+      gson.toJson(nan);
+      fail("Gson should not accept NaN for serialization");
+    } catch (IllegalArgumentException expected) {
+    }
+    try {
+      gson.toJson(Float.NaN);
+      fail("Gson should not accept NaN for serialization");
+    } catch (IllegalArgumentException expected) {
+    }
+  }
+
+  public void testFloatNaNSerialization() {
+    Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create();
+    float nan = Float.NaN;
+    assertEquals("NaN", gson.toJson(nan));
+    assertEquals("NaN", gson.toJson(Float.NaN));
+  }
+
+  public void testFloatNaNDeserialization() {
+    assertTrue(Float.isNaN(gson.fromJson("NaN", Float.class)));
+    assertTrue(Float.isNaN(gson.fromJson("NaN", float.class)));
+  }
+
+  public void testBigDecimalNaNDeserializationNotSupported() {
+    try {
+      gson.fromJson("NaN", BigDecimal.class);
+      fail("Gson should not accept NaN for deserialization by default.");
+    } catch (JsonSyntaxException expected) {
+    }
+  }
+
+  public void testDoubleInfinitySerializationNotSupportedByDefault() {
+    try {
+      double infinity = Double.POSITIVE_INFINITY;
+      gson.toJson(infinity);
+      fail("Gson should not accept positive infinity for serialization by default.");
+    } catch (IllegalArgumentException expected) {
+    }
+    try {
+      gson.toJson(Double.POSITIVE_INFINITY);
+      fail("Gson should not accept positive infinity for serialization by default.");
+    } catch (IllegalArgumentException expected) {
+    }
+  }
+
+  public void testDoubleInfinitySerialization() {
+    Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create();
+    double infinity = Double.POSITIVE_INFINITY;
+    assertEquals("Infinity", gson.toJson(infinity));
+    assertEquals("Infinity", gson.toJson(Double.POSITIVE_INFINITY));
+  }
+
+  public void testDoubleInfinityDeserialization() {
+    assertTrue(Double.isInfinite(gson.fromJson("Infinity", Double.class)));
+    assertTrue(Double.isInfinite(gson.fromJson("Infinity", double.class)));
+  }
+
+  public void testFloatInfinitySerializationNotSupportedByDefault() {
+    try {
+      float infinity = Float.POSITIVE_INFINITY;
+      gson.toJson(infinity);
+      fail("Gson should not accept positive infinity for serialization by default");
+    } catch (IllegalArgumentException expected) {
+    }
+    try {
+      gson.toJson(Float.POSITIVE_INFINITY);
+      fail("Gson should not accept positive infinity for serialization by default");
+    } catch (IllegalArgumentException expected) {
+    }
+  }
+
+  public void testFloatInfinitySerialization() {
+    Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create();
+    float infinity = Float.POSITIVE_INFINITY;
+    assertEquals("Infinity", gson.toJson(infinity));
+    assertEquals("Infinity", gson.toJson(Float.POSITIVE_INFINITY));
+  }
+
+  public void testFloatInfinityDeserialization() {
+    assertTrue(Float.isInfinite(gson.fromJson("Infinity", Float.class)));
+    assertTrue(Float.isInfinite(gson.fromJson("Infinity", float.class)));
+  }
+
+  public void testBigDecimalInfinityDeserializationNotSupported() {
+    try {
+      gson.fromJson("Infinity", BigDecimal.class);
+      fail("Gson should not accept positive infinity for deserialization with BigDecimal");
+    } catch (JsonSyntaxException expected) {
+    }
+  }
+
+  public void testNegativeInfinitySerializationNotSupportedByDefault() {
+    try {
+      double negativeInfinity = Double.NEGATIVE_INFINITY;
+      gson.toJson(negativeInfinity);
+      fail("Gson should not accept negative infinity for serialization by default");
+    } catch (IllegalArgumentException expected) {
+    }
+    try {
+      gson.toJson(Double.NEGATIVE_INFINITY);
+      fail("Gson should not accept negative infinity for serialization by default");
+    } catch (IllegalArgumentException expected) {
+    }
+  }
+
+  public void testNegativeInfinitySerialization() {
+    Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create();
+    double negativeInfinity = Double.NEGATIVE_INFINITY;
+    assertEquals("-Infinity", gson.toJson(negativeInfinity));
+    assertEquals("-Infinity", gson.toJson(Double.NEGATIVE_INFINITY));
+  }
+
+  public void testNegativeInfinityDeserialization() {
+    assertTrue(Double.isInfinite(gson.fromJson("-Infinity", double.class)));
+    assertTrue(Double.isInfinite(gson.fromJson("-Infinity", Double.class)));
+  }
+
+  public void testNegativeInfinityFloatSerializationNotSupportedByDefault() {
+    try {
+      float negativeInfinity = Float.NEGATIVE_INFINITY;
+      gson.toJson(negativeInfinity);
+      fail("Gson should not accept negative infinity for serialization by default");
+    } catch (IllegalArgumentException expected) {
+    }
+    try {
+      gson.toJson(Float.NEGATIVE_INFINITY);
+      fail("Gson should not accept negative infinity for serialization by default");
+    } catch (IllegalArgumentException expected) {
+    }
+  }
+
+  public void testNegativeInfinityFloatSerialization() {
+    Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create();
+    float negativeInfinity = Float.NEGATIVE_INFINITY;
+    assertEquals("-Infinity", gson.toJson(negativeInfinity));
+    assertEquals("-Infinity", gson.toJson(Float.NEGATIVE_INFINITY));
+  }
+
+  public void testNegativeInfinityFloatDeserialization() {
+    assertTrue(Float.isInfinite(gson.fromJson("-Infinity", float.class)));
+    assertTrue(Float.isInfinite(gson.fromJson("-Infinity", Float.class)));
+  }
+
+  public void testBigDecimalNegativeInfinityDeserializationNotSupported() {
+    try {
+      gson.fromJson("-Infinity", BigDecimal.class);
+      fail("Gson should not accept positive infinity for deserialization");
+    } catch (JsonSyntaxException expected) {
+    }
+  }
+
+  public void testLongAsStringSerialization() throws Exception {
+    gson = new GsonBuilder().setLongSerializationPolicy(LongSerializationPolicy.STRING).create();
+    String result = gson.toJson(15L);
+    assertEquals("\"15\"", result);
+
+    // Test with an integer and ensure its still a number
+    result = gson.toJson(2);
+    assertEquals("2", result);
+  }
+
+  public void testLongAsStringDeserialization() throws Exception {
+    long value = gson.fromJson("\"15\"", long.class);
+    assertEquals(15, value);
+
+    gson = new GsonBuilder().setLongSerializationPolicy(LongSerializationPolicy.STRING).create();
+    value = gson.fromJson("\"25\"", long.class);
+    assertEquals(25, value);
+  }
+
+  public void testQuotedStringSerializationAndDeserialization() throws Exception {
+    String value = "String Blah Blah Blah...1, 2, 3";
+    String serializedForm = gson.toJson(value);
+    assertEquals("\"" + value + "\"", serializedForm);
+
+    String actual = gson.fromJson(serializedForm, String.class);
+    assertEquals(value, actual);
+  }
+
+  public void testUnquotedStringDeserializationFails() throws Exception {
+    assertEquals("UnquotedSingleWord", gson.fromJson("UnquotedSingleWord", String.class));
+
+    String value = "String Blah Blah Blah...1, 2, 3";
+    try {
+      gson.fromJson(value, String.class);
+      fail();
+    } catch (JsonSyntaxException expected) { }
+  }
+
+  public void testHtmlCharacterSerialization() throws Exception {
+    String target = "<script>var a = 12;</script>";
+    String result = gson.toJson(target);
+    assertFalse(result.equals('"' + target + '"'));
+
+    gson = new GsonBuilder().disableHtmlEscaping().create();
+    result = gson.toJson(target);
+    assertTrue(result.equals('"' + target + '"'));
+  }
+
+  public void testDeserializePrimitiveWrapperAsObjectField() {
+    String json = "{i:10}";
+    ClassWithIntegerField target = gson.fromJson(json, ClassWithIntegerField.class);
+    assertEquals(10, target.i.intValue());
+  }
+
+  private static class ClassWithIntegerField {
+    Integer i;
+  }
+
+  public void testPrimitiveClassLiteral() {
+    assertEquals(1, gson.fromJson("1", int.class).intValue());
+    assertEquals(1, gson.fromJson(new StringReader("1"), int.class).intValue());
+    assertEquals(1, gson.fromJson(new JsonPrimitive(1), int.class).intValue());
+  }
+
+  public void testDeserializeJsonObjectAsLongPrimitive() {
+    try {
+      gson.fromJson("{'abc':1}", long.class);
+      fail();
+    } catch (JsonSyntaxException expected) {}
+  }
+
+  public void testDeserializeJsonArrayAsLongWrapper() {
+    try {
+      gson.fromJson("[1,2,3]", Long.class);
+      fail();
+    } catch (JsonSyntaxException expected) {}
+  }
+
+  public void testDeserializeJsonArrayAsInt() {
+    try {
+      gson.fromJson("[1, 2, 3, 4]", int.class);
+      fail();
+    } catch (JsonSyntaxException expected) {}
+  }
+
+  public void testDeserializeJsonObjectAsInteger() {
+    try {
+      gson.fromJson("{}", Integer.class);
+      fail();
+    } catch (JsonSyntaxException expected) {}
+  }
+
+  public void testDeserializeJsonObjectAsShortPrimitive() {
+    try {
+      gson.fromJson("{'abc':1}", short.class);
+      fail();
+    } catch (JsonSyntaxException expected) {}
+  }
+
+  public void testDeserializeJsonArrayAsShortWrapper() {
+    try {
+      gson.fromJson("['a','b']", Short.class);
+      fail();
+    } catch (JsonSyntaxException expected) {}
+  }
+
+  public void testDeserializeJsonArrayAsDoublePrimitive() {
+    try {
+      gson.fromJson("[1,2]", double.class);
+      fail();
+    } catch (JsonSyntaxException expected) {}
+  }
+
+  public void testDeserializeJsonObjectAsDoubleWrapper() {
+    try {
+      gson.fromJson("{'abc':1}", Double.class);
+      fail();
+    } catch (JsonSyntaxException expected) {}
+  }
+
+  public void testDeserializeJsonObjectAsFloatPrimitive() {
+    try {
+      gson.fromJson("{'abc':1}", float.class);
+      fail();
+    } catch (JsonSyntaxException expected) {}
+  }
+
+  public void testDeserializeJsonArrayAsFloatWrapper() {
+    try {
+      gson.fromJson("[1,2,3]", Float.class);
+      fail();
+    } catch (JsonSyntaxException expected) {}
+  }
+
+  public void testDeserializeJsonObjectAsBytePrimitive() {
+    try {
+      gson.fromJson("{'abc':1}", byte.class);
+      fail();
+    } catch (JsonSyntaxException expected) {}
+  }
+
+  public void testDeserializeJsonArrayAsByteWrapper() {
+    try {
+      gson.fromJson("[1,2,3,4]", Byte.class);
+      fail();
+    } catch (JsonSyntaxException expected) {}
+  }
+
+  public void testDeserializeJsonObjectAsBooleanPrimitive() {
+    try {
+      gson.fromJson("{'abc':1}", boolean.class);
+      fail();
+    } catch (JsonSyntaxException expected) {}
+  }
+
+  public void testDeserializeJsonArrayAsBooleanWrapper() {
+    try {
+      gson.fromJson("[1,2,3,4]", Boolean.class);
+      fail();
+    } catch (JsonSyntaxException expected) {}
+  }
+
+  public void testDeserializeJsonArrayAsBigDecimal() {
+    try {
+      gson.fromJson("[1,2,3,4]", BigDecimal.class);
+      fail();
+    } catch (JsonSyntaxException expected) {}
+  }
+
+  public void testDeserializeJsonObjectAsBigDecimal() {
+    try {
+      gson.fromJson("{'a':1}", BigDecimal.class);
+      fail();
+    } catch (JsonSyntaxException expected) {}
+  }
+
+  public void testDeserializeJsonArrayAsBigInteger() {
+    try {
+      gson.fromJson("[1,2,3,4]", BigInteger.class);
+      fail();
+    } catch (JsonSyntaxException expected) {}
+  }
+
+  public void testDeserializeJsonObjectAsBigInteger() {
+    try {
+      gson.fromJson("{'c':2}", BigInteger.class);
+      fail();
+    } catch (JsonSyntaxException expected) {}
+  }
+
+  public void testDeserializeJsonArrayAsNumber() {
+    try {
+      gson.fromJson("[1,2,3,4]", Number.class);
+      fail();
+    } catch (JsonSyntaxException expected) {}
+  }
+
+  public void testDeserializeJsonObjectAsNumber() {
+    try {
+      gson.fromJson("{'c':2}", Number.class);
+      fail();
+    } catch (JsonSyntaxException expected) {}
+  }
+
+  public void testDeserializingDecimalPointValueZeroSucceeds() {
+    assertEquals(1, (int) gson.fromJson("1.0", Integer.class));
+  }
+
+  public void testDeserializingNonZeroDecimalPointValuesAsIntegerFails() {
+    try {
+      gson.fromJson("1.02", Byte.class);
+      fail();
+    } catch (JsonSyntaxException expected) {
+    }
+    try {
+      gson.fromJson("1.02", Short.class);
+      fail();
+    } catch (JsonSyntaxException expected) {
+    }
+    try {
+      gson.fromJson("1.02", Integer.class);
+      fail();
+    } catch (JsonSyntaxException expected) {
+    }
+    try {
+      gson.fromJson("1.02", Long.class);
+      fail();
+    } catch (JsonSyntaxException expected) {
+    }
+  }
+
+  public void testDeserializingBigDecimalAsIntegerFails() {
+    try {
+      gson.fromJson("-122.08e-213", Integer.class);
+      fail();
+    } catch (JsonSyntaxException expected) {
+    }
+  }
+
+  public void testDeserializingBigIntegerAsInteger() {
+    try {
+      gson.fromJson("12121211243123245845384534687435634558945453489543985435", Integer.class);
+      fail();
+    } catch (JsonSyntaxException expected) {
+    }
+  }
+
+  public void testDeserializingBigIntegerAsLong() {
+    try {
+      gson.fromJson("12121211243123245845384534687435634558945453489543985435", Long.class);
+      fail();
+    } catch (JsonSyntaxException expected) {
+    }
+  }
+
+  public void testValueVeryCloseToZeroIsZero() {
+    assertEquals(0, (byte) gson.fromJson("-122.08e-2132", byte.class));
+    assertEquals(0, (short) gson.fromJson("-122.08e-2132", short.class));
+    assertEquals(0, (int) gson.fromJson("-122.08e-2132", int.class));
+    assertEquals(0, (long) gson.fromJson("-122.08e-2132", long.class));
+    assertEquals(-0.0f, gson.fromJson("-122.08e-2132", float.class));
+    assertEquals(-0.0, gson.fromJson("-122.08e-2132", double.class));
+    assertEquals(0.0f, gson.fromJson("122.08e-2132", float.class));
+    assertEquals(0.0, gson.fromJson("122.08e-2132", double.class));
+  }
+
+  public void testDeserializingBigDecimalAsFloat() {
+    String json = "-122.08e-2132332";
+    float actual = gson.fromJson(json, float.class);
+    assertEquals(-0.0f, actual);
+  }
+
+  public void testDeserializingBigDecimalAsDouble() {
+    String json = "-122.08e-2132332";
+    double actual = gson.fromJson(json, double.class);
+    assertEquals(-0.0d, actual);
+  }
+
+  public void testDeserializingBigDecimalAsBigIntegerFails() {
+    try {
+      gson.fromJson("-122.08e-213", BigInteger.class);
+      fail();
+    } catch (JsonSyntaxException expected) {
+    }
+  }
+
+  public void testDeserializingBigIntegerAsBigDecimal() {
+    BigDecimal actual =
+      gson.fromJson("12121211243123245845384534687435634558945453489543985435", BigDecimal.class);
+    assertEquals("12121211243123245845384534687435634558945453489543985435", actual.toPlainString());
+  }
+
+  public void testStringsAsBooleans() {
+    String json = "['true', 'false', 'TRUE', 'yes', '1']";
+    assertEquals(Arrays.asList(true, false, true, false, false),
+        gson.<List<Boolean>>fromJson(json, new TypeToken<List<Boolean>>() {}.getType()));
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/PrintFormattingTest.java b/gson/src/test/java/com/google/gson/functional/PrintFormattingTest.java
new file mode 100644
index 0000000..7dcbc23
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/PrintFormattingTest.java
@@ -0,0 +1,84 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.functional;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonObject;
+import com.google.gson.common.TestTypes.BagOfPrimitives;
+import com.google.gson.common.TestTypes.ClassWithTransientFields;
+import com.google.gson.common.TestTypes.Nested;
+import com.google.gson.common.TestTypes.PrimitiveArray;
+
+import junit.framework.TestCase;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Functional tests for print formatting.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public class PrintFormattingTest extends TestCase {
+
+  private Gson gson;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    gson = new Gson();
+  }
+
+  @SuppressWarnings({"unchecked", "rawtypes"})
+  public void testCompactFormattingLeavesNoWhiteSpace() {
+    List list = new ArrayList();
+    list.add(new BagOfPrimitives());
+    list.add(new Nested());
+    list.add(new PrimitiveArray());
+    list.add(new ClassWithTransientFields());
+
+    String json = gson.toJson(list);
+    assertContainsNoWhiteSpace(json);
+  }
+
+  public void testJsonObjectWithNullValues() {
+    JsonObject obj = new JsonObject();
+    obj.addProperty("field1", "value1");
+    obj.addProperty("field2", (String) null);
+    String json = gson.toJson(obj);
+    assertTrue(json.contains("field1"));
+    assertFalse(json.contains("field2"));
+  }
+
+  public void testJsonObjectWithNullValuesSerialized() {
+    gson = new GsonBuilder().serializeNulls().create();
+    JsonObject obj = new JsonObject();
+    obj.addProperty("field1", "value1");
+    obj.addProperty("field2", (String) null);
+    String json = gson.toJson(obj);
+    assertTrue(json.contains("field1"));
+    assertTrue(json.contains("field2"));
+  }
+
+  private static void assertContainsNoWhiteSpace(String str) {
+    for (char c : str.toCharArray()) {
+      assertFalse(Character.isWhitespace(c));
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/RawSerializationTest.java b/gson/src/test/java/com/google/gson/functional/RawSerializationTest.java
new file mode 100644
index 0000000..7876999
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/RawSerializationTest.java
@@ -0,0 +1,101 @@
+/*
+ * Copyright (C) 2010 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.functional;
+
+import java.util.Arrays;
+import java.util.Collection;
+
+import junit.framework.TestCase;
+
+import com.google.gson.Gson;
+import com.google.gson.reflect.TypeToken;
+
+/**
+ * Unit tests to validate serialization of parameterized types without explicit types
+ *
+ * @author Inderjeet Singh
+ */
+public class RawSerializationTest extends TestCase {
+
+  private Gson gson;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    gson = new Gson();
+  }
+
+  public void testCollectionOfPrimitives() {
+    Collection<Integer> ints = Arrays.asList(1, 2, 3, 4, 5);
+    String json = gson.toJson(ints);
+    assertEquals("[1,2,3,4,5]", json);
+  }
+
+  public void testCollectionOfObjects() {
+    Collection<Foo> foos = Arrays.asList(new Foo(1), new Foo(2));
+    String json = gson.toJson(foos);
+    assertEquals("[{\"b\":1},{\"b\":2}]", json);
+  }
+
+  public void testParameterizedObject() {
+    Bar<Foo> bar = new Bar<>(new Foo(1));
+    String expectedJson = "{\"t\":{\"b\":1}}";
+    // Ensure that serialization works without specifying the type explicitly
+    String json = gson.toJson(bar);
+    assertEquals(expectedJson, json);
+    // Ensure that serialization also works when the type is specified explicitly
+    json = gson.toJson(bar, new TypeToken<Bar<Foo>>(){}.getType());
+    assertEquals(expectedJson, json);
+  }
+
+  public void testTwoLevelParameterizedObject() {
+    Bar<Bar<Foo>> bar = new Bar<>(new Bar<>(new Foo(1)));
+    String expectedJson = "{\"t\":{\"t\":{\"b\":1}}}";
+    // Ensure that serialization works without specifying the type explicitly
+    String json = gson.toJson(bar);
+    assertEquals(expectedJson, json);
+    // Ensure that serialization also works when the type is specified explicitly
+    json = gson.toJson(bar, new TypeToken<Bar<Bar<Foo>>>(){}.getType());
+    assertEquals(expectedJson, json);
+  }
+
+  public void testThreeLevelParameterizedObject() {
+    Bar<Bar<Bar<Foo>>> bar = new Bar<>(new Bar<>(new Bar<>(new Foo(1))));
+    String expectedJson = "{\"t\":{\"t\":{\"t\":{\"b\":1}}}}";
+    // Ensure that serialization works without specifying the type explicitly
+    String json = gson.toJson(bar);
+    assertEquals(expectedJson, json);
+    // Ensure that serialization also works when the type is specified explicitly
+    json = gson.toJson(bar, new TypeToken<Bar<Bar<Bar<Foo>>>>(){}.getType());
+    assertEquals(expectedJson, json);
+  }
+
+  private static class Foo {
+    @SuppressWarnings("unused")
+    int b;
+    Foo(int b) {
+      this.b = b;
+    }
+  }
+
+  private static class Bar<T> {
+    @SuppressWarnings("unused")
+    T t;
+    Bar(T t) {
+      this.t = t;
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/ReadersWritersTest.java b/gson/src/test/java/com/google/gson/functional/ReadersWritersTest.java
new file mode 100644
index 0000000..e21fb90
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/ReadersWritersTest.java
@@ -0,0 +1,135 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.functional;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonStreamParser;
+import com.google.gson.JsonSyntaxException;
+import com.google.gson.common.TestTypes.BagOfPrimitives;
+
+import com.google.gson.reflect.TypeToken;
+import java.util.Map;
+import junit.framework.TestCase;
+
+import java.io.CharArrayReader;
+import java.io.CharArrayWriter;
+import java.io.IOException;
+import java.io.Reader;
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.io.Writer;
+
+/**
+ * Functional tests for the support of {@link Reader}s and {@link Writer}s.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public class ReadersWritersTest extends TestCase {
+  private Gson gson;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    gson = new Gson();
+  }
+
+  public void testWriterForSerialization() throws Exception {
+    Writer writer = new StringWriter();
+    BagOfPrimitives src = new BagOfPrimitives();
+    gson.toJson(src, writer);
+    assertEquals(src.getExpectedJson(), writer.toString());
+  }
+
+  public void testReaderForDeserialization() throws Exception {
+    BagOfPrimitives expected = new BagOfPrimitives();
+    Reader json = new StringReader(expected.getExpectedJson());
+    BagOfPrimitives actual = gson.fromJson(json, BagOfPrimitives.class);
+    assertEquals(expected, actual);
+  }
+
+  public void testTopLevelNullObjectSerializationWithWriter() {
+    StringWriter writer = new StringWriter();
+    gson.toJson(null, writer);
+    assertEquals("null", writer.toString());
+  }
+
+  public void testTopLevelNullObjectDeserializationWithReader() {
+    StringReader reader = new StringReader("null");
+    Integer nullIntObject = gson.fromJson(reader, Integer.class);
+    assertNull(nullIntObject);
+  }
+
+  public void testTopLevelNullObjectSerializationWithWriterAndSerializeNulls() {
+    Gson gson = new GsonBuilder().serializeNulls().create();
+    StringWriter writer = new StringWriter();
+    gson.toJson(null, writer);
+    assertEquals("null", writer.toString());
+  }
+
+  public void testTopLevelNullObjectDeserializationWithReaderAndSerializeNulls() {
+    Gson gson = new GsonBuilder().serializeNulls().create();
+    StringReader reader = new StringReader("null");
+    Integer nullIntObject = gson.fromJson(reader, Integer.class);
+    assertNull(nullIntObject);
+  }
+
+  public void testReadWriteTwoStrings() throws IOException {
+    Gson gson= new Gson();
+    CharArrayWriter writer= new CharArrayWriter();
+    writer.write(gson.toJson("one").toCharArray());
+    writer.write(gson.toJson("two").toCharArray());
+    CharArrayReader reader = new CharArrayReader(writer.toCharArray());
+    JsonStreamParser parser = new JsonStreamParser(reader);
+    String actualOne = gson.fromJson(parser.next(), String.class);
+    assertEquals("one", actualOne);
+    String actualTwo = gson.fromJson(parser.next(), String.class);
+    assertEquals("two", actualTwo);
+  }
+
+  public void testReadWriteTwoObjects() throws IOException {
+    Gson gson= new Gson();
+    CharArrayWriter writer= new CharArrayWriter();
+    BagOfPrimitives expectedOne = new BagOfPrimitives(1, 1, true, "one");
+    writer.write(gson.toJson(expectedOne).toCharArray());
+    BagOfPrimitives expectedTwo = new BagOfPrimitives(2, 2, false, "two");
+    writer.write(gson.toJson(expectedTwo).toCharArray());
+    CharArrayReader reader = new CharArrayReader(writer.toCharArray());
+    JsonStreamParser parser = new JsonStreamParser(reader);
+    BagOfPrimitives actualOne = gson.fromJson(parser.next(), BagOfPrimitives.class);
+    assertEquals("one", actualOne.stringValue);
+    BagOfPrimitives actualTwo = gson.fromJson(parser.next(), BagOfPrimitives.class);
+    assertEquals("two", actualTwo.stringValue);
+    assertFalse(parser.hasNext());
+  }
+
+  public void testTypeMismatchThrowsJsonSyntaxExceptionForStrings() {
+    try {
+      gson.fromJson("true", new TypeToken<Map<String, String>>() {}.getType());
+      fail();
+    } catch (JsonSyntaxException expected) {
+    }
+  }
+
+  public void testTypeMismatchThrowsJsonSyntaxExceptionForReaders() {
+    try {
+      gson.fromJson(new StringReader("true"), new TypeToken<Map<String, String>>() {}.getType());
+      fail();
+    } catch (JsonSyntaxException expected) {
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/ReflectionAccessFilterTest.java b/gson/src/test/java/com/google/gson/functional/ReflectionAccessFilterTest.java
new file mode 100644
index 0000000..775baf9
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/ReflectionAccessFilterTest.java
@@ -0,0 +1,426 @@
+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.GsonBuilder;
+import com.google.gson.InstanceCreator;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonIOException;
+import com.google.gson.JsonPrimitive;
+import com.google.gson.JsonSerializationContext;
+import com.google.gson.JsonSerializer;
+import com.google.gson.ReflectionAccessFilter;
+import com.google.gson.ReflectionAccessFilter.FilterResult;
+import com.google.gson.TypeAdapter;
+import com.google.gson.internal.ConstructorConstructor;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonWriter;
+import java.awt.Point;
+import java.io.File;
+import java.io.IOException;
+import java.io.Reader;
+import java.lang.reflect.Type;
+import java.util.LinkedList;
+import java.util.List;
+import org.junit.Test;
+
+public class ReflectionAccessFilterTest {
+  // Reader has protected `lock` field which cannot be accessed
+  private static class ClassExtendingJdkClass extends Reader {
+    @Override
+    public int read(char[] cbuf, int off, int len) throws IOException {
+      return 0;
+    }
+
+    @Override
+    public void close() throws IOException {
+    }
+  }
+
+  @Test
+  public void testBlockInaccessibleJava() {
+    Gson gson = new GsonBuilder()
+      .addReflectionAccessFilter(ReflectionAccessFilter.BLOCK_INACCESSIBLE_JAVA)
+      .create();
+
+    // Serialization should fail for classes with non-public fields
+    try {
+      gson.toJson(new File("a"));
+      fail("Expected exception; test needs to be run with Java >= 9");
+    } catch (JsonIOException expected) {
+      // Note: This test is rather brittle and depends on the JDK implementation
+      assertEquals(
+        "Field 'java.io.File#path' is not accessible and ReflectionAccessFilter does not permit "
+        + "making it accessible. Register a TypeAdapter for the declaring type or adjust the access filter.",
+        expected.getMessage()
+      );
+    }
+
+    // But serialization should succeed for classes with only public fields
+    String json = gson.toJson(new Point(1, 2));
+    assertEquals("{\"x\":1,\"y\":2}", json);
+  }
+
+  @Test
+  public void testBlockInaccessibleJavaExtendingJdkClass() {
+    Gson gson = new GsonBuilder()
+      .addReflectionAccessFilter(ReflectionAccessFilter.BLOCK_INACCESSIBLE_JAVA)
+      .create();
+
+    try {
+      gson.toJson(new ClassExtendingJdkClass());
+      fail("Expected exception; test needs to be run with Java >= 9");
+    } catch (JsonIOException expected) {
+      assertEquals(
+        "Field 'java.io.Reader#lock' is not accessible and ReflectionAccessFilter does not permit "
+        + "making it accessible. Register a TypeAdapter for the declaring type or adjust the access filter.",
+        expected.getMessage()
+      );
+    }
+  }
+
+  @Test
+  public void testBlockAllJava() {
+    Gson gson = new GsonBuilder()
+      .addReflectionAccessFilter(ReflectionAccessFilter.BLOCK_ALL_JAVA)
+      .create();
+
+    // Serialization should fail for any Java class
+    try {
+      gson.toJson(Thread.currentThread());
+      fail();
+    } catch (JsonIOException expected) {
+      assertEquals(
+        "ReflectionAccessFilter does not permit using reflection for class java.lang.Thread. "
+        + "Register a TypeAdapter for this type or adjust the access filter.",
+        expected.getMessage()
+      );
+    }
+  }
+
+  @Test
+  public void testBlockAllJavaExtendingJdkClass() {
+    Gson gson = new GsonBuilder()
+      .addReflectionAccessFilter(ReflectionAccessFilter.BLOCK_ALL_JAVA)
+      .create();
+
+    try {
+      gson.toJson(new ClassExtendingJdkClass());
+      fail();
+    } catch (JsonIOException expected) {
+      assertEquals(
+        "ReflectionAccessFilter does not permit using reflection for class java.io.Reader "
+        + "(supertype of class com.google.gson.functional.ReflectionAccessFilterTest$ClassExtendingJdkClass). "
+        + "Register a TypeAdapter for this type or adjust the access filter.",
+        expected.getMessage()
+      );
+    }
+  }
+
+  private static class ClassWithStaticField {
+    @SuppressWarnings("unused")
+    private static int i = 1;
+  }
+
+  @Test
+  public void testBlockInaccessibleStaticField() {
+    Gson gson = new GsonBuilder()
+      .addReflectionAccessFilter(new ReflectionAccessFilter() {
+        @Override public FilterResult check(Class<?> rawClass) {
+          return FilterResult.BLOCK_INACCESSIBLE;
+        }
+      })
+      // Include static fields
+      .excludeFieldsWithModifiers(0)
+      .create();
+
+      try {
+        gson.toJson(new ClassWithStaticField());
+        fail("Expected exception; test needs to be run with Java >= 9");
+      } catch (JsonIOException expected) {
+        assertEquals(
+          "Field 'com.google.gson.functional.ReflectionAccessFilterTest$ClassWithStaticField#i' "
+          + "is not accessible and ReflectionAccessFilter does not permit making it accessible. "
+          + "Register a TypeAdapter for the declaring type or adjust the access filter.",
+          expected.getMessage()
+        );
+      }
+  }
+
+  private static class SuperTestClass {
+  }
+  private static class SubTestClass extends SuperTestClass {
+    @SuppressWarnings("unused")
+    public int i = 1;
+  }
+  private static class OtherClass {
+    @SuppressWarnings("unused")
+    public int i = 2;
+  }
+
+  @Test
+  public void testDelegation() {
+    Gson gson = new GsonBuilder()
+      .addReflectionAccessFilter(new ReflectionAccessFilter() {
+        @Override public FilterResult check(Class<?> rawClass) {
+          // INDECISIVE in last filter should act like ALLOW
+          return SuperTestClass.class.isAssignableFrom(rawClass) ? FilterResult.BLOCK_ALL : FilterResult.INDECISIVE;
+        }
+      })
+      .addReflectionAccessFilter(new ReflectionAccessFilter() {
+        @Override public FilterResult check(Class<?> rawClass) {
+          // INDECISIVE should delegate to previous filter
+          return rawClass == SubTestClass.class ? FilterResult.ALLOW : FilterResult.INDECISIVE;
+        }
+      })
+      .create();
+
+    // Filter disallows SuperTestClass
+    try {
+      gson.toJson(new SuperTestClass());
+      fail();
+    } catch (JsonIOException expected) {
+      assertEquals(
+        "ReflectionAccessFilter does not permit using reflection for class "
+        + "com.google.gson.functional.ReflectionAccessFilterTest$SuperTestClass. "
+        + "Register a TypeAdapter for this type or adjust the access filter.",
+        expected.getMessage()
+      );
+    }
+
+    // But registration order is reversed, so filter for SubTestClass allows reflection
+    String json = gson.toJson(new SubTestClass());
+    assertEquals("{\"i\":1}", json);
+
+    // And unrelated class should not be affected
+    json = gson.toJson(new OtherClass());
+    assertEquals("{\"i\":2}", json);
+  }
+
+  private static class ClassWithPrivateField {
+    @SuppressWarnings("unused")
+    private int i = 1;
+  }
+  private static class ExtendingClassWithPrivateField extends ClassWithPrivateField {
+  }
+
+  @Test
+  public void testAllowForSupertype() {
+    Gson gson = new GsonBuilder()
+      .addReflectionAccessFilter(new ReflectionAccessFilter() {
+        @Override public FilterResult check(Class<?> rawClass) {
+          return FilterResult.BLOCK_INACCESSIBLE;
+        }
+      })
+      .create();
+
+    // First make sure test is implemented correctly and access is blocked
+    try {
+      gson.toJson(new ExtendingClassWithPrivateField());
+      fail("Expected exception; test needs to be run with Java >= 9");
+    } catch (JsonIOException expected) {
+      assertEquals(
+        "Field 'com.google.gson.functional.ReflectionAccessFilterTest$ClassWithPrivateField#i' "
+        + "is not accessible and ReflectionAccessFilter does not permit making it accessible. "
+        + "Register a TypeAdapter for the declaring type or adjust the access filter.",
+        expected.getMessage()
+      );
+    }
+
+    gson = gson.newBuilder()
+      // Allow reflective access for supertype
+      .addReflectionAccessFilter(new ReflectionAccessFilter() {
+        @Override public FilterResult check(Class<?> rawClass) {
+          return rawClass == ClassWithPrivateField.class ? FilterResult.ALLOW : FilterResult.INDECISIVE;
+        }
+      })
+      .create();
+
+    // Inherited (inaccessible) private field should have been made accessible
+    String json = gson.toJson(new ExtendingClassWithPrivateField());
+    assertEquals("{\"i\":1}", json);
+  }
+
+  private static class ClassWithPrivateNoArgsConstructor {
+    private ClassWithPrivateNoArgsConstructor() {
+    }
+  }
+
+  @Test
+  public void testInaccessibleNoArgsConstructor() {
+    Gson gson = new GsonBuilder()
+      .addReflectionAccessFilter(new ReflectionAccessFilter() {
+        @Override public FilterResult check(Class<?> rawClass) {
+          return FilterResult.BLOCK_INACCESSIBLE;
+        }
+      })
+      .create();
+
+    try {
+      gson.fromJson("{}", ClassWithPrivateNoArgsConstructor.class);
+      fail("Expected exception; test needs to be run with Java >= 9");
+    } catch (JsonIOException expected) {
+      assertEquals(
+        "Unable to invoke no-args constructor of class com.google.gson.functional.ReflectionAccessFilterTest$ClassWithPrivateNoArgsConstructor; "
+        + "constructor is not accessible and ReflectionAccessFilter does not permit making it accessible. Register an "
+        + "InstanceCreator or a TypeAdapter for this type, change the visibility of the constructor or adjust the access filter.",
+        expected.getMessage()
+      );
+    }
+  }
+
+  private static class ClassWithoutNoArgsConstructor {
+    public String s;
+
+    public ClassWithoutNoArgsConstructor(String s) {
+      this.s = s;
+    }
+  }
+
+  @Test
+  public void testClassWithoutNoArgsConstructor() {
+    GsonBuilder gsonBuilder = new GsonBuilder()
+      .addReflectionAccessFilter(new ReflectionAccessFilter() {
+        @Override public FilterResult check(Class<?> rawClass) {
+          // Even BLOCK_INACCESSIBLE should prevent usage of Unsafe for object creation
+          return FilterResult.BLOCK_INACCESSIBLE;
+        }
+      });
+    Gson gson = gsonBuilder.create();
+
+    try {
+      gson.fromJson("{}", ClassWithoutNoArgsConstructor.class);
+      fail();
+    } catch (JsonIOException expected) {
+      assertEquals(
+        "Unable to create instance of class com.google.gson.functional.ReflectionAccessFilterTest$ClassWithoutNoArgsConstructor; "
+        + "ReflectionAccessFilter does not permit using reflection or Unsafe. Register an InstanceCreator "
+        + "or a TypeAdapter for this type or adjust the access filter to allow using reflection.",
+        expected.getMessage()
+      );
+    }
+
+    // But should not fail when custom TypeAdapter is specified
+    gson = gson.newBuilder()
+      .registerTypeAdapter(ClassWithoutNoArgsConstructor.class, new TypeAdapter<ClassWithoutNoArgsConstructor>() {
+        @Override public ClassWithoutNoArgsConstructor read(JsonReader in) throws IOException {
+          in.skipValue();
+          return new ClassWithoutNoArgsConstructor("TypeAdapter");
+        }
+        @Override public void write(JsonWriter out, ClassWithoutNoArgsConstructor value) throws IOException {
+          throw new AssertionError("Not needed for test");
+        };
+      })
+      .create();
+    ClassWithoutNoArgsConstructor deserialized = gson.fromJson("{}", ClassWithoutNoArgsConstructor.class);
+    assertEquals("TypeAdapter", deserialized.s);
+
+    // But should not fail when custom InstanceCreator is specified
+    gson = gsonBuilder
+      .registerTypeAdapter(ClassWithoutNoArgsConstructor.class, new InstanceCreator<ClassWithoutNoArgsConstructor>() {
+        @Override public ClassWithoutNoArgsConstructor createInstance(Type type) {
+          return new ClassWithoutNoArgsConstructor("InstanceCreator");
+        }
+      })
+      .create();
+    deserialized = gson.fromJson("{}", ClassWithoutNoArgsConstructor.class);
+    assertEquals("InstanceCreator", deserialized.s);
+  }
+
+  /**
+   * When using {@link FilterResult#BLOCK_ALL}, registering only a {@link JsonSerializer}
+   * but not performing any deserialization should not throw any exception.
+   */
+  @Test
+  public void testBlockAllPartial() {
+    Gson gson = new GsonBuilder()
+      .addReflectionAccessFilter(new ReflectionAccessFilter() {
+        @Override public FilterResult check(Class<?> rawClass) {
+          return FilterResult.BLOCK_ALL;
+        }
+      })
+      .registerTypeAdapter(OtherClass.class, new JsonSerializer<OtherClass>() {
+        @Override public JsonElement serialize(OtherClass src, Type typeOfSrc, JsonSerializationContext context) {
+          return new JsonPrimitive(123);
+        }
+      })
+      .create();
+
+    String json = gson.toJson(new OtherClass());
+    assertEquals("123", json);
+
+    // But deserialization should fail
+    try {
+      gson.fromJson("{}", OtherClass.class);
+      fail();
+    } catch (JsonIOException expected) {
+      assertEquals(
+        "ReflectionAccessFilter does not permit using reflection for class com.google.gson.functional.ReflectionAccessFilterTest$OtherClass. "
+        + "Register a TypeAdapter for this type or adjust the access filter.",
+        expected.getMessage()
+      );
+    }
+  }
+
+  /**
+   * Should not fail when deserializing collection interface
+   * (Even though this goes through {@link ConstructorConstructor} as well)
+   */
+  @Test
+  public void testBlockAllCollectionInterface() {
+    Gson gson = new GsonBuilder()
+      .addReflectionAccessFilter(new ReflectionAccessFilter() {
+        @Override public FilterResult check(Class<?> rawClass) {
+          return FilterResult.BLOCK_ALL;
+        }
+      })
+      .create();
+    List<?> deserialized = gson.fromJson("[1.0]", List.class);
+    assertEquals(1.0, deserialized.get(0));
+  }
+
+  /**
+   * Should not fail when deserializing specific collection implementation
+   * (Even though this goes through {@link ConstructorConstructor} as well)
+   */
+  @Test
+  public void testBlockAllCollectionImplementation() {
+    Gson gson = new GsonBuilder()
+      .addReflectionAccessFilter(new ReflectionAccessFilter() {
+        @Override public FilterResult check(Class<?> rawClass) {
+          return FilterResult.BLOCK_ALL;
+        }
+      })
+      .create();
+    List<?> deserialized = gson.fromJson("[1.0]", LinkedList.class);
+    assertEquals(1.0, deserialized.get(0));
+  }
+
+  /**
+   * When trying to deserialize interface an exception for that should
+   * be thrown, even if {@link FilterResult#BLOCK_INACCESSIBLE} is used
+   */
+  @Test
+  public void testBlockInaccessibleInterface() {
+    Gson gson = new GsonBuilder()
+      .addReflectionAccessFilter(new ReflectionAccessFilter() {
+        @Override public FilterResult check(Class<?> rawClass) {
+          return FilterResult.BLOCK_INACCESSIBLE;
+        }
+      })
+      .create();
+
+    try {
+      gson.fromJson("{}", Runnable.class);
+      fail();
+    } catch (JsonIOException expected) {
+      assertEquals(
+        "Interfaces can't be instantiated! Register an InstanceCreator or a TypeAdapter for "
+        + "this type. Interface name: java.lang.Runnable",
+        expected.getMessage()
+      );
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/ReflectionAccessTest.java b/gson/src/test/java/com/google/gson/functional/ReflectionAccessTest.java
new file mode 100644
index 0000000..ece3512
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/ReflectionAccessTest.java
@@ -0,0 +1,123 @@
+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.GsonBuilder;
+import com.google.gson.JsonIOException;
+import com.google.gson.TypeAdapter;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
+import java.lang.reflect.ReflectPermission;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.security.Permission;
+import java.util.Collections;
+import java.util.concurrent.atomic.AtomicBoolean;
+import org.junit.Test;
+
+public class ReflectionAccessTest {
+  @SuppressWarnings("unused")
+  private static class ClassWithPrivateMembers {
+    private String s;
+
+    private ClassWithPrivateMembers() {
+    }
+  }
+
+  private static Class<?> loadClassWithDifferentClassLoader(Class<?> c) throws Exception {
+    URL url = c.getProtectionDomain().getCodeSource().getLocation();
+    URLClassLoader classLoader = new URLClassLoader(new URL[] { url }, null);
+    return classLoader.loadClass(c.getName());
+  }
+
+  @Test
+  public void testRestrictiveSecurityManager() throws Exception {
+    // Must use separate class loader, otherwise permission is not checked, see Class.getDeclaredFields()
+    Class<?> clazz = loadClassWithDifferentClassLoader(ClassWithPrivateMembers.class);
+
+    final Permission accessDeclaredMembers = new RuntimePermission("accessDeclaredMembers");
+    final Permission suppressAccessChecks = new ReflectPermission("suppressAccessChecks");
+    SecurityManager original = System.getSecurityManager();
+    SecurityManager restrictiveManager = new SecurityManager() {
+      @Override
+      public void checkPermission(Permission perm) {
+        if (accessDeclaredMembers.equals(perm)) {
+          throw new SecurityException("Gson: no-member-access");
+        }
+        if (suppressAccessChecks.equals(perm)) {
+          throw new SecurityException("Gson: no-suppress-access-check");
+        }
+      }
+    };
+    System.setSecurityManager(restrictiveManager);
+
+    try {
+      Gson gson = new Gson();
+      try {
+        // Getting reflection based adapter should fail
+        gson.getAdapter(clazz);
+        fail();
+      } catch (SecurityException e) {
+        assertEquals("Gson: no-member-access", e.getMessage());
+      }
+
+      final AtomicBoolean wasReadCalled = new AtomicBoolean(false);
+      gson = new GsonBuilder()
+        .registerTypeAdapter(clazz, new TypeAdapter<Object>() {
+          @Override
+          public void write(JsonWriter out, Object value) throws IOException {
+            out.value("custom-write");
+          }
+
+          @Override
+          public Object read(JsonReader in) throws IOException {
+            in.skipValue();
+            wasReadCalled.set(true);
+            return null;
+          }}
+        )
+        .create();
+
+      assertEquals("\"custom-write\"", gson.toJson(null, clazz));
+      assertNull(gson.fromJson("{}", clazz));
+      assertTrue(wasReadCalled.get());
+    } finally {
+      System.setSecurityManager(original);
+    }
+  }
+
+  /**
+   * Test serializing an instance of a non-accessible internal class, but where
+   * Gson supports serializing one of its superinterfaces.
+   *
+   * <p>Here {@link Collections#emptyList()} is used which returns an instance
+   * of the internal class {@code java.util.Collections.EmptyList}. Gson should
+   * serialize the object as {@code List} despite the internal class not being
+   * accessible.
+   *
+   * <p>See https://github.com/google/gson/issues/1875
+   */
+  @Test
+  public void testSerializeInternalImplementationObject() {
+    Gson gson = new Gson();
+    String json = gson.toJson(Collections.emptyList());
+    assertEquals("[]", json);
+
+    // But deserialization should fail
+    Class<?> internalClass = Collections.emptyList().getClass();
+    try {
+      gson.fromJson("{}", internalClass);
+      fail("Missing exception; test has to be run with `--illegal-access=deny`");
+    } catch (JsonIOException expected) {
+      assertTrue(expected.getMessage().startsWith(
+          "Failed making constructor 'java.util.Collections$EmptyList#EmptyList()' accessible; "
+          + "either change its visibility or write a custom InstanceCreator or TypeAdapter for its declaring type"
+      ));
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/ReusedTypeVariablesFullyResolveTest.java b/gson/src/test/java/com/google/gson/functional/ReusedTypeVariablesFullyResolveTest.java
new file mode 100644
index 0000000..10c7c6d
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/ReusedTypeVariablesFullyResolveTest.java
@@ -0,0 +1,55 @@
+package com.google.gson.functional;
+
+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.GsonBuilder;
+import org.junit.Before;
+import org.junit.Test;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.Set;
+
+/**
+ * This test covers the scenario described in #1390 where a type variable needs to be used
+ * by a type definition multiple times.  Both type variable references should resolve to the
+ * same underlying concrete type.
+ */
+public class ReusedTypeVariablesFullyResolveTest {
+
+  private Gson gson;
+
+  @Before
+  public void setUp() {
+    gson = new GsonBuilder().create();
+  }
+
+  @SuppressWarnings("ConstantConditions") // The instances were being unmarshaled as Strings instead of TestEnums
+  @Test
+  public void testGenericsPreservation() {
+    TestEnumSetCollection withSet = gson.fromJson("{\"collection\":[\"ONE\",\"THREE\"]}", TestEnumSetCollection.class);
+    Iterator<TestEnum> iterator = withSet.collection.iterator();
+    assertNotNull(withSet);
+    assertNotNull(withSet.collection);
+    assertEquals(2, withSet.collection.size());
+    TestEnum first = iterator.next();
+    TestEnum second = iterator.next();
+
+    assertTrue(first instanceof TestEnum);
+    assertTrue(second instanceof TestEnum);
+  }
+
+  enum TestEnum { ONE, TWO, THREE }
+
+  private static class TestEnumSetCollection extends SetCollection<TestEnum> {}
+
+  private static class SetCollection<T> extends BaseCollection<T, Set<T>> {}
+
+  private static class BaseCollection<U, C extends Collection<U>>
+  {
+    public C collection;
+  }
+
+}
diff --git a/gson/src/test/java/com/google/gson/functional/RuntimeTypeAdapterFactoryFunctionalTest.java b/gson/src/test/java/com/google/gson/functional/RuntimeTypeAdapterFactoryFunctionalTest.java
new file mode 100644
index 0000000..0c6bd07
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/RuntimeTypeAdapterFactoryFunctionalTest.java
@@ -0,0 +1,203 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.functional;
+
+import java.io.IOException;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+import junit.framework.TestCase;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParseException;
+import com.google.gson.JsonPrimitive;
+import com.google.gson.TypeAdapter;
+import com.google.gson.TypeAdapterFactory;
+import com.google.gson.annotations.JsonAdapter;
+import com.google.gson.internal.Streams;
+import com.google.gson.reflect.TypeToken;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonWriter;
+
+/**
+ * Functional tests for the RuntimeTypeAdapterFactory feature in extras.
+ */
+public final class RuntimeTypeAdapterFactoryFunctionalTest extends TestCase {
+
+  private final Gson gson = new Gson();
+
+  /**
+   * This test also ensures that {@link TypeAdapterFactory} registered through {@link JsonAdapter}
+   * work correctly for {@link Gson#getDelegateAdapter(TypeAdapterFactory, TypeToken)}.
+   */
+  public void testSubclassesAutomaticallySerialized() throws Exception {
+    Shape shape = new Circle(25);
+    String json = gson.toJson(shape);
+    shape = gson.fromJson(json, Shape.class);
+    assertEquals(25, ((Circle)shape).radius);
+
+    shape = new Square(15);
+    json = gson.toJson(shape);
+    shape = gson.fromJson(json, Shape.class);
+    assertEquals(15, ((Square)shape).side);
+    assertEquals(ShapeType.SQUARE, shape.type);
+  }
+
+  @JsonAdapter(Shape.JsonAdapterFactory.class)
+  static class Shape {
+    final ShapeType type;
+    Shape(ShapeType type) { this.type = type; }
+    private static final class JsonAdapterFactory extends RuntimeTypeAdapterFactory<Shape> {
+      public JsonAdapterFactory() {
+        super(Shape.class, "type");
+        registerSubtype(Circle.class, ShapeType.CIRCLE.toString());
+        registerSubtype(Square.class, ShapeType.SQUARE.toString());
+      }
+    }
+  }
+
+  public enum ShapeType {
+    SQUARE, CIRCLE
+  }
+
+  private static final class Circle extends Shape {
+    final int radius;
+    Circle(int radius) { super(ShapeType.CIRCLE); this.radius = radius; }
+  }
+
+  private static final class Square extends Shape {
+    final int side;
+    Square(int side) { super(ShapeType.SQUARE); this.side = side; }
+  }
+
+  // Copied from the extras package
+  static class RuntimeTypeAdapterFactory<T> implements TypeAdapterFactory {
+    private final Class<?> baseType;
+    private final String typeFieldName;
+    private final Map<String, Class<?>> labelToSubtype = new LinkedHashMap<>();
+    private final Map<Class<?>, String> subtypeToLabel = new LinkedHashMap<>();
+
+    protected RuntimeTypeAdapterFactory(Class<?> baseType, String typeFieldName) {
+      if (typeFieldName == null || baseType == null) {
+        throw new NullPointerException();
+      }
+      this.baseType = baseType;
+      this.typeFieldName = typeFieldName;
+    }
+
+    /**
+     * Creates a new runtime type adapter using for {@code baseType} using {@code
+     * typeFieldName} as the type field name. Type field names are case sensitive.
+     */
+    public static <T> RuntimeTypeAdapterFactory<T> of(Class<T> baseType, String typeFieldName) {
+      return new RuntimeTypeAdapterFactory<>(baseType, typeFieldName);
+    }
+
+    /**
+     * Creates a new runtime type adapter for {@code baseType} using {@code "type"} as
+     * the type field name.
+     */
+    public static <T> RuntimeTypeAdapterFactory<T> of(Class<T> baseType) {
+      return new RuntimeTypeAdapterFactory<>(baseType, "type");
+    }
+
+    /**
+     * Registers {@code type} identified by {@code label}. Labels are case
+     * sensitive.
+     *
+     * @throws IllegalArgumentException if either {@code type} or {@code label}
+     *     have already been registered on this type adapter.
+     */
+    public RuntimeTypeAdapterFactory<T> registerSubtype(Class<? extends T> type, String label) {
+      if (type == null || label == null) {
+        throw new NullPointerException();
+      }
+      if (subtypeToLabel.containsKey(type) || labelToSubtype.containsKey(label)) {
+        throw new IllegalArgumentException("types and labels must be unique");
+      }
+      labelToSubtype.put(label, type);
+      subtypeToLabel.put(type, label);
+      return this;
+    }
+
+    /**
+     * Registers {@code type} identified by its {@link Class#getSimpleName simple
+     * name}. Labels are case sensitive.
+     *
+     * @throws IllegalArgumentException if either {@code type} or its simple name
+     *     have already been registered on this type adapter.
+     */
+    public RuntimeTypeAdapterFactory<T> registerSubtype(Class<? extends T> type) {
+      return registerSubtype(type, type.getSimpleName());
+    }
+
+    @Override public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
+      if (type.getRawType() != baseType) {
+        return null;
+      }
+
+      final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<>();
+      final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<>();
+      for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
+        TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue()));
+        labelToDelegate.put(entry.getKey(), delegate);
+        subtypeToDelegate.put(entry.getValue(), delegate);
+      }
+
+      return new TypeAdapter<R>() {
+        @Override public R read(JsonReader in) throws IOException {
+          JsonElement jsonElement = Streams.parse(in);
+          JsonElement labelJsonElement = jsonElement.getAsJsonObject().get(typeFieldName);
+          if (labelJsonElement == null) {
+            throw new JsonParseException("cannot deserialize " + baseType
+                + " because it does not define a field named " + typeFieldName);
+          }
+          String label = labelJsonElement.getAsString();
+          @SuppressWarnings("unchecked") // registration requires that subtype extends T
+          TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label);
+          if (delegate == null) {
+            throw new JsonParseException("cannot deserialize " + baseType + " subtype named "
+                + label + "; did you forget to register a subtype?");
+          }
+          return delegate.fromJsonTree(jsonElement);
+        }
+
+        @Override public void write(JsonWriter out, R value) throws IOException {
+          Class<?> srcType = value.getClass();
+          String label = subtypeToLabel.get(srcType);
+          @SuppressWarnings("unchecked") // registration requires that subtype extends T
+          TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType);
+          if (delegate == null) {
+            throw new JsonParseException("cannot serialize " + srcType.getName()
+                + "; did you forget to register a subtype?");
+          }
+          JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject();
+          if (!jsonObject.has(typeFieldName)) {
+            JsonObject clone = new JsonObject();
+            clone.add(typeFieldName, new JsonPrimitive(label));
+            for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
+              clone.add(e.getKey(), e.getValue());
+            }
+            jsonObject = clone;
+          }
+          Streams.write(jsonObject, out);
+        }
+      };
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/SecurityTest.java b/gson/src/test/java/com/google/gson/functional/SecurityTest.java
new file mode 100644
index 0000000..aa1c2d4
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/SecurityTest.java
@@ -0,0 +1,86 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.functional;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.common.TestTypes.BagOfPrimitives;
+
+import junit.framework.TestCase;
+
+/**
+ * Tests for security-related aspects of Gson
+ * 
+ * @author Inderjeet Singh
+ */
+public class SecurityTest extends TestCase {
+  /**
+   * Keep this in sync with Gson.JSON_NON_EXECUTABLE_PREFIX
+   */
+  private static final String JSON_NON_EXECUTABLE_PREFIX = ")]}'\n";
+
+  private GsonBuilder gsonBuilder;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    gsonBuilder = new GsonBuilder();
+  }
+
+  public void testNonExecutableJsonSerialization() {
+    Gson gson = gsonBuilder.generateNonExecutableJson().create();
+    String json = gson.toJson(new BagOfPrimitives());
+    assertTrue(json.startsWith(JSON_NON_EXECUTABLE_PREFIX));
+  }
+  
+  public void testNonExecutableJsonDeserialization() {
+    String json = JSON_NON_EXECUTABLE_PREFIX + "{longValue:1}";
+    Gson gson = gsonBuilder.create();
+    BagOfPrimitives target = gson.fromJson(json, BagOfPrimitives.class);
+    assertEquals(1, target.longValue);
+  }
+  
+  public void testJsonWithNonExectuableTokenSerialization() {
+    Gson gson = gsonBuilder.generateNonExecutableJson().create();
+    String json = gson.toJson(JSON_NON_EXECUTABLE_PREFIX);
+    assertTrue(json.contains(")]}'\n"));
+  }
+  
+  /**
+   *  Gson should be able to deserialize a stream with non-exectuable token even if it is created
+   *  without {@link GsonBuilder#generateNonExecutableJson()}.
+   */
+  public void testJsonWithNonExectuableTokenWithRegularGsonDeserialization() {
+    Gson gson = gsonBuilder.create();
+    String json = JSON_NON_EXECUTABLE_PREFIX + "{stringValue:')]}\\u0027\\n'}";
+    BagOfPrimitives target = gson.fromJson(json, BagOfPrimitives.class);
+    assertEquals(")]}'\n", target.stringValue);
+  }  
+  
+  /**
+   *  Gson should be able to deserialize a stream with non-exectuable token if it is created
+   *  with {@link GsonBuilder#generateNonExecutableJson()}.
+   */
+  public void testJsonWithNonExectuableTokenWithConfiguredGsonDeserialization() {
+    // Gson should be able to deserialize a stream with non-exectuable token even if it is created 
+    Gson gson = gsonBuilder.generateNonExecutableJson().create();
+    String json = JSON_NON_EXECUTABLE_PREFIX + "{intValue:2,stringValue:')]}\\u0027\\n'}";
+    BagOfPrimitives target = gson.fromJson(json, BagOfPrimitives.class);
+    assertEquals(")]}'\n", target.stringValue);
+    assertEquals(2, target.intValue);
+  }  
+}
diff --git a/gson/src/test/java/com/google/gson/functional/SerializedNameTest.java b/gson/src/test/java/com/google/gson/functional/SerializedNameTest.java
new file mode 100644
index 0000000..0314ae0
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/SerializedNameTest.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2015 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.functional;
+
+import com.google.gson.Gson;
+import com.google.gson.annotations.SerializedName;
+
+import junit.framework.TestCase;
+
+public final class SerializedNameTest extends TestCase {
+  private final Gson gson = new Gson();
+
+  public void testFirstNameIsChosenForSerialization() {
+    MyClass target = new MyClass("v1", "v2");
+    // Ensure name1 occurs exactly once, and name2 and name3 don't appear
+    assertEquals("{\"name\":\"v1\",\"name1\":\"v2\"}", gson.toJson(target));
+  }
+
+  public void testMultipleNamesDeserializedCorrectly() {
+    assertEquals("v1", gson.fromJson("{'name':'v1'}", MyClass.class).a);
+
+    // Both name1 and name2 gets deserialized to b
+    assertEquals("v11", gson.fromJson("{'name1':'v11'}", MyClass.class).b);
+    assertEquals("v2", gson.fromJson("{'name2':'v2'}", MyClass.class).b);
+    assertEquals("v3", gson.fromJson("{'name3':'v3'}", MyClass.class).b);
+  }
+
+  public void testMultipleNamesInTheSameString() {
+    // The last value takes precedence
+    assertEquals("v3", gson.fromJson("{'name1':'v1','name2':'v2','name3':'v3'}", MyClass.class).b);
+  }
+
+  private static final class MyClass {
+    @SerializedName("name") String a;
+    @SerializedName(value="name1", alternate={"name2", "name3"}) String b;
+    MyClass(String a, String b) {
+      this.a = a;
+      this.b = b;
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/StreamingTypeAdaptersTest.java b/gson/src/test/java/com/google/gson/functional/StreamingTypeAdaptersTest.java
new file mode 100644
index 0000000..6884412
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/StreamingTypeAdaptersTest.java
@@ -0,0 +1,244 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.functional;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonPrimitive;
+import com.google.gson.JsonSyntaxException;
+import com.google.gson.TypeAdapter;
+import com.google.gson.reflect.TypeToken;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import junit.framework.TestCase;
+
+public final class StreamingTypeAdaptersTest extends TestCase {
+  private Gson miniGson = new GsonBuilder().create();
+  private TypeAdapter<Truck> truckAdapter = miniGson.getAdapter(Truck.class);
+  private TypeAdapter<Map<String, Double>> mapAdapter
+      = miniGson.getAdapter(new TypeToken<Map<String, Double>>() {});
+
+  public void testSerialize() {
+    Truck truck = new Truck();
+    truck.passengers = Arrays.asList(new Person("Jesse", 29), new Person("Jodie", 29));
+    truck.horsePower = 300;
+
+    assertEquals("{'horsePower':300.0,"
+        + "'passengers':[{'age':29,'name':'Jesse'},{'age':29,'name':'Jodie'}]}",
+        truckAdapter.toJson(truck).replace('\"', '\''));
+  }
+
+  public void testDeserialize() throws IOException {
+    String json = "{'horsePower':300.0,"
+        + "'passengers':[{'age':29,'name':'Jesse'},{'age':29,'name':'Jodie'}]}";
+    Truck truck = truckAdapter.fromJson(json.replace('\'', '\"'));
+    assertEquals(300.0, truck.horsePower);
+    assertEquals(Arrays.asList(new Person("Jesse", 29), new Person("Jodie", 29)), truck.passengers);
+  }
+
+  public void testSerializeNullField() {
+    Truck truck = new Truck();
+    truck.passengers = null;
+    assertEquals("{'horsePower':0.0,'passengers':null}",
+        truckAdapter.toJson(truck).replace('\"', '\''));
+  }
+
+  public void testDeserializeNullField() throws IOException {
+    Truck truck = truckAdapter.fromJson("{'horsePower':0.0,'passengers':null}".replace('\'', '\"'));
+    assertNull(truck.passengers);
+  }
+
+  public void testSerializeNullObject() {
+    Truck truck = new Truck();
+    truck.passengers = Arrays.asList((Person) null);
+    assertEquals("{'horsePower':0.0,'passengers':[null]}",
+        truckAdapter.toJson(truck).replace('\"', '\''));
+  }
+
+  public void testDeserializeNullObject() throws IOException {
+    Truck truck = truckAdapter.fromJson("{'horsePower':0.0,'passengers':[null]}".replace('\'', '\"'));
+    assertEquals(Arrays.asList((Person) null), truck.passengers);
+  }
+
+  public void testSerializeWithCustomTypeAdapter() {
+    usePersonNameAdapter();
+    Truck truck = new Truck();
+    truck.passengers = Arrays.asList(new Person("Jesse", 29), new Person("Jodie", 29));
+    assertEquals("{'horsePower':0.0,'passengers':['Jesse','Jodie']}",
+        truckAdapter.toJson(truck).replace('\"', '\''));
+  }
+
+  public void testDeserializeWithCustomTypeAdapter() throws IOException {
+    usePersonNameAdapter();
+    Truck truck = truckAdapter.fromJson("{'horsePower':0.0,'passengers':['Jesse','Jodie']}".replace('\'', '\"'));
+    assertEquals(Arrays.asList(new Person("Jesse", -1), new Person("Jodie", -1)), truck.passengers);
+  }
+
+  private void usePersonNameAdapter() {
+    TypeAdapter<Person> personNameAdapter = new TypeAdapter<Person>() {
+      @Override public Person read(JsonReader in) throws IOException {
+        String name = in.nextString();
+        return new Person(name, -1);
+      }
+      @Override public void write(JsonWriter out, Person value) throws IOException {
+        out.value(value.name);
+      }
+    };
+    miniGson = new GsonBuilder().registerTypeAdapter(Person.class, personNameAdapter).create();
+    truckAdapter = miniGson.getAdapter(Truck.class);
+  }
+
+  public void testSerializeMap() {
+    Map<String, Double> map = new LinkedHashMap<>();
+    map.put("a", 5.0);
+    map.put("b", 10.0);
+    assertEquals("{'a':5.0,'b':10.0}", mapAdapter.toJson(map).replace('"', '\''));
+  }
+
+  public void testDeserializeMap() throws IOException {
+    Map<String, Double> map = new LinkedHashMap<>();
+    map.put("a", 5.0);
+    map.put("b", 10.0);
+    assertEquals(map, mapAdapter.fromJson("{'a':5.0,'b':10.0}".replace('\'', '\"')));
+  }
+
+  public void testSerialize1dArray() {
+    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 }));
+  }
+
+  public void testDeserialize1dArray() throws IOException {
+    TypeAdapter<double[]> arrayAdapter = miniGson.getAdapter(new TypeToken<double[]>() {});
+    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));
+  }
+
+  public void testSerialize2dArray() {
+    TypeAdapter<double[][]> arrayAdapter = miniGson.getAdapter(new TypeToken<double[][]>() {});
+    double[][] array = { {1.0, 2.0 }, { 3.0 } };
+    assertEquals("[[1.0,2.0],[3.0]]", arrayAdapter.toJson(array));
+  }
+
+  public void testDeserialize2dArray() throws IOException {
+    TypeAdapter<double[][]> arrayAdapter = miniGson.getAdapter(new TypeToken<double[][]>() {});
+    double[][] array = arrayAdapter.fromJson("[[1.0,2.0],[3.0]]");
+    double[][] expected = { {1.0, 2.0 }, { 3.0 } };
+    assertTrue(Arrays.toString(array), Arrays.deepEquals(expected, array));
+  }
+
+  public void testNullSafe() {
+    TypeAdapter<Person> typeAdapter = new TypeAdapter<Person>() {
+      @Override public Person read(JsonReader in) throws IOException {
+        String[] values = in.nextString().split(",");
+        return new Person(values[0], Integer.parseInt(values[1]));
+      }
+      @Override public void write(JsonWriter out, Person person) throws IOException {
+        out.value(person.name + "," + person.age);
+      }
+    };
+    Gson gson = new GsonBuilder().registerTypeAdapter(
+        Person.class, typeAdapter).create();
+    Truck truck = new Truck();
+    truck.horsePower = 1.0D;
+    truck.passengers = new ArrayList<>();
+    truck.passengers.add(null);
+    truck.passengers.add(new Person("jesse", 30));
+    try {
+      gson.toJson(truck, Truck.class);
+      fail();
+    } catch (NullPointerException expected) {}
+    String json = "{horsePower:1.0,passengers:[null,'jesse,30']}";
+    try {
+      gson.fromJson(json, Truck.class);
+      fail();
+    } catch (JsonSyntaxException expected) {}
+    gson = new GsonBuilder().registerTypeAdapter(Person.class, typeAdapter.nullSafe()).create();
+    assertEquals("{\"horsePower\":1.0,\"passengers\":[null,\"jesse,30\"]}",
+        gson.toJson(truck, Truck.class));
+    truck = gson.fromJson(json, Truck.class);
+    assertEquals(1.0D, truck.horsePower);
+    assertNull(truck.passengers.get(0));
+    assertEquals("jesse", truck.passengers.get(1).name);
+  }
+
+  public void testSerializeRecursive() {
+    TypeAdapter<Node> nodeAdapter = miniGson.getAdapter(Node.class);
+    Node root = new Node("root");
+    root.left = new Node("left");
+    root.right = new Node("right");
+    assertEquals("{'label':'root',"
+        + "'left':{'label':'left','left':null,'right':null},"
+        + "'right':{'label':'right','left':null,'right':null}}",
+        nodeAdapter.toJson(root).replace('"', '\''));
+  }
+  
+  public void testFromJsonTree() {
+    JsonObject truckObject = new JsonObject();
+    truckObject.add("horsePower", new JsonPrimitive(300));
+    JsonArray passengersArray = new JsonArray();
+    JsonObject jesseObject = new JsonObject();
+    jesseObject.add("age", new JsonPrimitive(30));
+    jesseObject.add("name", new JsonPrimitive("Jesse"));
+    passengersArray.add(jesseObject);
+    truckObject.add("passengers", passengersArray);
+
+    Truck truck = truckAdapter.fromJsonTree(truckObject);
+    assertEquals(300.0, truck.horsePower);
+    assertEquals(Arrays.asList(new Person("Jesse", 30)), truck.passengers);
+  }
+
+  static class Truck {
+    double horsePower;
+    List<Person> passengers = Collections.emptyList();
+  }
+
+  static class Person {
+    int age;
+    String name;
+    Person(String name, int age) {
+      this.name = name;
+      this.age = age;
+    }
+
+    @Override public boolean equals(Object o) {
+      return o instanceof Person
+          && ((Person) o).name.equals(name)
+          && ((Person) o).age == age;
+    }
+    @Override public int hashCode() {
+      return name.hashCode() ^ age;
+    }
+  }
+
+  static class Node {
+    String label;
+    Node left;
+    Node right;
+    Node(String label) {
+      this.label = label;
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/StringTest.java b/gson/src/test/java/com/google/gson/functional/StringTest.java
new file mode 100644
index 0000000..7dcf6f0
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/StringTest.java
@@ -0,0 +1,140 @@
+package com.google.gson.functional;
+
+import com.google.gson.Gson;
+
+import junit.framework.TestCase;
+
+/**
+ * Functional tests for Json serialization and deserialization of strings.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public class StringTest extends TestCase {
+  private Gson gson;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    gson = new Gson();
+  }
+
+  public void testStringValueSerialization() throws Exception {
+    String value = "someRandomStringValue";
+    assertEquals('"' + value + '"', gson.toJson(value));
+  }
+
+  public void testStringValueDeserialization() throws Exception {
+    String value = "someRandomStringValue";
+    String actual = gson.fromJson("\"" + value + "\"", String.class);
+    assertEquals(value, actual);
+  }
+
+  public void testSingleQuoteInStringSerialization() throws Exception {
+    String valueWithQuotes = "beforeQuote'afterQuote";
+    String jsonRepresentation = gson.toJson(valueWithQuotes);
+    assertEquals(valueWithQuotes, gson.fromJson(jsonRepresentation, String.class));
+  }
+
+  public void testEscapedCtrlNInStringSerialization() throws Exception {
+    String value = "a\nb";
+    String json = gson.toJson(value);
+    assertEquals("\"a\\nb\"", json);
+  }
+
+  public void testEscapedCtrlNInStringDeserialization() throws Exception {
+    String json = "'a\\nb'";
+    String actual = gson.fromJson(json, String.class);
+    assertEquals("a\nb", actual);
+  }
+
+  public void testEscapedCtrlRInStringSerialization() throws Exception {
+    String value = "a\rb";
+    String json = gson.toJson(value);
+    assertEquals("\"a\\rb\"", json);
+  }
+
+  public void testEscapedCtrlRInStringDeserialization() throws Exception {
+    String json = "'a\\rb'";
+    String actual = gson.fromJson(json, String.class);
+    assertEquals("a\rb", actual);
+  }
+
+  public void testEscapedBackslashInStringSerialization() throws Exception {
+    String value = "a\\b";
+    String json = gson.toJson(value);
+    assertEquals("\"a\\\\b\"", json);
+  }
+
+  public void testEscapedBackslashInStringDeserialization() throws Exception {
+    String actual = gson.fromJson("'a\\\\b'", String.class);
+    assertEquals("a\\b", actual);
+  }
+
+  public void testSingleQuoteInStringDeserialization() throws Exception {
+    String value = "beforeQuote'afterQuote";
+    String actual = gson.fromJson("\"" + value + "\"", String.class);
+    assertEquals(value, actual);
+  }
+
+  public void testEscapingQuotesInStringSerialization() throws Exception {
+    String valueWithQuotes = "beforeQuote\"afterQuote";
+    String jsonRepresentation = gson.toJson(valueWithQuotes);
+    String target = gson.fromJson(jsonRepresentation, String.class);
+    assertEquals(valueWithQuotes, target);
+  }
+
+  public void testEscapingQuotesInStringDeserialization() throws Exception {
+    String value = "beforeQuote\\\"afterQuote";
+    String actual = gson.fromJson("\"" + value + "\"", String.class);
+    String expected = "beforeQuote\"afterQuote";
+    assertEquals(expected, actual);
+  }
+
+  public void testStringValueAsSingleElementArraySerialization() throws Exception {
+    String[] target = {"abc"};
+    assertEquals("[\"abc\"]", gson.toJson(target));
+    assertEquals("[\"abc\"]", gson.toJson(target, String[].class));
+  }
+
+  public void testStringWithEscapedSlashDeserialization() {
+    String value = "/";
+    String json = "'\\/'";
+    String actual = gson.fromJson(json, String.class);
+    assertEquals(value, actual);
+  }
+
+  /**
+   * Created in response to http://groups.google.com/group/google-gson/browse_thread/thread/2431d4a3d0d6cb23
+   */
+  public void testAssignmentCharSerialization() {
+    String value = "abc=";
+    String json = gson.toJson(value);
+    assertEquals("\"abc\\u003d\"", json);
+  }
+
+  /**
+   * Created in response to http://groups.google.com/group/google-gson/browse_thread/thread/2431d4a3d0d6cb23
+   */
+  public void testAssignmentCharDeserialization() {
+    String json = "\"abc=\"";
+    String value = gson.fromJson(json, String.class);
+    assertEquals("abc=", value);
+
+    json = "'abc\u003d'";
+    value = gson.fromJson(json, String.class);
+    assertEquals("abc=", value);
+  }
+
+  public void testJavascriptKeywordsInStringSerialization() {
+    String value = "null true false function";
+    String json = gson.toJson(value);
+    assertEquals("\"" + value + "\"", json);
+  }
+
+  public void testJavascriptKeywordsInStringDeserialization() {
+    String json = "'null true false function'";
+    String value = gson.fromJson(json, String.class);
+    assertEquals(json.substring(1, json.length() - 1), value);
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/ToNumberPolicyFunctionalTest.java b/gson/src/test/java/com/google/gson/functional/ToNumberPolicyFunctionalTest.java
new file mode 100644
index 0000000..3e261d5
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/ToNumberPolicyFunctionalTest.java
@@ -0,0 +1,134 @@
+/*
+ * Copyright (C) 2021 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.functional;
+
+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 com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.ToNumberPolicy;
+import com.google.gson.ToNumberStrategy;
+import com.google.gson.internal.LazilyParsedNumber;
+import com.google.gson.reflect.TypeToken;
+import com.google.gson.stream.JsonReader;
+import junit.framework.TestCase;
+
+public class ToNumberPolicyFunctionalTest extends TestCase {
+  public void testDefault() {
+    Gson gson = new Gson();
+    assertEquals(null, gson.fromJson("null", Object.class));
+    assertEquals(10D, gson.fromJson("10", Object.class));
+    assertEquals(null, gson.fromJson("null", Number.class));
+    assertEquals(new LazilyParsedNumber("10"), gson.fromJson("10", Number.class));
+  }
+
+  public void testAsDoubles() {
+    Gson gson = new GsonBuilder()
+        .setObjectToNumberStrategy(ToNumberPolicy.DOUBLE)
+        .setNumberToNumberStrategy(ToNumberPolicy.DOUBLE)
+        .create();
+    assertEquals(null, gson.fromJson("null", Object.class));
+    assertEquals(10.0, gson.fromJson("10", Object.class));
+    assertEquals(null, gson.fromJson("null", Number.class));
+    assertEquals(10.0, gson.fromJson("10", Number.class));
+  }
+
+  public void testAsLazilyParsedNumbers() {
+    Gson gson = new GsonBuilder()
+        .setObjectToNumberStrategy(ToNumberPolicy.LAZILY_PARSED_NUMBER)
+        .setNumberToNumberStrategy(ToNumberPolicy.LAZILY_PARSED_NUMBER)
+        .create();
+    assertEquals(null, gson.fromJson("null", Object.class));
+    assertEquals(new LazilyParsedNumber("10"), gson.fromJson("10", Object.class));
+    assertEquals(null, gson.fromJson("null", Number.class));
+    assertEquals(new LazilyParsedNumber("10"), gson.fromJson("10", Number.class));
+  }
+
+  public void testAsLongsOrDoubles() {
+    Gson gson = new GsonBuilder()
+        .setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
+        .setNumberToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
+        .create();
+    assertEquals(null, gson.fromJson("null", Object.class));
+    assertEquals(10L, gson.fromJson("10", Object.class));
+    assertEquals(10.0, gson.fromJson("10.0", Object.class));
+    assertEquals(null, gson.fromJson("null", Number.class));
+    assertEquals(10L, gson.fromJson("10", Number.class));
+    assertEquals(10.0, gson.fromJson("10.0", Number.class));
+  }
+
+  public void testAsBigDecimals() {
+    Gson gson = new GsonBuilder()
+        .setObjectToNumberStrategy(ToNumberPolicy.BIG_DECIMAL)
+        .setNumberToNumberStrategy(ToNumberPolicy.BIG_DECIMAL)
+        .create();
+    assertEquals(null, gson.fromJson("null", Object.class));
+    assertEquals(new BigDecimal("10"), gson.fromJson("10", Object.class));
+    assertEquals(new BigDecimal("10.0"), gson.fromJson("10.0", Object.class));
+    assertEquals(null, gson.fromJson("null", Number.class));
+    assertEquals(new BigDecimal("10"), gson.fromJson("10", Number.class));
+    assertEquals(new BigDecimal("10.0"), gson.fromJson("10.0", Number.class));
+    assertEquals(new BigDecimal("3.141592653589793238462643383279"), gson.fromJson("3.141592653589793238462643383279", BigDecimal.class));
+    assertEquals(new BigDecimal("1e400"), gson.fromJson("1e400", BigDecimal.class));
+  }
+
+  public void testAsListOfLongsOrDoubles() {
+    Gson gson = new GsonBuilder()
+        .setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
+        .setNumberToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
+        .create();
+    List<Object> expected = new LinkedList<>();
+    expected.add(null);
+    expected.add(10L);
+    expected.add(10.0);
+    Type objectCollectionType = new TypeToken<Collection<Object>>() { }.getType();
+    Collection<Object> objects = gson.fromJson("[null,10,10.0]", objectCollectionType);
+    assertEquals(expected, objects);
+    Type numberCollectionType = new TypeToken<Collection<Number>>() { }.getType();
+    Collection<Object> numbers = gson.fromJson("[null,10,10.0]", numberCollectionType);
+    assertEquals(expected, numbers);
+  }
+
+  public void testCustomStrategiesCannotAffectConcreteDeclaredNumbers() {
+    ToNumberStrategy fail = new ToNumberStrategy() {
+      @Override
+      public Byte readNumber(JsonReader in) {
+        throw new UnsupportedOperationException();
+      }
+    };
+    Gson gson = new GsonBuilder()
+        .setObjectToNumberStrategy(fail)
+        .setNumberToNumberStrategy(fail)
+        .create();
+    List<Object> numbers = gson.fromJson("[null, 10, 20, 30]", new TypeToken<List<Byte>>() {}.getType());
+    assertEquals(Arrays.asList(null, (byte) 10, (byte) 20, (byte) 30), numbers);
+    try {
+      gson.fromJson("[null, 10, 20, 30]", new TypeToken<List<Object>>() {}.getType());
+      fail();
+    } catch (UnsupportedOperationException ex) {
+    }
+    try {
+      gson.fromJson("[null, 10, 20, 30]", new TypeToken<List<Number>>() {}.getType());
+      fail();
+    } catch (UnsupportedOperationException ex) {
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/TreeTypeAdaptersTest.java b/gson/src/test/java/com/google/gson/functional/TreeTypeAdaptersTest.java
new file mode 100644
index 0000000..f82d92e
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/TreeTypeAdaptersTest.java
@@ -0,0 +1,174 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.functional;
+
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import junit.framework.TestCase;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonDeserializationContext;
+import com.google.gson.JsonDeserializer;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonParseException;
+import com.google.gson.JsonPrimitive;
+import com.google.gson.JsonSerializationContext;
+import com.google.gson.JsonSerializer;
+import com.google.gson.reflect.TypeToken;
+
+/**
+ * Collection of functional tests for DOM tree based type adapters.
+ */
+public class TreeTypeAdaptersTest extends TestCase {
+  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 Student STUDENT1 = new Student(STUDENT1_ID, "first");
+  private static final Student STUDENT2 = new Student(STUDENT2_ID, "second");
+  private static final Type TYPE_COURSE_HISTORY =
+    new TypeToken<Course<HistoryCourse>>(){}.getType(); 
+  private static final Id<Course<HistoryCourse>> COURSE_ID =
+      new Id<>("10", TYPE_COURSE_HISTORY);
+
+  private Gson gson;
+  private Course<HistoryCourse> course;
+
+  @Override
+  protected void setUp() {
+    gson = new GsonBuilder()
+        .registerTypeAdapter(Id.class, new IdTreeTypeAdapter())
+        .create();
+    course = new Course<>(COURSE_ID, 4,
+        new Assignment<HistoryCourse>(null, null), Arrays.asList(STUDENT1, STUDENT2));
+  }
+
+  public void testSerializeId() {
+    String json = gson.toJson(course, TYPE_COURSE_HISTORY);
+    assertTrue(json.contains(String.valueOf(COURSE_ID.getValue())));
+    assertTrue(json.contains(String.valueOf(STUDENT1_ID.getValue())));
+    assertTrue(json.contains(String.valueOf(STUDENT2_ID.getValue())));
+  }
+
+  public void testDeserializeId() {
+    String json = "{courseId:1,students:[{id:1,name:'first'},{id:6,name:'second'}],"
+      + "numAssignments:4,assignment:{}}";
+    Course<HistoryCourse> target = gson.fromJson(json, TYPE_COURSE_HISTORY);
+    assertEquals("1", target.getStudents().get(0).id.getValue());
+    assertEquals("6", target.getStudents().get(1).id.getValue());
+    assertEquals("1", target.getId().getValue());
+  }
+
+  private static final class Id<R> {
+    final String value;
+    @SuppressWarnings("unused")
+    final Type typeOfId;
+
+    private Id(String value, Type typeOfId) {
+      this.value = value;
+      this.typeOfId = typeOfId;
+    }
+    public String getValue() {
+      return value;
+    }
+  }
+
+  private static final class IdTreeTypeAdapter implements JsonSerializer<Id<?>>,
+      JsonDeserializer<Id<?>> {
+
+    @SuppressWarnings("rawtypes")
+    @Override
+    public Id<?> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
+        throws JsonParseException {
+      if (!(typeOfT instanceof ParameterizedType)) {
+        throw new JsonParseException("Id of unknown type: " + typeOfT);
+      }
+      ParameterizedType parameterizedType = (ParameterizedType) typeOfT;
+      // Since Id takes only one TypeVariable, the actual type corresponding to the first
+      // TypeVariable is the Type we are looking for
+      Type typeOfId = parameterizedType.getActualTypeArguments()[0];
+      return new Id(json.getAsString(), typeOfId);
+    }
+
+    @Override
+    public JsonElement serialize(Id<?> src, Type typeOfSrc, JsonSerializationContext context) {
+      return new JsonPrimitive(src.getValue());
+    }
+  }
+
+  @SuppressWarnings("unused")
+  private static class Student {
+    Id<Student> id;
+    String name;
+
+    private Student() {
+      this(null, null);
+    }
+    public Student(Id<Student> id, String name) {
+      this.id = id;
+      this.name = name;
+    }
+  }
+
+  @SuppressWarnings("unused")
+  private static class Course<T> {
+    final List<Student> students;
+    private final Id<Course<T>> courseId;
+    private final int numAssignments;
+    private final Assignment<T> assignment;
+
+    private Course() {
+      this(null, 0, null, new ArrayList<Student>());
+    }
+
+    public Course(Id<Course<T>> courseId, int numAssignments,
+        Assignment<T> assignment, List<Student> players) {
+      this.courseId = courseId;
+      this.numAssignments = numAssignments;
+      this.assignment = assignment;
+      this.students = players;
+    }
+    public Id<Course<T>> getId() {
+      return courseId;
+    }
+    List<Student> getStudents() {
+      return students;
+    }
+  }
+
+  @SuppressWarnings("unused")
+  private static class Assignment<T> {
+    private final Id<Assignment<T>> id;
+    private final T data;
+
+    private Assignment() {
+      this(null, null);
+    }
+    public Assignment(Id<Assignment<T>> id, T data) {
+      this.id = id;
+      this.data = data;
+    }
+  }
+
+  @SuppressWarnings("unused")
+  private static class HistoryCourse {
+    int numClasses;
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/TypeAdapterPrecedenceTest.java b/gson/src/test/java/com/google/gson/functional/TypeAdapterPrecedenceTest.java
new file mode 100644
index 0000000..5f88153
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/TypeAdapterPrecedenceTest.java
@@ -0,0 +1,151 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.functional;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonDeserializationContext;
+import com.google.gson.JsonDeserializer;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonPrimitive;
+import com.google.gson.JsonSerializationContext;
+import com.google.gson.JsonSerializer;
+import com.google.gson.TypeAdapter;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
+import java.lang.reflect.Type;
+import junit.framework.TestCase;
+
+public final class TypeAdapterPrecedenceTest extends TestCase {
+  public void testNonstreamingFollowedByNonstreaming() {
+    Gson gson = new GsonBuilder()
+        .registerTypeAdapter(Foo.class, newSerializer("serializer 1"))
+        .registerTypeAdapter(Foo.class, newSerializer("serializer 2"))
+        .registerTypeAdapter(Foo.class, newDeserializer("deserializer 1"))
+        .registerTypeAdapter(Foo.class, newDeserializer("deserializer 2"))
+        .create();
+    assertEquals("\"foo via serializer 2\"", gson.toJson(new Foo("foo")));
+    assertEquals("foo via deserializer 2", gson.fromJson("foo", Foo.class).name);
+  }
+
+  public void testStreamingFollowedByStreaming() {
+    Gson gson = new GsonBuilder()
+        .registerTypeAdapter(Foo.class, newTypeAdapter("type adapter 1"))
+        .registerTypeAdapter(Foo.class, newTypeAdapter("type adapter 2"))
+        .create();
+    assertEquals("\"foo via type adapter 2\"", gson.toJson(new Foo("foo")));
+    assertEquals("foo via type adapter 2", gson.fromJson("foo", Foo.class).name);
+  }
+
+  public void testSerializeNonstreamingTypeAdapterFollowedByStreamingTypeAdapter() {
+    Gson gson = new GsonBuilder()
+        .registerTypeAdapter(Foo.class, newSerializer("serializer"))
+        .registerTypeAdapter(Foo.class, newDeserializer("deserializer"))
+        .registerTypeAdapter(Foo.class, newTypeAdapter("type adapter"))
+        .create();
+    assertEquals("\"foo via type adapter\"", gson.toJson(new Foo("foo")));
+    assertEquals("foo via type adapter", gson.fromJson("foo", Foo.class).name);
+  }
+
+  public void testStreamingFollowedByNonstreaming() {
+    Gson gson = new GsonBuilder()
+        .registerTypeAdapter(Foo.class, newTypeAdapter("type adapter"))
+        .registerTypeAdapter(Foo.class, newSerializer("serializer"))
+        .registerTypeAdapter(Foo.class, newDeserializer("deserializer"))
+        .create();
+    assertEquals("\"foo via serializer\"", gson.toJson(new Foo("foo")));
+    assertEquals("foo via deserializer", gson.fromJson("foo", Foo.class).name);
+  }
+
+  public void testStreamingHierarchicalFollowedByNonstreaming() {
+    Gson gson = new GsonBuilder()
+        .registerTypeHierarchyAdapter(Foo.class, newTypeAdapter("type adapter"))
+        .registerTypeAdapter(Foo.class, newSerializer("serializer"))
+        .registerTypeAdapter(Foo.class, newDeserializer("deserializer"))
+        .create();
+    assertEquals("\"foo via serializer\"", gson.toJson(new Foo("foo")));
+    assertEquals("foo via deserializer", gson.fromJson("foo", Foo.class).name);
+  }
+
+  public void testStreamingFollowedByNonstreamingHierarchical() {
+    Gson gson = new GsonBuilder()
+        .registerTypeAdapter(Foo.class, newTypeAdapter("type adapter"))
+        .registerTypeHierarchyAdapter(Foo.class, newSerializer("serializer"))
+        .registerTypeHierarchyAdapter(Foo.class, newDeserializer("deserializer"))
+        .create();
+    assertEquals("\"foo via type adapter\"", gson.toJson(new Foo("foo")));
+    assertEquals("foo via type adapter", gson.fromJson("foo", Foo.class).name);
+  }
+
+  public void testStreamingHierarchicalFollowedByNonstreamingHierarchical() {
+    Gson gson = new GsonBuilder()
+        .registerTypeHierarchyAdapter(Foo.class, newSerializer("serializer"))
+        .registerTypeHierarchyAdapter(Foo.class, newDeserializer("deserializer"))
+        .registerTypeHierarchyAdapter(Foo.class, newTypeAdapter("type adapter"))
+        .create();
+    assertEquals("\"foo via type adapter\"", gson.toJson(new Foo("foo")));
+    assertEquals("foo via type adapter", gson.fromJson("foo", Foo.class).name);
+  }
+
+  public void testNonstreamingHierarchicalFollowedByNonstreaming() {
+    Gson gson = new GsonBuilder()
+        .registerTypeHierarchyAdapter(Foo.class, newSerializer("hierarchical"))
+        .registerTypeHierarchyAdapter(Foo.class, newDeserializer("hierarchical"))
+        .registerTypeAdapter(Foo.class, newSerializer("non hierarchical"))
+        .registerTypeAdapter(Foo.class, newDeserializer("non hierarchical"))
+        .create();
+    assertEquals("\"foo via non hierarchical\"", gson.toJson(new Foo("foo")));
+    assertEquals("foo via non hierarchical", gson.fromJson("foo", Foo.class).name);
+  }
+
+  private static class Foo {
+    final String name;
+    private Foo(String name) {
+      this.name = name;
+    }
+  }
+
+  private JsonSerializer<Foo> newSerializer(final String name) {
+    return new JsonSerializer<Foo>() {
+      @Override
+      public JsonElement serialize(Foo src, Type typeOfSrc, JsonSerializationContext context) {
+        return new JsonPrimitive(src.name + " via " + name);
+      }
+    };
+  }
+
+  private JsonDeserializer<Foo> newDeserializer(final String name) {
+    return new JsonDeserializer<Foo>() {
+      @Override
+      public Foo deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
+        return new Foo(json.getAsString() + " via " + name);
+      }
+    };
+  }
+
+  private TypeAdapter<Foo> newTypeAdapter(final String name) {
+    return new TypeAdapter<Foo>() {
+      @Override public Foo read(JsonReader in) throws IOException {
+        return new Foo(in.nextString() + " via " + name);
+      }
+      @Override public void write(JsonWriter out, Foo value) throws IOException {
+        out.value(value.name + " via " + name);
+      }
+    };
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/TypeHierarchyAdapterTest.java b/gson/src/test/java/com/google/gson/functional/TypeHierarchyAdapterTest.java
new file mode 100644
index 0000000..25b9c34
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/TypeHierarchyAdapterTest.java
@@ -0,0 +1,221 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.functional;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonDeserializationContext;
+import com.google.gson.JsonDeserializer;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParseException;
+import com.google.gson.JsonPrimitive;
+import com.google.gson.JsonSerializationContext;
+import com.google.gson.JsonSerializer;
+import java.lang.reflect.Type;
+import junit.framework.TestCase;
+
+/**
+ * Test that the hierarchy adapter works when subtypes are used.
+ */
+public final class TypeHierarchyAdapterTest extends TestCase {
+
+  public void testTypeHierarchy() {
+    Manager andy = new Manager();
+    andy.userid = "andy";
+    andy.startDate = 2005;
+    andy.minions = new Employee[] {
+        new Employee("inder", 2007),
+        new Employee("joel", 2006),
+        new Employee("jesse", 2006),
+    };
+
+    CEO eric = new CEO();
+    eric.userid = "eric";
+    eric.startDate = 2001;
+    eric.assistant = new Employee("jerome", 2006);
+
+    eric.minions = new Employee[] {
+        new Employee("larry", 1998),
+        new Employee("sergey", 1998),
+        andy,
+    };
+
+    Gson gson = new GsonBuilder()
+        .registerTypeHierarchyAdapter(Employee.class, new EmployeeAdapter())
+        .setPrettyPrinting()
+        .create();
+
+    Company company = new Company();
+    company.ceo = eric;
+
+    String json = gson.toJson(company, Company.class);
+    assertEquals("{\n" +
+        "  \"ceo\": {\n" +
+        "    \"userid\": \"eric\",\n" +
+        "    \"startDate\": 2001,\n" +
+        "    \"minions\": [\n" +
+        "      {\n" +
+        "        \"userid\": \"larry\",\n" +
+        "        \"startDate\": 1998\n" +
+        "      },\n" +
+        "      {\n" +
+        "        \"userid\": \"sergey\",\n" +
+        "        \"startDate\": 1998\n" +
+        "      },\n" +
+        "      {\n" +
+        "        \"userid\": \"andy\",\n" +
+        "        \"startDate\": 2005,\n" +
+        "        \"minions\": [\n" +
+        "          {\n" +
+        "            \"userid\": \"inder\",\n" +
+        "            \"startDate\": 2007\n" +
+        "          },\n" +
+        "          {\n" +
+        "            \"userid\": \"joel\",\n" +
+        "            \"startDate\": 2006\n" +
+        "          },\n" +
+        "          {\n" +
+        "            \"userid\": \"jesse\",\n" +
+        "            \"startDate\": 2006\n" +
+        "          }\n" +
+        "        ]\n" +
+        "      }\n" +
+        "    ],\n" +
+        "    \"assistant\": {\n" +
+        "      \"userid\": \"jerome\",\n" +
+        "      \"startDate\": 2006\n" +
+        "    }\n" +
+        "  }\n" +
+        "}", json);
+
+    Company copied = gson.fromJson(json, Company.class);
+    assertEquals(json, gson.toJson(copied, Company.class));
+    assertEquals(copied.ceo.userid, company.ceo.userid);
+    assertEquals(copied.ceo.assistant.userid, company.ceo.assistant.userid);
+    assertEquals(copied.ceo.minions[0].userid, company.ceo.minions[0].userid);
+    assertEquals(copied.ceo.minions[1].userid, company.ceo.minions[1].userid);
+    assertEquals(copied.ceo.minions[2].userid, company.ceo.minions[2].userid);
+    assertEquals(((Manager) copied.ceo.minions[2]).minions[0].userid,
+        ((Manager) company.ceo.minions[2]).minions[0].userid);
+    assertEquals(((Manager) copied.ceo.minions[2]).minions[1].userid,
+        ((Manager) company.ceo.minions[2]).minions[1].userid);
+  }
+
+  public void testRegisterSuperTypeFirst() {
+    Gson gson = new GsonBuilder()
+        .registerTypeHierarchyAdapter(Employee.class, new EmployeeAdapter())
+        .registerTypeHierarchyAdapter(Manager.class, new ManagerAdapter())
+        .create();
+
+    Manager manager = new Manager();
+    manager.userid = "inder";
+
+    String json = gson.toJson(manager, Manager.class);
+    assertEquals("\"inder\"", json);
+    Manager copied = gson.fromJson(json, Manager.class);
+    assertEquals(manager.userid, copied.userid);
+  }
+
+  /** This behaviour changed in Gson 2.1; it used to throw. */
+  public void testRegisterSubTypeFirstAllowed() {
+    new GsonBuilder()
+        .registerTypeHierarchyAdapter(Manager.class, new ManagerAdapter())
+        .registerTypeHierarchyAdapter(Employee.class, new EmployeeAdapter())
+        .create();
+  }
+
+  static class ManagerAdapter implements JsonSerializer<Manager>, JsonDeserializer<Manager> {
+    @Override public Manager deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
+      Manager result = new Manager();
+      result.userid = json.getAsString();
+      return result;
+    }
+    @Override public JsonElement serialize(Manager src, Type typeOfSrc, JsonSerializationContext context) {
+      return new JsonPrimitive(src.userid);
+    }
+  }
+
+  static class EmployeeAdapter implements JsonSerializer<Employee>, JsonDeserializer<Employee> {
+    @Override public JsonElement serialize(Employee employee, Type typeOfSrc,
+        JsonSerializationContext context) {
+      JsonObject result = new JsonObject();
+      result.add("userid", context.serialize(employee.userid, String.class));
+      result.add("startDate", context.serialize(employee.startDate, long.class));
+      if (employee instanceof Manager) {
+        result.add("minions", context.serialize(((Manager) employee).minions, Employee[].class));
+        if (employee instanceof CEO) {
+          result.add("assistant", context.serialize(((CEO) employee).assistant, Employee.class));
+        }
+      }
+      return result;
+    }
+
+    @Override public Employee deserialize(JsonElement json, Type typeOfT,
+        JsonDeserializationContext context) throws JsonParseException {
+      JsonObject object = json.getAsJsonObject();
+      Employee result = null;
+
+      // if the employee has an assistant, she must be the CEO
+      JsonElement assistant = object.get("assistant");
+      if (assistant != null) {
+        result = new CEO();
+        ((CEO) result).assistant = context.deserialize(assistant, Employee.class);
+      }
+
+      // only managers have minions
+      JsonElement minons = object.get("minions");
+      if (minons != null) {
+        if (result == null) {
+          result = new Manager();
+        }
+        ((Manager) result).minions = context.deserialize(minons, Employee[].class);
+      }
+
+      if (result == null) {
+        result = new Employee();
+      }
+      result.userid = context.deserialize(object.get("userid"), String.class);
+      result.startDate = context.<Long>deserialize(object.get("startDate"), long.class);
+      return result;
+    }
+  }
+
+  static class Employee {
+    String userid;
+    long startDate;
+
+    Employee(String userid, long startDate) {
+      this.userid = userid;
+      this.startDate = startDate;
+    }
+
+    Employee() {}
+  }
+
+  static class Manager extends Employee {
+    Employee[] minions;
+  }
+
+  static class CEO extends Manager {
+    Employee assistant;
+  }
+
+  static class Company {
+    CEO ceo;
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/TypeVariableTest.java b/gson/src/test/java/com/google/gson/functional/TypeVariableTest.java
new file mode 100644
index 0000000..e5a4d8b
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/TypeVariableTest.java
@@ -0,0 +1,140 @@
+/*
+ * Copyright (C) 2010 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.functional;
+
+import com.google.gson.Gson;
+
+import com.google.gson.reflect.TypeToken;
+import java.lang.reflect.Type;
+import java.util.Arrays;
+import junit.framework.TestCase;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Functional test for Gson serialization and deserialization of
+ * classes with type variables.
+ *
+ * @author Joel Leitch
+ */
+public class TypeVariableTest extends TestCase {
+
+  public void testAdvancedTypeVariables() throws Exception {
+    Gson gson = new Gson();
+    Bar bar1 = new Bar("someString", 1, true);
+    ArrayList<Integer> arrayList = new ArrayList<>();
+    arrayList.add(1);
+    arrayList.add(2);
+    arrayList.add(3);
+    bar1.map.put("key1", arrayList);
+    bar1.map.put("key2", new ArrayList<Integer>());
+    String json = gson.toJson(bar1);
+
+    Bar bar2 = gson.fromJson(json, Bar.class);
+    assertEquals(bar1, bar2);
+  }
+
+  public void testTypeVariablesViaTypeParameter() throws Exception {
+    Gson gson = new Gson();
+    Foo<String, Integer> original = new Foo<>("e", 5, false);
+    original.map.put("f", Arrays.asList(6, 7));
+    Type type = new TypeToken<Foo<String, Integer>>() {}.getType();
+    String json = gson.toJson(original, type);
+    assertEquals("{\"someSField\":\"e\",\"someTField\":5,\"map\":{\"f\":[6,7]},\"redField\":false}",
+        json);
+    assertEquals(original, gson.<Foo<String, Integer>>fromJson(json, type));
+  }
+
+  public void testBasicTypeVariables() throws Exception {
+    Gson gson = new Gson();
+    Blue blue1 = new Blue(true);
+    String json = gson.toJson(blue1);
+
+    Blue blue2 = gson.fromJson(json, Blue.class);
+    assertEquals(blue1, blue2);
+  }
+
+  public static class Blue extends Red<Boolean> {
+    public Blue() {
+      super(false);
+    }
+
+    public Blue(boolean value) {
+      super(value);
+    }
+
+    // Technically, we should implement hashcode too
+    @Override
+    public boolean equals(Object o) {
+      if (!(o instanceof Blue)) {
+        return false;
+      }
+      Blue blue = (Blue) o;
+      return redField.equals(blue.redField);
+    }
+  }
+
+  public static class Red<S> {
+    protected S redField;
+
+    public Red() {}
+
+    public Red(S redField) {
+      this.redField = redField;
+    }
+  }
+
+  public static class Foo<S, T> extends Red<Boolean> {
+    private S someSField;
+    private T someTField;
+    public final Map<S, List<T>> map = new HashMap<>();
+
+    public Foo() {}
+
+    public Foo(S sValue, T tValue, Boolean redField) {
+      super(redField);
+      this.someSField = sValue;
+      this.someTField = tValue;
+    }
+
+    // Technically, we should implement hashcode too
+    @Override
+    @SuppressWarnings("unchecked")
+    public boolean equals(Object o) {
+      if (!(o instanceof Foo<?, ?>)) {
+        return false;
+      }
+      Foo<S, T> realFoo = (Foo<S, T>) o;
+      return redField.equals(realFoo.redField)
+        && someTField.equals(realFoo.someTField)
+        && someSField.equals(realFoo.someSField)
+        && map.equals(realFoo.map);
+    }
+  }
+
+  public static class Bar extends Foo<String, Integer> {
+    public Bar() {
+      this("", 0, false);
+    }
+
+    public Bar(String s, Integer i, boolean b) {
+      super(s, i, b);
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/UncategorizedTest.java b/gson/src/test/java/com/google/gson/functional/UncategorizedTest.java
new file mode 100644
index 0000000..0ac0380
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/UncategorizedTest.java
@@ -0,0 +1,134 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.functional;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonDeserializationContext;
+import com.google.gson.JsonDeserializer;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonParseException;
+import com.google.gson.common.TestTypes.BagOfPrimitives;
+import com.google.gson.common.TestTypes.ClassOverridingEquals;
+
+import com.google.gson.reflect.TypeToken;
+import java.util.Arrays;
+import java.util.List;
+import junit.framework.TestCase;
+
+import java.lang.reflect.Type;
+
+/**
+ * Functional tests that do not fall neatly into any of the existing classification.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public class UncategorizedTest extends TestCase {
+
+  private Gson gson = null;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    gson = new Gson();
+  }
+
+  public void testInvalidJsonDeserializationFails() throws Exception {
+    try {
+      gson.fromJson("adfasdf1112,,,\":", BagOfPrimitives.class);
+      fail("Bad JSON should throw a ParseException");
+    } catch (JsonParseException expected) { }
+
+    try {
+      gson.fromJson("{adfasdf1112,,,\":}", BagOfPrimitives.class);
+      fail("Bad JSON should throw a ParseException");
+    } catch (JsonParseException expected) { }
+  }
+
+  public void testObjectEqualButNotSameSerialization() throws Exception {
+    ClassOverridingEquals objA = new ClassOverridingEquals();
+    ClassOverridingEquals objB = new ClassOverridingEquals();
+    objB.ref = objA;
+    String json = gson.toJson(objB);
+    assertEquals(objB.getExpectedJson(), json);
+  }
+
+  public void testStaticFieldsAreNotSerialized() {
+    BagOfPrimitives target = new BagOfPrimitives();
+    assertFalse(gson.toJson(target).contains("DEFAULT_VALUE"));
+  }
+
+  public void testGsonInstanceReusableForSerializationAndDeserialization() {
+    BagOfPrimitives bag = new BagOfPrimitives();
+    String json = gson.toJson(bag);
+    BagOfPrimitives deserialized = gson.fromJson(json, BagOfPrimitives.class);
+    assertEquals(bag, deserialized);
+  }
+
+  /**
+   * This test ensures that a custom deserializer is able to return a derived class instance for a
+   * base class object. For a motivation for this test, see Issue 37 and
+   * http://groups.google.com/group/google-gson/browse_thread/thread/677d56e9976d7761
+   */
+  public void testReturningDerivedClassesDuringDeserialization() {
+    Gson gson = new GsonBuilder().registerTypeAdapter(Base.class, new BaseTypeAdapter()).create();
+    String json = "{\"opType\":\"OP1\"}";
+    Base base = gson.fromJson(json, Base.class);
+    assertTrue(base instanceof Derived1);
+    assertEquals(OperationType.OP1, base.opType);
+
+    json = "{\"opType\":\"OP2\"}";
+    base = gson.fromJson(json, Base.class);
+    assertTrue(base instanceof Derived2);
+    assertEquals(OperationType.OP2, base.opType);
+  }
+
+  /**
+   * Test that trailing whitespace is ignored.
+   * http://code.google.com/p/google-gson/issues/detail?id=302
+   */
+  public void testTrailingWhitespace() throws Exception {
+    List<Integer> integers = gson.fromJson("[1,2,3]  \n\n  ",
+        new TypeToken<List<Integer>>() {}.getType());
+    assertEquals(Arrays.asList(1, 2, 3), integers);
+  }
+
+  private enum OperationType { OP1, OP2 }
+  private static class Base {
+    OperationType opType;
+  }
+  private static class Derived1 extends Base {
+    Derived1() { opType = OperationType.OP1; }
+  }
+  private static class Derived2 extends Base {
+    Derived2() { opType = OperationType.OP2; }
+  }
+  private static class BaseTypeAdapter implements JsonDeserializer<Base> {
+    @Override public Base deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
+        throws JsonParseException {
+      String opTypeStr = json.getAsJsonObject().get("opType").getAsString();
+      OperationType opType = OperationType.valueOf(opTypeStr);
+      switch (opType) {
+      case OP1:
+        return new Derived1();
+      case OP2:
+        return new Derived2();
+      }
+      throw new JsonParseException("unknown type: " + json);
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/functional/VersioningTest.java b/gson/src/test/java/com/google/gson/functional/VersioningTest.java
new file mode 100644
index 0000000..2416fc0
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/functional/VersioningTest.java
@@ -0,0 +1,170 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.functional;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.annotations.Since;
+import com.google.gson.annotations.Until;
+import com.google.gson.common.TestTypes.BagOfPrimitives;
+
+import junit.framework.TestCase;
+
+/**
+ * Functional tests for versioning support in Gson.
+ *
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public class VersioningTest extends TestCase {
+  private static final int A = 0;
+  private static final int B = 1;
+  private static final int C = 2;
+  private static final int D = 3;
+
+  private GsonBuilder builder;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    builder = new GsonBuilder();
+  }
+
+  public void testVersionedUntilSerialization() {
+    Version1 target = new Version1();
+    Gson gson = builder.setVersion(1.29).create();
+    String json = gson.toJson(target);
+    assertTrue(json.contains("\"a\":" + A));
+
+    gson = builder.setVersion(1.3).create();
+    json = gson.toJson(target);
+    assertFalse(json.contains("\"a\":" + A));
+  }
+
+  public void testVersionedUntilDeserialization() {
+    Gson gson = builder.setVersion(1.3).create();
+    String json = "{\"a\":3,\"b\":4,\"c\":5}";
+    Version1 version1 = gson.fromJson(json, Version1.class);
+    assertEquals(A, version1.a);
+  }
+
+  public void testVersionedClassesSerialization() {
+    Gson gson = builder.setVersion(1.0).create();
+    String json1 = gson.toJson(new Version1());
+    String json2 = gson.toJson(new Version1_1());
+    assertEquals(json1, json2);
+  }
+
+  public void testVersionedClassesDeserialization() {
+    Gson gson = builder.setVersion(1.0).create();
+    String json = "{\"a\":3,\"b\":4,\"c\":5}";
+    Version1 version1 = gson.fromJson(json, Version1.class);
+    assertEquals(3, version1.a);
+    assertEquals(4, version1.b);
+    Version1_1 version1_1 = gson.fromJson(json, Version1_1.class);
+    assertEquals(3, version1_1.a);
+    assertEquals(4, version1_1.b);
+    assertEquals(C, version1_1.c);
+  }
+
+  public void testIgnoreLaterVersionClassSerialization() {
+    Gson gson = builder.setVersion(1.0).create();
+    assertEquals("null", gson.toJson(new Version1_2()));
+  }
+
+  public void testIgnoreLaterVersionClassDeserialization() {
+    Gson gson = builder.setVersion(1.0).create();
+    String json = "{\"a\":3,\"b\":4,\"c\":5,\"d\":6}";
+    Version1_2 version1_2 = gson.fromJson(json, Version1_2.class);
+    // Since the class is versioned to be after 1.0, we expect null
+    // This is the new behavior in Gson 2.0
+    assertNull(version1_2);
+  }
+
+  public void testVersionedGsonWithUnversionedClassesSerialization() {
+    Gson gson = builder.setVersion(1.0).create();
+    BagOfPrimitives target = new BagOfPrimitives(10, 20, false, "stringValue");
+    assertEquals(target.getExpectedJson(), gson.toJson(target));
+  }
+
+  public void testVersionedGsonWithUnversionedClassesDeserialization() {
+    Gson gson = builder.setVersion(1.0).create();
+    String json = "{\"longValue\":10,\"intValue\":20,\"booleanValue\":false}";
+
+    BagOfPrimitives expected = new BagOfPrimitives();
+    expected.longValue = 10;
+    expected.intValue = 20;
+    expected.booleanValue = false;
+    BagOfPrimitives actual = gson.fromJson(json, BagOfPrimitives.class);
+    assertEquals(expected, actual);
+  }
+
+  public void testVersionedGsonMixingSinceAndUntilSerialization() {
+    Gson gson = builder.setVersion(1.0).create();
+    SinceUntilMixing target = new SinceUntilMixing();
+    String json = gson.toJson(target);
+    assertFalse(json.contains("\"b\":" + B));
+
+    gson = builder.setVersion(1.2).create();
+    json = gson.toJson(target);
+    assertTrue(json.contains("\"b\":" + B));
+
+    gson = builder.setVersion(1.3).create();
+    json = gson.toJson(target);
+    assertFalse(json.contains("\"b\":" + B));
+  }
+
+  public void testVersionedGsonMixingSinceAndUntilDeserialization() {
+    String json = "{\"a\":5,\"b\":6}";
+    Gson gson = builder.setVersion(1.0).create();
+    SinceUntilMixing result = gson.fromJson(json, SinceUntilMixing.class);
+    assertEquals(5, result.a);
+    assertEquals(B, result.b);
+
+    gson = builder.setVersion(1.2).create();
+    result = gson.fromJson(json, SinceUntilMixing.class);
+    assertEquals(5, result.a);
+    assertEquals(6, result.b);
+
+    gson = builder.setVersion(1.3).create();
+    result = gson.fromJson(json, SinceUntilMixing.class);
+    assertEquals(5, result.a);
+    assertEquals(B, result.b);
+  }
+
+  private static class Version1 {
+    @Until(1.3) int a = A;
+    @Since(1.0) int b = B;
+  }
+
+  private static class Version1_1 extends Version1 {
+    @Since(1.1) int c = C;
+  }
+
+  @Since(1.2)
+  private static class Version1_2 extends Version1_1 {
+    @SuppressWarnings("unused")
+    int d = D;
+  }
+
+  private static class SinceUntilMixing {
+    int a = A;
+
+    @Since(1.1)
+    @Until(1.3)
+    int b = B;
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/internal/ConstructorConstructorTest.java b/gson/src/test/java/com/google/gson/internal/ConstructorConstructorTest.java
new file mode 100644
index 0000000..ba3c339
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/internal/ConstructorConstructorTest.java
@@ -0,0 +1,58 @@
+package com.google.gson.internal;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+import com.google.gson.InstanceCreator;
+import com.google.gson.ReflectionAccessFilter;
+import com.google.gson.reflect.TypeToken;
+import java.lang.reflect.Type;
+import java.util.Collections;
+import org.junit.Test;
+
+public class ConstructorConstructorTest {
+  private ConstructorConstructor constructorConstructor = new ConstructorConstructor(
+      Collections.<Type, InstanceCreator<?>>emptyMap(), true,
+      Collections.<ReflectionAccessFilter>emptyList()
+  );
+
+  private abstract static class AbstractClass {
+    @SuppressWarnings("unused")
+    public AbstractClass() { }
+  }
+  private interface Interface { }
+
+  /**
+   * Verify that ConstructorConstructor does not try to invoke no-arg constructor
+   * of abstract class.
+   */
+  @Test
+  public void testGet_AbstractClassNoArgConstructor() {
+    ObjectConstructor<AbstractClass> constructor = constructorConstructor.get(TypeToken.get(AbstractClass.class));
+    try {
+      constructor.construct();
+      fail("Expected exception");
+    } catch (RuntimeException exception) {
+      assertEquals(
+        "Abstract classes can't be instantiated! Register an InstanceCreator or a TypeAdapter for this "
+        + "type. Class name: com.google.gson.internal.ConstructorConstructorTest$AbstractClass",
+        exception.getMessage()
+      );
+    }
+  }
+
+  @Test
+  public void testGet_Interface() {
+    ObjectConstructor<Interface> constructor = constructorConstructor.get(TypeToken.get(Interface.class));
+    try {
+      constructor.construct();
+      fail("Expected exception");
+    } catch (RuntimeException exception) {
+      assertEquals(
+        "Interfaces can't be instantiated! Register an InstanceCreator or a TypeAdapter for "
+        + "this type. Interface name: com.google.gson.internal.ConstructorConstructorTest$Interface",
+        exception.getMessage()
+      );
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/internal/GsonBuildConfigTest.java b/gson/src/test/java/com/google/gson/internal/GsonBuildConfigTest.java
new file mode 100644
index 0000000..dc39bc0
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/internal/GsonBuildConfigTest.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2018 The Gson authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.internal;
+
+import static org.junit.Assert.assertFalse;
+
+import org.junit.Test;
+
+/**
+ * Unit tests for {@code GsonBuildConfig}
+ *
+ * @author Inderjeet Singh
+ */
+public class GsonBuildConfigTest {
+
+  @Test
+  public void testEnsureGsonBuildConfigGetsUpdatedToMavenVersion() {
+    assertFalse("${project.version}".equals(GsonBuildConfig.VERSION));
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/internal/GsonTypesTest.java b/gson/src/test/java/com/google/gson/internal/GsonTypesTest.java
new file mode 100644
index 0000000..c80700b
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/internal/GsonTypesTest.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2014 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.internal;
+
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.util.List;
+
+import junit.framework.TestCase;
+
+public final class GsonTypesTest extends TestCase {
+
+  public void testNewParameterizedTypeWithoutOwner() throws Exception {
+    // List<A>. List is a top-level class
+    Type type = $Gson$Types.newParameterizedTypeWithOwner(null, List.class, A.class);
+    assertEquals(A.class, getFirstTypeArgument(type));
+
+    // A<B>. A is a static inner class.
+    type = $Gson$Types.newParameterizedTypeWithOwner(null, A.class, B.class);
+    assertEquals(B.class, getFirstTypeArgument(type));
+
+    final class D {
+    }
+    try {
+      // D<A> is not allowed since D is not a static inner class
+      $Gson$Types.newParameterizedTypeWithOwner(null, D.class, A.class);
+      fail();
+    } catch (IllegalArgumentException expected) {}
+
+    // A<D> is allowed.
+    type = $Gson$Types.newParameterizedTypeWithOwner(null, A.class, D.class);
+    assertEquals(D.class, getFirstTypeArgument(type));
+  }
+
+  public void testGetFirstTypeArgument() throws Exception {
+    assertNull(getFirstTypeArgument(A.class));
+
+    Type type = $Gson$Types.newParameterizedTypeWithOwner(null, A.class, B.class, C.class);
+    assertEquals(B.class, getFirstTypeArgument(type));
+  }
+
+  private static final class A {
+  }
+  private static final class B {
+  }
+  private static final class C {
+  }
+
+  /**
+   * Given a parameterized type A&lt;B,C&gt;, returns B. If the specified type is not
+   * a generic type, returns null.
+   */
+  public static Type getFirstTypeArgument(Type type) throws Exception {
+    if (!(type instanceof ParameterizedType)) return null;
+    ParameterizedType ptype = (ParameterizedType) type;
+    Type[] actualTypeArguments = ptype.getActualTypeArguments();
+    if (actualTypeArguments.length == 0) return null;
+    return $Gson$Types.canonicalize(actualTypeArguments[0]);
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/internal/JavaVersionTest.java b/gson/src/test/java/com/google/gson/internal/JavaVersionTest.java
new file mode 100644
index 0000000..54b6286
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/internal/JavaVersionTest.java
@@ -0,0 +1,79 @@
+/*
+ * Copyright (C) 2017 The Gson authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.internal;
+
+import static org.junit.Assert.*;
+
+import org.junit.Test;
+
+/**
+ * Unit and functional tests for {@link JavaVersion}
+ *
+ * @author Inderjeet Singh
+ */
+public class JavaVersionTest {
+  // Borrowed some of test strings from https://github.com/prestodb/presto/blob/master/presto-main/src/test/java/com/facebook/presto/server/TestJavaVersion.java
+
+  @Test
+  public void testGetMajorJavaVersion() {
+    JavaVersion.getMajorJavaVersion();
+  }
+
+  @Test
+  public void testJava6() {
+    assertEquals(6, JavaVersion.getMajorJavaVersion("1.6.0")); // http://www.oracle.com/technetwork/java/javase/version-6-141920.html
+  }
+
+  @Test
+  public void testJava7() {
+    assertEquals(7, JavaVersion.getMajorJavaVersion("1.7.0")); // http://www.oracle.com/technetwork/java/javase/jdk7-naming-418744.html
+  }
+
+  @Test
+  public void testJava8() {
+    assertEquals(8, JavaVersion.getMajorJavaVersion("1.8"));
+    assertEquals(8, JavaVersion.getMajorJavaVersion("1.8.0"));
+    assertEquals(8, JavaVersion.getMajorJavaVersion("1.8.0_131"));
+    assertEquals(8, JavaVersion.getMajorJavaVersion("1.8.0_60-ea"));
+    assertEquals(8, JavaVersion.getMajorJavaVersion("1.8.0_111-internal"));
+
+    // openjdk8 per https://github.com/AdoptOpenJDK/openjdk-build/issues/93
+    assertEquals(8, JavaVersion.getMajorJavaVersion("1.8.0-internal"));
+    assertEquals(8, JavaVersion.getMajorJavaVersion("1.8.0_131-adoptopenjdk"));
+  }
+
+  @Test
+  public void testJava9() {
+    // Legacy style
+    assertEquals(9, JavaVersion.getMajorJavaVersion("9.0.4")); // Oracle JDK 9
+    assertEquals(9, JavaVersion.getMajorJavaVersion("9-Debian")); // Debian as reported in https://github.com/google/gson/issues/1310
+    // New style
+    assertEquals(9, JavaVersion.getMajorJavaVersion("9-ea+19"));
+    assertEquals(9, JavaVersion.getMajorJavaVersion("9+100"));
+    assertEquals(9, JavaVersion.getMajorJavaVersion("9.0.1+20"));
+    assertEquals(9, JavaVersion.getMajorJavaVersion("9.1.1+20"));
+  }
+
+  @Test
+  public void testJava10() {
+    assertEquals(10, JavaVersion.getMajorJavaVersion("10.0.1")); // Oracle JDK 10.0.1
+  }
+
+  @Test
+  public void testUnknownVersionFormat() {
+    assertEquals(6, JavaVersion.getMajorJavaVersion("Java9")); // unknown format
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/internal/LazilyParsedNumberTest.java b/gson/src/test/java/com/google/gson/internal/LazilyParsedNumberTest.java
new file mode 100644
index 0000000..75e77bb
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/internal/LazilyParsedNumberTest.java
@@ -0,0 +1,50 @@
+/*

+ * Copyright (C) 2015 Google Inc.

+ *

+ * Licensed under the Apache License, Version 2.0 (the "License");

+ * you may not use this file except in compliance with the License.

+ * You may obtain a copy of the License at

+ *

+ * http://www.apache.org/licenses/LICENSE-2.0

+ *

+ * Unless required by applicable law or agreed to in writing, software

+ * distributed under the License is distributed on an "AS IS" BASIS,

+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

+ * See the License for the specific language governing permissions and

+ * limitations under the License.

+ */

+package com.google.gson.internal;

+

+import java.io.ByteArrayInputStream;

+import java.io.ByteArrayOutputStream;

+import java.io.IOException;

+import java.io.ObjectInputStream;

+import java.io.ObjectOutputStream;

+import java.math.BigDecimal;

+

+import junit.framework.TestCase;

+

+public class LazilyParsedNumberTest extends TestCase {

+  public void testHashCode() {

+    LazilyParsedNumber n1 = new LazilyParsedNumber("1");

+    LazilyParsedNumber n1Another = new LazilyParsedNumber("1");

+    assertEquals(n1.hashCode(), n1Another.hashCode());

+  }

+

+  public void testEquals() {

+    LazilyParsedNumber n1 = new LazilyParsedNumber("1");

+    LazilyParsedNumber n1Another = new LazilyParsedNumber("1");

+    assertTrue(n1.equals(n1Another));

+  }

+

+  public void testJavaSerialization() throws IOException, ClassNotFoundException {

+    ByteArrayOutputStream out = new ByteArrayOutputStream();

+    ObjectOutputStream objOut = new ObjectOutputStream(out);

+    objOut.writeObject(new LazilyParsedNumber("123"));

+    objOut.close();

+

+    ObjectInputStream objIn = new ObjectInputStream(new ByteArrayInputStream(out.toByteArray()));

+    Number deserialized = (Number) objIn.readObject();

+    assertEquals(new BigDecimal("123"), deserialized);

+  }

+}

diff --git a/gson/src/test/java/com/google/gson/internal/LinkedTreeMapTest.java b/gson/src/test/java/com/google/gson/internal/LinkedTreeMapTest.java
new file mode 100644
index 0000000..ee1bb10
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/internal/LinkedTreeMapTest.java
@@ -0,0 +1,171 @@
+/*
+ * Copyright (C) 2012 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.internal;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Random;
+
+import junit.framework.TestCase;
+
+import com.google.gson.common.MoreAsserts;
+
+public final class LinkedTreeMapTest extends TestCase {
+
+  public void testIterationOrder() {
+    LinkedTreeMap<String, String> map = new LinkedTreeMap<>();
+    map.put("a", "android");
+    map.put("c", "cola");
+    map.put("b", "bbq");
+    assertIterationOrder(map.keySet(), "a", "c", "b");
+    assertIterationOrder(map.values(), "android", "cola", "bbq");
+  }
+
+  public void testRemoveRootDoesNotDoubleUnlink() {
+    LinkedTreeMap<String, String> map = new LinkedTreeMap<>();
+    map.put("a", "android");
+    map.put("c", "cola");
+    map.put("b", "bbq");
+    Iterator<Map.Entry<String,String>> it = map.entrySet().iterator();
+    it.next();
+    it.next();
+    it.next();
+    it.remove();
+    assertIterationOrder(map.keySet(), "a", "c");
+  }
+
+  public void testPutNullKeyFails() {
+    LinkedTreeMap<String, String> map = new LinkedTreeMap<>();
+    try {
+      map.put(null, "android");
+      fail();
+    } catch (NullPointerException expected) {
+    }
+  }
+
+  public void testPutNonComparableKeyFails() {
+    LinkedTreeMap<Object, String> map = new LinkedTreeMap<>();
+    try {
+      map.put(new Object(), "android");
+      fail();
+    } catch (ClassCastException expected) {}
+  }
+
+  public void testContainsNonComparableKeyReturnsFalse() {
+    LinkedTreeMap<String, String> map = new LinkedTreeMap<>();
+    map.put("a", "android");
+    assertFalse(map.containsKey(new Object()));
+  }
+
+  public void testContainsNullKeyIsAlwaysFalse() {
+    LinkedTreeMap<String, String> map = new LinkedTreeMap<>();
+    map.put("a", "android");
+    assertFalse(map.containsKey(null));
+  }
+
+  public void testPutOverrides() throws Exception {
+    LinkedTreeMap<String, String> map = new LinkedTreeMap<>();
+    assertNull(map.put("d", "donut"));
+    assertNull(map.put("e", "eclair"));
+    assertNull(map.put("f", "froyo"));
+    assertEquals(3, map.size());
+
+    assertEquals("donut", map.get("d"));
+    assertEquals("donut", map.put("d", "done"));
+    assertEquals(3, map.size());
+  }
+
+  public void testEmptyStringValues() {
+    LinkedTreeMap<String, String> map = new LinkedTreeMap<>();
+    map.put("a", "");
+    assertTrue(map.containsKey("a"));
+    assertEquals("", map.get("a"));
+  }
+
+  public void testLargeSetOfRandomKeys() throws Exception {
+    Random random = new Random(1367593214724L);
+    LinkedTreeMap<String, String> map = new LinkedTreeMap<>();
+    String[] keys = new String[1000];
+    for (int i = 0; i < keys.length; i++) {
+      keys[i] = Integer.toString(Math.abs(random.nextInt()), 36) + "-" + i;
+      map.put(keys[i], "" + i);
+    }
+
+    for (int i = 0; i < keys.length; i++) {
+      String key = keys[i];
+      assertTrue(map.containsKey(key));
+      assertEquals("" + i, map.get(key));
+    }
+  }
+
+  public void testClear() {
+    LinkedTreeMap<String, String> map = new LinkedTreeMap<>();
+    map.put("a", "android");
+    map.put("c", "cola");
+    map.put("b", "bbq");
+    map.clear();
+    assertIterationOrder(map.keySet());
+    assertEquals(0, map.size());
+  }
+
+  public void testEqualsAndHashCode() throws Exception {
+    LinkedTreeMap<String, Integer> map1 = new LinkedTreeMap<>();
+    map1.put("A", 1);
+    map1.put("B", 2);
+    map1.put("C", 3);
+    map1.put("D", 4);
+
+    LinkedTreeMap<String, Integer> map2 = new LinkedTreeMap<>();
+    map2.put("C", 3);
+    map2.put("B", 2);
+    map2.put("D", 4);
+    map2.put("A", 1);
+
+    MoreAsserts.assertEqualsAndHashCode(map1, map2);
+  }
+
+  public void testJavaSerialization() throws IOException, ClassNotFoundException {
+    ByteArrayOutputStream out = new ByteArrayOutputStream();
+    ObjectOutputStream objOut = new ObjectOutputStream(out);
+    Map<String, Integer> map = new LinkedTreeMap<>();
+    map.put("a", 1);
+    objOut.writeObject(map);
+    objOut.close();
+
+    ObjectInputStream objIn = new ObjectInputStream(new ByteArrayInputStream(out.toByteArray()));
+    @SuppressWarnings("unchecked")
+    Map<String, Integer> deserialized = (Map<String, Integer>) objIn.readObject();
+    assertEquals(Collections.singletonMap("a", 1), deserialized);
+  }
+
+  @SafeVarargs
+  private final <T> void assertIterationOrder(Iterable<T> actual, T... expected) {
+    ArrayList<T> actualList = new ArrayList<>();
+    for (T t : actual) {
+      actualList.add(t);
+    }
+    assertEquals(Arrays.asList(expected), actualList);
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/internal/UnsafeAllocatorInstantiationTest.java b/gson/src/test/java/com/google/gson/internal/UnsafeAllocatorInstantiationTest.java
new file mode 100644
index 0000000..e3ce147
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/internal/UnsafeAllocatorInstantiationTest.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2016 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.internal;
+
+import junit.framework.TestCase;
+
+/**
+ * Test unsafe allocator instantiation
+ * @author Ugljesa Jovanovic
+ */
+public final class UnsafeAllocatorInstantiationTest extends TestCase {
+
+  public interface Interface {
+  }
+
+  public static abstract class AbstractClass {
+  }
+
+  public static class ConcreteClass {
+  }
+
+  /**
+   * Ensure that an {@link AssertionError} is thrown when trying
+   * to instantiate an interface
+   */
+  public void testInterfaceInstantiation() throws Exception {
+    UnsafeAllocator unsafeAllocator = UnsafeAllocator.create();
+    try {
+      unsafeAllocator.newInstance(Interface.class);
+      fail();
+    } catch (AssertionError e) {
+      assertTrue(e.getMessage().startsWith("UnsafeAllocator is used for non-instantiable type"));
+    }
+  }
+
+  /**
+   * Ensure that an {@link AssertionError} is thrown when trying
+   * to instantiate an abstract class
+   */
+  public void testAbstractClassInstantiation() throws Exception {
+    UnsafeAllocator unsafeAllocator = UnsafeAllocator.create();
+    try {
+      unsafeAllocator.newInstance(AbstractClass.class);
+      fail();
+    } catch (AssertionError e) {
+      assertTrue(e.getMessage().startsWith("UnsafeAllocator is used for non-instantiable type"));
+    }
+  }
+
+  /**
+   * Ensure that no exception is thrown when trying to instantiate a concrete class
+   */
+  public void testConcreteClassInstantiation() throws Exception {
+    UnsafeAllocator unsafeAllocator = UnsafeAllocator.create();
+    ConcreteClass instance = unsafeAllocator.newInstance(ConcreteClass.class);
+    assertNotNull(instance);
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/internal/bind/DefaultDateTypeAdapterTest.java b/gson/src/test/java/com/google/gson/internal/bind/DefaultDateTypeAdapterTest.java
new file mode 100644
index 0000000..3d1ec7f
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/internal/bind/DefaultDateTypeAdapterTest.java
@@ -0,0 +1,217 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.internal.bind;
+
+import java.io.IOException;
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.Locale;
+import java.util.TimeZone;
+
+import com.google.gson.Gson;
+import com.google.gson.TypeAdapter;
+import com.google.gson.TypeAdapterFactory;
+import com.google.gson.internal.JavaVersion;
+import com.google.gson.internal.bind.DefaultDateTypeAdapter.DateType;
+import com.google.gson.reflect.TypeToken;
+
+import junit.framework.TestCase;
+
+/**
+ * A simple unit test for the {@link DefaultDateTypeAdapter} class.
+ *
+ * @author Joel Leitch
+ */
+public class DefaultDateTypeAdapterTest extends TestCase {
+
+  public void testFormattingInEnUs() {
+    assertFormattingAlwaysEmitsUsLocale(Locale.US);
+  }
+
+  public void testFormattingInFr() {
+    assertFormattingAlwaysEmitsUsLocale(Locale.FRANCE);
+  }
+
+  private void assertFormattingAlwaysEmitsUsLocale(Locale locale) {
+    TimeZone defaultTimeZone = TimeZone.getDefault();
+    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
+    Locale defaultLocale = Locale.getDefault();
+    Locale.setDefault(locale);
+    try {
+      String afterYearSep = JavaVersion.isJava9OrLater() ? ", " : " ";
+      String afterYearLongSep = JavaVersion.isJava9OrLater() ? " at " : " ";
+      String utcFull = JavaVersion.isJava9OrLater() ? "Coordinated Universal Time" : "UTC";
+      assertFormatted(String.format("Jan 1, 1970%s12:00:00 AM", afterYearSep),
+          DateType.DATE.createDefaultsAdapterFactory());
+      assertFormatted("1/1/70", DateType.DATE.createAdapterFactory(DateFormat.SHORT));
+      assertFormatted("Jan 1, 1970", DateType.DATE.createAdapterFactory(DateFormat.MEDIUM));
+      assertFormatted("January 1, 1970", DateType.DATE.createAdapterFactory(DateFormat.LONG));
+      assertFormatted(String.format("1/1/70%s12:00 AM", afterYearSep),
+          DateType.DATE.createAdapterFactory(DateFormat.SHORT, DateFormat.SHORT));
+      assertFormatted(String.format("Jan 1, 1970%s12:00:00 AM", afterYearSep),
+          DateType.DATE.createAdapterFactory(DateFormat.MEDIUM, DateFormat.MEDIUM));
+      assertFormatted(String.format("January 1, 1970%s12:00:00 AM UTC", afterYearLongSep),
+          DateType.DATE.createAdapterFactory(DateFormat.LONG, DateFormat.LONG));
+      assertFormatted(String.format("Thursday, January 1, 1970%s12:00:00 AM %s", afterYearLongSep, utcFull),
+          DateType.DATE.createAdapterFactory(DateFormat.FULL, DateFormat.FULL));
+    } finally {
+      TimeZone.setDefault(defaultTimeZone);
+      Locale.setDefault(defaultLocale);
+    }
+  }
+
+  public void testParsingDatesFormattedWithSystemLocale() throws Exception {
+    TimeZone defaultTimeZone = TimeZone.getDefault();
+    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
+    Locale defaultLocale = Locale.getDefault();
+    Locale.setDefault(Locale.FRANCE);
+    try {
+      String afterYearSep = JavaVersion.isJava9OrLater() ? " à " : " ";
+      assertParsed(String.format("1 janv. 1970%s00:00:00", afterYearSep),
+          DateType.DATE.createDefaultsAdapterFactory());
+      assertParsed("01/01/70", DateType.DATE.createAdapterFactory(DateFormat.SHORT));
+      assertParsed("1 janv. 1970", DateType.DATE.createAdapterFactory(DateFormat.MEDIUM));
+      assertParsed("1 janvier 1970", DateType.DATE.createAdapterFactory(DateFormat.LONG));
+      assertParsed("01/01/70 00:00",
+          DateType.DATE.createAdapterFactory(DateFormat.SHORT, DateFormat.SHORT));
+      assertParsed(String.format("1 janv. 1970%s00:00:00", afterYearSep),
+          DateType.DATE.createAdapterFactory(DateFormat.MEDIUM, DateFormat.MEDIUM));
+      assertParsed(String.format("1 janvier 1970%s00:00:00 UTC", afterYearSep),
+          DateType.DATE.createAdapterFactory(DateFormat.LONG, DateFormat.LONG));
+      assertParsed(JavaVersion.isJava9OrLater() ? (JavaVersion.getMajorJavaVersion() <11 ?
+                      "jeudi 1 janvier 1970 à 00:00:00 Coordinated Universal Time" :
+                      "jeudi 1 janvier 1970 à 00:00:00 Temps universel coordonné") :
+                      "jeudi 1 janvier 1970 00 h 00 UTC",
+          DateType.DATE.createAdapterFactory(DateFormat.FULL, DateFormat.FULL));
+    } finally {
+      TimeZone.setDefault(defaultTimeZone);
+      Locale.setDefault(defaultLocale);
+    }
+  }
+
+  public void testParsingDatesFormattedWithUsLocale() throws Exception {
+    TimeZone defaultTimeZone = TimeZone.getDefault();
+    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
+    Locale defaultLocale = Locale.getDefault();
+    Locale.setDefault(Locale.US);
+    try {
+      assertParsed("Jan 1, 1970 0:00:00 AM", DateType.DATE.createDefaultsAdapterFactory());
+      assertParsed("1/1/70", DateType.DATE.createAdapterFactory(DateFormat.SHORT));
+      assertParsed("Jan 1, 1970", DateType.DATE.createAdapterFactory(DateFormat.MEDIUM));
+      assertParsed("January 1, 1970", DateType.DATE.createAdapterFactory(DateFormat.LONG));
+      assertParsed("1/1/70 0:00 AM",
+          DateType.DATE.createAdapterFactory(DateFormat.SHORT, DateFormat.SHORT));
+      assertParsed("Jan 1, 1970 0:00:00 AM",
+          DateType.DATE.createAdapterFactory(DateFormat.MEDIUM, DateFormat.MEDIUM));
+      assertParsed("January 1, 1970 0:00:00 AM UTC",
+          DateType.DATE.createAdapterFactory(DateFormat.LONG, DateFormat.LONG));
+      assertParsed("Thursday, January 1, 1970 0:00:00 AM UTC",
+          DateType.DATE.createAdapterFactory(DateFormat.FULL, DateFormat.FULL));
+    } finally {
+      TimeZone.setDefault(defaultTimeZone);
+      Locale.setDefault(defaultLocale);
+    }
+  }
+
+  public void testFormatUsesDefaultTimezone() throws Exception {
+    TimeZone defaultTimeZone = TimeZone.getDefault();
+    TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles"));
+    Locale defaultLocale = Locale.getDefault();
+    Locale.setDefault(Locale.US);
+    try {
+      String afterYearSep = JavaVersion.isJava9OrLater() ? ", " : " ";
+      assertFormatted(String.format("Dec 31, 1969%s4:00:00 PM", afterYearSep),
+          DateType.DATE.createDefaultsAdapterFactory());
+      assertParsed("Dec 31, 1969 4:00:00 PM", DateType.DATE.createDefaultsAdapterFactory());
+    } finally {
+      TimeZone.setDefault(defaultTimeZone);
+      Locale.setDefault(defaultLocale);
+    }
+  }
+
+  public void testDateDeserializationISO8601() throws Exception {
+    TypeAdapterFactory adapterFactory = DateType.DATE.createDefaultsAdapterFactory();
+    assertParsed("1970-01-01T00:00:00.000Z", adapterFactory);
+    assertParsed("1970-01-01T00:00Z", adapterFactory);
+    assertParsed("1970-01-01T00:00:00+00:00", adapterFactory);
+    assertParsed("1970-01-01T01:00:00+01:00", adapterFactory);
+    assertParsed("1970-01-01T01:00:00+01", adapterFactory);
+  }
+
+  public void testDateSerialization() throws Exception {
+    int dateStyle = DateFormat.LONG;
+    TypeAdapter<Date> dateTypeAdapter = dateAdapter(DateType.DATE.createAdapterFactory(dateStyle));
+    DateFormat formatter = DateFormat.getDateInstance(dateStyle, Locale.US);
+    Date currentDate = new Date();
+
+    String dateString = dateTypeAdapter.toJson(currentDate);
+    assertEquals(toLiteral(formatter.format(currentDate)), dateString);
+  }
+
+  public void testDatePattern() throws Exception {
+    String pattern = "yyyy-MM-dd";
+    TypeAdapter<Date> dateTypeAdapter = dateAdapter(DateType.DATE.createAdapterFactory(pattern));
+    DateFormat formatter = new SimpleDateFormat(pattern);
+    Date currentDate = new Date();
+
+    String dateString = dateTypeAdapter.toJson(currentDate);
+    assertEquals(toLiteral(formatter.format(currentDate)), dateString);
+  }
+
+  public void testInvalidDatePattern() throws Exception {
+    try {
+      DateType.DATE.createAdapterFactory("I am a bad Date pattern....");
+      fail("Invalid date pattern should fail.");
+    } catch (IllegalArgumentException expected) { }
+  }
+
+  public void testNullValue() throws Exception {
+    TypeAdapter<Date> adapter = dateAdapter(DateType.DATE.createDefaultsAdapterFactory());
+    assertNull(adapter.fromJson("null"));
+    assertEquals("null", adapter.toJson(null));
+  }
+
+  public void testUnexpectedToken() throws Exception {
+    try {
+      TypeAdapter<Date> adapter = dateAdapter(DateType.DATE.createDefaultsAdapterFactory());
+      adapter.fromJson("{}");
+      fail("Unexpected token should fail.");
+    } catch (IllegalStateException expected) { }
+  }
+
+  private static TypeAdapter<Date> dateAdapter(TypeAdapterFactory adapterFactory) {
+    TypeAdapter<Date> adapter = adapterFactory.create(new Gson(), TypeToken.get(Date.class));
+    assertNotNull(adapter);
+    return adapter;
+  }
+
+  private static void assertFormatted(String formatted, TypeAdapterFactory adapterFactory) {
+    TypeAdapter<Date> adapter = dateAdapter(adapterFactory);
+    assertEquals(toLiteral(formatted), adapter.toJson(new Date(0)));
+  }
+
+  private static void assertParsed(String date, TypeAdapterFactory adapterFactory) throws IOException {
+    TypeAdapter<Date> adapter = dateAdapter(adapterFactory);
+    assertEquals(date, new Date(0), adapter.fromJson(toLiteral(date)));
+    assertEquals("ISO 8601", new Date(0), adapter.fromJson(toLiteral("1970-01-01T00:00:00Z")));
+  }
+
+  private static String toLiteral(String s) {
+    return '"' + s + '"';
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/internal/bind/JsonElementReaderTest.java b/gson/src/test/java/com/google/gson/internal/bind/JsonElementReaderTest.java
new file mode 100644
index 0000000..204fb3c
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/internal/bind/JsonElementReaderTest.java
@@ -0,0 +1,348 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.internal.bind;
+
+import com.google.gson.JsonElement;
+import com.google.gson.JsonParser;
+import com.google.gson.JsonPrimitive;
+import com.google.gson.stream.JsonToken;
+import java.io.IOException;
+import junit.framework.TestCase;
+
+@SuppressWarnings("resource")
+public final class JsonElementReaderTest extends TestCase {
+
+  public void testNumbers() throws IOException {
+    JsonElement element = JsonParser.parseString("[1, 2, 3]");
+    JsonTreeReader reader = new JsonTreeReader(element);
+    reader.beginArray();
+    assertEquals(1, reader.nextInt());
+    assertEquals(2L, reader.nextLong());
+    assertEquals(3.0, reader.nextDouble());
+    reader.endArray();
+  }
+
+  public void testLenientNansAndInfinities() throws IOException {
+    JsonElement element = JsonParser.parseString("[NaN, -Infinity, Infinity]");
+    JsonTreeReader reader = new JsonTreeReader(element);
+    reader.setLenient(true);
+    reader.beginArray();
+    assertTrue(Double.isNaN(reader.nextDouble()));
+    assertEquals(Double.NEGATIVE_INFINITY, reader.nextDouble());
+    assertEquals(Double.POSITIVE_INFINITY, reader.nextDouble());
+    reader.endArray();
+  }
+
+  public void testStrictNansAndInfinities() throws IOException {
+    JsonElement element = JsonParser.parseString("[NaN, -Infinity, Infinity]");
+    JsonTreeReader reader = new JsonTreeReader(element);
+    reader.setLenient(false);
+    reader.beginArray();
+    try {
+      reader.nextDouble();
+      fail();
+    } catch (NumberFormatException e) {
+    }
+    assertEquals("NaN", reader.nextString());
+    try {
+      reader.nextDouble();
+      fail();
+    } catch (NumberFormatException e) {
+    }
+    assertEquals("-Infinity", reader.nextString());
+    try {
+      reader.nextDouble();
+      fail();
+    } catch (NumberFormatException e) {
+    }
+    assertEquals("Infinity", reader.nextString());
+    reader.endArray();
+  }
+
+  public void testNumbersFromStrings() throws IOException {
+    JsonElement element = JsonParser.parseString("[\"1\", \"2\", \"3\"]");
+    JsonTreeReader reader = new JsonTreeReader(element);
+    reader.beginArray();
+    assertEquals(1, reader.nextInt());
+    assertEquals(2L, reader.nextLong());
+    assertEquals(3.0, reader.nextDouble());
+    reader.endArray();
+  }
+
+  public void testStringsFromNumbers() throws IOException {
+    JsonElement element = JsonParser.parseString("[1]");
+    JsonTreeReader reader = new JsonTreeReader(element);
+    reader.beginArray();
+    assertEquals("1", reader.nextString());
+    reader.endArray();
+  }
+
+  public void testBooleans() throws IOException {
+    JsonElement element = JsonParser.parseString("[true, false]");
+    JsonTreeReader reader = new JsonTreeReader(element);
+    reader.beginArray();
+    assertEquals(true, reader.nextBoolean());
+    assertEquals(false, reader.nextBoolean());
+    reader.endArray();
+  }
+
+  public void testNulls() throws IOException {
+    JsonElement element = JsonParser.parseString("[null,null]");
+    JsonTreeReader reader = new JsonTreeReader(element);
+    reader.beginArray();
+    reader.nextNull();
+    reader.nextNull();
+    reader.endArray();
+  }
+
+  public void testStrings() throws IOException {
+    JsonElement element = JsonParser.parseString("[\"A\",\"B\"]");
+    JsonTreeReader reader = new JsonTreeReader(element);
+    reader.beginArray();
+    assertEquals("A", reader.nextString());
+    assertEquals("B", reader.nextString());
+    reader.endArray();
+  }
+
+  public void testArray() throws IOException {
+    JsonElement element = JsonParser.parseString("[1, 2, 3]");
+    JsonTreeReader reader = new JsonTreeReader(element);
+    assertEquals(JsonToken.BEGIN_ARRAY, reader.peek());
+    reader.beginArray();
+    assertEquals(JsonToken.NUMBER, reader.peek());
+    assertEquals(1, reader.nextInt());
+    assertEquals(JsonToken.NUMBER, reader.peek());
+    assertEquals(2, reader.nextInt());
+    assertEquals(JsonToken.NUMBER, reader.peek());
+    assertEquals(3, reader.nextInt());
+    assertEquals(JsonToken.END_ARRAY, reader.peek());
+    reader.endArray();
+    assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+  }
+
+  public void testObject() throws IOException {
+    JsonElement element = JsonParser.parseString("{\"A\": 1, \"B\": 2}");
+    JsonTreeReader reader = new JsonTreeReader(element);
+    assertEquals(JsonToken.BEGIN_OBJECT, reader.peek());
+    reader.beginObject();
+    assertEquals(JsonToken.NAME, reader.peek());
+    assertEquals("A", reader.nextName());
+    assertEquals(JsonToken.NUMBER, reader.peek());
+    assertEquals(1, reader.nextInt());
+    assertEquals(JsonToken.NAME, reader.peek());
+    assertEquals("B", reader.nextName());
+    assertEquals(JsonToken.NUMBER, reader.peek());
+    assertEquals(2, reader.nextInt());
+    assertEquals(JsonToken.END_OBJECT, reader.peek());
+    reader.endObject();
+    assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+  }
+
+  public void testEmptyArray() throws IOException {
+    JsonElement element = JsonParser.parseString("[]");
+    JsonTreeReader reader = new JsonTreeReader(element);
+    reader.beginArray();
+    reader.endArray();
+  }
+
+  public void testNestedArrays() throws IOException {
+    JsonElement element = JsonParser.parseString("[[],[[]]]");
+    JsonTreeReader reader = new JsonTreeReader(element);
+    reader.beginArray();
+    reader.beginArray();
+    reader.endArray();
+    reader.beginArray();
+    reader.beginArray();
+    reader.endArray();
+    reader.endArray();
+    reader.endArray();
+  }
+
+  public void testNestedObjects() throws IOException {
+    JsonElement element = JsonParser.parseString("{\"A\":{},\"B\":{\"C\":{}}}");
+    JsonTreeReader reader = new JsonTreeReader(element);
+    reader.beginObject();
+    assertEquals("A", reader.nextName());
+    reader.beginObject();
+    reader.endObject();
+    assertEquals("B", reader.nextName());
+    reader.beginObject();
+    assertEquals("C", reader.nextName());
+    reader.beginObject();
+    reader.endObject();
+    reader.endObject();
+    reader.endObject();
+  }
+
+  public void testEmptyObject() throws IOException {
+    JsonElement element = JsonParser.parseString("{}");
+    JsonTreeReader reader = new JsonTreeReader(element);
+    reader.beginObject();
+    reader.endObject();
+  }
+
+  public void testSkipValue() throws IOException {
+    JsonElement element = JsonParser.parseString("[\"A\",{\"B\":[[]]},\"C\",[[]],\"D\",null]");
+    JsonTreeReader reader = new JsonTreeReader(element);
+    reader.beginArray();
+    assertEquals("A", reader.nextString());
+    reader.skipValue();
+    assertEquals("C", reader.nextString());
+    reader.skipValue();
+    assertEquals("D", reader.nextString());
+    reader.skipValue();
+    reader.endArray();
+  }
+
+  public void testWrongType() throws IOException {
+    JsonElement element = JsonParser.parseString("[[],\"A\"]");
+    JsonTreeReader reader = new JsonTreeReader(element);
+    reader.beginArray();
+    try {
+      reader.nextBoolean();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+    try {
+      reader.nextNull();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+    try {
+      reader.nextString();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+    try {
+      reader.nextInt();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+    try {
+      reader.nextLong();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+    try {
+      reader.nextDouble();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+    try {
+      reader.nextName();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+    try {
+      reader.beginObject();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+    try {
+      reader.endArray();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+    try {
+      reader.endObject();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+    reader.beginArray();
+    reader.endArray();
+
+    try {
+      reader.nextBoolean();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+    try {
+      reader.nextNull();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+    try {
+      reader.nextInt();
+      fail();
+    } catch (NumberFormatException expected) {
+    }
+    try {
+      reader.nextLong();
+      fail();
+    } catch (NumberFormatException expected) {
+    }
+    try {
+      reader.nextDouble();
+      fail();
+    } catch (NumberFormatException expected) {
+    }
+    try {
+      reader.nextName();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+    assertEquals("A", reader.nextString());
+    reader.endArray();
+  }
+
+  public void testNextJsonElement() throws IOException {
+    final JsonElement element = JsonParser.parseString("{\"A\": 1, \"B\" : {}, \"C\" : []}");
+    JsonTreeReader reader = new JsonTreeReader(element);
+    reader.beginObject();
+    try {
+      reader.nextJsonElement();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+    reader.nextName();
+    assertEquals(reader.nextJsonElement(), new JsonPrimitive(1));
+    reader.nextName();
+    reader.beginObject();
+    try {
+      reader.nextJsonElement();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+    reader.endObject();
+    reader.nextName();
+    reader.beginArray();
+    try {
+      reader.nextJsonElement();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+    reader.endArray();
+    reader.endObject();
+    try {
+      reader.nextJsonElement();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+  }
+
+  public void testEarlyClose() throws IOException {
+    JsonElement element = JsonParser.parseString("[1, 2, 3]");
+    JsonTreeReader reader = new JsonTreeReader(element);
+    reader.beginArray();
+    reader.close();
+    try {
+      reader.peek();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/internal/bind/JsonTreeReaderTest.java b/gson/src/test/java/com/google/gson/internal/bind/JsonTreeReaderTest.java
new file mode 100644
index 0000000..1166381
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/internal/bind/JsonTreeReaderTest.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2017 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.internal.bind;
+
+import com.google.gson.JsonArray;
+import com.google.gson.JsonNull;
+import com.google.gson.JsonObject;
+import com.google.gson.stream.JsonToken;
+import java.io.IOException;
+import junit.framework.TestCase;
+
+@SuppressWarnings("resource")
+public class JsonTreeReaderTest extends TestCase {
+  public void testSkipValue_emptyJsonObject() throws IOException {
+    JsonTreeReader in = new JsonTreeReader(new JsonObject());
+    in.skipValue();
+    assertEquals(JsonToken.END_DOCUMENT, in.peek());
+  }
+
+  public void testSkipValue_filledJsonObject() throws IOException {
+    JsonObject jsonObject = new JsonObject();
+    JsonArray jsonArray = new JsonArray();
+    jsonArray.add('c');
+    jsonArray.add("text");
+    jsonObject.add("a", jsonArray);
+    jsonObject.addProperty("b", true);
+    jsonObject.addProperty("i", 1);
+    jsonObject.add("n", JsonNull.INSTANCE);
+    JsonObject jsonObject2 = new JsonObject();
+    jsonObject2.addProperty("n", 2L);
+    jsonObject.add("o", jsonObject2);
+    jsonObject.addProperty("s", "text");
+    JsonTreeReader in = new JsonTreeReader(jsonObject);
+    in.skipValue();
+    assertEquals(JsonToken.END_DOCUMENT, in.peek());
+  }
+
+  public void testHasNext_endOfDocument() throws IOException {
+    JsonTreeReader reader = new JsonTreeReader(new JsonObject());
+    reader.beginObject();
+    reader.endObject();
+    assertFalse(reader.hasNext());
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/internal/bind/JsonTreeWriterTest.java b/gson/src/test/java/com/google/gson/internal/bind/JsonTreeWriterTest.java
new file mode 100644
index 0000000..3167be1
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/internal/bind/JsonTreeWriterTest.java
@@ -0,0 +1,236 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.internal.bind;
+
+import com.google.gson.JsonNull;
+import java.io.IOException;
+import junit.framework.TestCase;
+
+@SuppressWarnings("resource")
+public final class JsonTreeWriterTest extends TestCase {
+  public void testArray() throws IOException {
+    JsonTreeWriter writer = new JsonTreeWriter();
+    writer.beginArray();
+    writer.value(1);
+    writer.value(2);
+    writer.value(3);
+    writer.endArray();
+    assertEquals("[1,2,3]", writer.get().toString());
+  }
+
+  public void testNestedArray() throws IOException {
+    JsonTreeWriter writer = new JsonTreeWriter();
+    writer.beginArray();
+    writer.beginArray();
+    writer.endArray();
+    writer.beginArray();
+    writer.beginArray();
+    writer.endArray();
+    writer.endArray();
+    writer.endArray();
+    assertEquals("[[],[[]]]", writer.get().toString());
+  }
+
+  public void testObject() throws IOException {
+    JsonTreeWriter writer = new JsonTreeWriter();
+    writer.beginObject();
+    writer.name("A").value(1);
+    writer.name("B").value(2);
+    writer.endObject();
+    assertEquals("{\"A\":1,\"B\":2}", writer.get().toString());
+  }
+
+  public void testNestedObject() throws IOException {
+    JsonTreeWriter writer = new JsonTreeWriter();
+    writer.beginObject();
+    writer.name("A");
+    writer.beginObject();
+    writer.name("B");
+    writer.beginObject();
+    writer.endObject();
+    writer.endObject();
+    writer.name("C");
+    writer.beginObject();
+    writer.endObject();
+    writer.endObject();
+    assertEquals("{\"A\":{\"B\":{}},\"C\":{}}", writer.get().toString());
+  }
+
+  public void testWriteAfterClose() throws Exception {
+    JsonTreeWriter writer = new JsonTreeWriter();
+    writer.setLenient(true);
+    writer.beginArray();
+    writer.value("A");
+    writer.endArray();
+    writer.close();
+    try {
+      writer.beginArray();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+  }
+
+  public void testPrematureClose() throws Exception {
+    JsonTreeWriter writer = new JsonTreeWriter();
+    writer.setLenient(true);
+    writer.beginArray();
+    try {
+      writer.close();
+      fail();
+    } catch (IOException expected) {
+    }
+  }
+
+  public void testSerializeNullsFalse() throws IOException {
+    JsonTreeWriter writer = new JsonTreeWriter();
+    writer.setSerializeNulls(false);
+    writer.beginObject();
+    writer.name("A");
+    writer.nullValue();
+    writer.endObject();
+    assertEquals("{}", writer.get().toString());
+  }
+
+  public void testSerializeNullsTrue() throws IOException {
+    JsonTreeWriter writer = new JsonTreeWriter();
+    writer.setSerializeNulls(true);
+    writer.beginObject();
+    writer.name("A");
+    writer.nullValue();
+    writer.endObject();
+    assertEquals("{\"A\":null}", writer.get().toString());
+  }
+
+  public void testEmptyWriter() {
+    JsonTreeWriter writer = new JsonTreeWriter();
+    assertEquals(JsonNull.INSTANCE, writer.get());
+  }
+
+  public void testBeginArray() throws Exception {
+    JsonTreeWriter writer = new JsonTreeWriter();
+    assertEquals(writer, writer.beginArray());
+  }
+
+  public void testBeginObject() throws Exception {
+    JsonTreeWriter writer = new JsonTreeWriter();
+    assertEquals(writer, writer.beginObject());
+  }
+
+  public void testValueString() throws Exception {
+    JsonTreeWriter writer = new JsonTreeWriter();
+    String n = "as";
+    assertEquals(writer, writer.value(n));
+  }
+
+  public void testBoolValue() throws Exception {
+    JsonTreeWriter writer = new JsonTreeWriter();
+    boolean bool = true;
+    assertEquals(writer, writer.value(bool));
+  }
+
+  public void testBoolMaisValue() throws Exception {
+    JsonTreeWriter writer = new JsonTreeWriter();
+    Boolean bool = true;
+    assertEquals(writer, writer.value(bool));
+  }
+
+  public void testLenientNansAndInfinities() throws IOException {
+    JsonTreeWriter writer = new JsonTreeWriter();
+    writer.setLenient(true);
+    writer.beginArray();
+    writer.value(Float.NaN);
+    writer.value(Float.NEGATIVE_INFINITY);
+    writer.value(Float.POSITIVE_INFINITY);
+    writer.value(Double.NaN);
+    writer.value(Double.NEGATIVE_INFINITY);
+    writer.value(Double.POSITIVE_INFINITY);
+    writer.endArray();
+    assertEquals("[NaN,-Infinity,Infinity,NaN,-Infinity,Infinity]", writer.get().toString());
+  }
+
+  public void testStrictNansAndInfinities() throws IOException {
+    JsonTreeWriter writer = new JsonTreeWriter();
+    writer.setLenient(false);
+    writer.beginArray();
+    try {
+      writer.value(Float.NaN);
+      fail();
+    } catch (IllegalArgumentException expected) {
+    }
+    try {
+      writer.value(Float.NEGATIVE_INFINITY);
+      fail();
+    } catch (IllegalArgumentException expected) {
+    }
+    try {
+      writer.value(Float.POSITIVE_INFINITY);
+      fail();
+    } catch (IllegalArgumentException expected) {
+    }
+    try {
+      writer.value(Double.NaN);
+      fail();
+    } catch (IllegalArgumentException expected) {
+    }
+    try {
+      writer.value(Double.NEGATIVE_INFINITY);
+      fail();
+    } catch (IllegalArgumentException expected) {
+    }
+    try {
+      writer.value(Double.POSITIVE_INFINITY);
+      fail();
+    } catch (IllegalArgumentException expected) {
+    }
+  }
+
+  public void testStrictBoxedNansAndInfinities() throws IOException {
+    JsonTreeWriter writer = new JsonTreeWriter();
+    writer.setLenient(false);
+    writer.beginArray();
+    try {
+      writer.value(Float.valueOf(Float.NaN));
+      fail();
+    } catch (IllegalArgumentException expected) {
+    }
+    try {
+      writer.value(Float.valueOf(Float.NEGATIVE_INFINITY));
+      fail();
+    } catch (IllegalArgumentException expected) {
+    }
+    try {
+      writer.value(Float.valueOf(Float.POSITIVE_INFINITY));
+      fail();
+    } catch (IllegalArgumentException expected) {
+    }
+    try {
+      writer.value(Double.valueOf(Double.NaN));
+      fail();
+    } catch (IllegalArgumentException expected) {
+    }
+    try {
+      writer.value(Double.valueOf(Double.NEGATIVE_INFINITY));
+      fail();
+    } catch (IllegalArgumentException expected) {
+    }
+    try {
+      writer.value(Double.valueOf(Double.POSITIVE_INFINITY));
+      fail();
+    } catch (IllegalArgumentException expected) {
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/internal/bind/RecursiveTypesResolveTest.java b/gson/src/test/java/com/google/gson/internal/bind/RecursiveTypesResolveTest.java
new file mode 100644
index 0000000..ca068df
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/internal/bind/RecursiveTypesResolveTest.java
@@ -0,0 +1,102 @@
+/*
+ * Copyright (C) 2017 Gson Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.internal.bind;
+
+import com.google.gson.Gson;
+import com.google.gson.TypeAdapter;
+import com.google.gson.internal.$Gson$Types;
+import junit.framework.TestCase;
+
+/**
+ * Test fixes for infinite recursion on {@link $Gson$Types#resolve(java.lang.reflect.Type, Class,
+ * java.lang.reflect.Type)}, described at <a href="https://github.com/google/gson/issues/440">Issue #440</a>
+ * and similar issues.
+ * <p>
+ * These tests originally caused {@link StackOverflowError} because of infinite recursion on attempts to
+ * resolve generics on types, with an intermediate types like 'Foo2&lt;? extends ? super ? extends ... ? extends A&gt;'
+ */
+public class RecursiveTypesResolveTest extends TestCase {
+
+  @SuppressWarnings("unused")
+  private static class Foo1<A> {
+    public Foo2<? extends A> foo2;
+  }
+  @SuppressWarnings("unused")
+  private static class Foo2<B> {
+    public Foo1<? super B> foo1;
+  }
+
+  /**
+   * Test simplest case of recursion.
+   */
+
+  public void testRecursiveResolveSimple() {
+    @SuppressWarnings("rawtypes")
+    TypeAdapter<Foo1> adapter = new Gson().getAdapter(Foo1.class);
+    assertNotNull(adapter);
+  }
+
+  /**
+   * Tests belows check the behaviour of the methods changed for the fix.
+   */
+
+  public void testDoubleSupertype() {
+    assertEquals($Gson$Types.supertypeOf(Number.class),
+            $Gson$Types.supertypeOf($Gson$Types.supertypeOf(Number.class)));
+  }
+
+  public void testDoubleSubtype() {
+    assertEquals($Gson$Types.subtypeOf(Number.class),
+            $Gson$Types.subtypeOf($Gson$Types.subtypeOf(Number.class)));
+  }
+
+  public void testSuperSubtype() {
+    assertEquals($Gson$Types.subtypeOf(Object.class),
+            $Gson$Types.supertypeOf($Gson$Types.subtypeOf(Number.class)));
+  }
+
+  public void testSubSupertype() {
+    assertEquals($Gson$Types.subtypeOf(Object.class),
+            $Gson$Types.subtypeOf($Gson$Types.supertypeOf(Number.class)));
+  }
+
+  /**
+   * Tests for recursion while resolving type variables.
+   */
+
+  @SuppressWarnings("unused")
+  private static class TestType<X> {
+    TestType<? super X> superType;
+  }
+
+  @SuppressWarnings("unused")
+  private static class TestType2<X, Y> {
+    TestType2<? super Y, ? super X> superReversedType;
+  }
+
+  public void testRecursiveTypeVariablesResolve1() throws Exception {
+    @SuppressWarnings("rawtypes")
+    TypeAdapter<TestType> adapter = new Gson().getAdapter(TestType.class);
+    assertNotNull(adapter);
+  }
+
+  public void testRecursiveTypeVariablesResolve12() throws Exception {
+    @SuppressWarnings("rawtypes")
+    TypeAdapter<TestType2> adapter = new Gson().getAdapter(TestType2.class);
+    assertNotNull(adapter);
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/internal/bind/util/ISO8601UtilsTest.java b/gson/src/test/java/com/google/gson/internal/bind/util/ISO8601UtilsTest.java
new file mode 100644
index 0000000..68db238
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/internal/bind/util/ISO8601UtilsTest.java
@@ -0,0 +1,119 @@
+package com.google.gson.internal.bind.util;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.fail;
+
+import java.text.ParseException;
+import java.text.ParsePosition;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.Locale;
+import java.util.TimeZone;
+import org.junit.Test;
+import org.junit.function.ThrowingRunnable;
+
+public class ISO8601UtilsTest {
+
+    private static TimeZone utcTimeZone() {
+        return TimeZone.getTimeZone("UTC");
+    }
+
+    private static GregorianCalendar createUtcCalendar() {
+        TimeZone utc = utcTimeZone();
+        GregorianCalendar calendar = new GregorianCalendar(utc);
+        // Calendar was created with current time, must clear it
+        calendar.clear();
+        return calendar;
+    }
+
+    @Test
+    public void testDateFormatString() {
+        GregorianCalendar calendar = new GregorianCalendar(utcTimeZone(), Locale.US);
+        // Calendar was created with current time, must clear it
+        calendar.clear();
+        calendar.set(2018, Calendar.JUNE, 25);
+        Date date = calendar.getTime();
+        String dateStr = ISO8601Utils.format(date);
+        String expectedDate = "2018-06-25";
+        assertEquals(expectedDate, dateStr.substring(0, expectedDate.length()));
+    }
+
+    @Test
+    public void testDateFormatWithMilliseconds() {
+        long time = 1530209176870L;
+        Date date = new Date(time);
+        String dateStr = ISO8601Utils.format(date, true);
+        String expectedDate = "2018-06-28T18:06:16.870Z";
+        assertEquals(expectedDate, dateStr);
+    }
+
+    @Test
+    public void testDateFormatWithTimezone() {
+        long time = 1530209176870L;
+        Date date = new Date(time);
+        String dateStr = ISO8601Utils.format(date, true, TimeZone.getTimeZone("Brazil/East"));
+        String expectedDate = "2018-06-28T15:06:16.870-03:00";
+        assertEquals(expectedDate, dateStr);
+    }
+
+    @Test
+    public void testDateParseWithDefaultTimezone() throws ParseException {
+        String dateStr = "2018-06-25";
+        Date date = ISO8601Utils.parse(dateStr, new ParsePosition(0));
+        Date expectedDate = new GregorianCalendar(2018, Calendar.JUNE, 25).getTime();
+        assertEquals(expectedDate, date);
+    }
+
+    @Test
+    public void testDateParseInvalidDay() {
+      String dateStr = "2022-12-33";
+      try {
+        ISO8601Utils.parse(dateStr, new ParsePosition(0));
+        fail("Expected parsing to fail");
+      } catch (ParseException expected) {
+      }
+    }
+
+    @Test
+    public void testDateParseInvalidMonth() {
+      String dateStr = "2022-14-30";
+      try {
+        ISO8601Utils.parse(dateStr, new ParsePosition(0));
+        fail("Expected parsing to fail");
+      } catch (ParseException expected) {
+      }
+    }
+
+    @Test
+    public void testDateParseWithTimezone() throws ParseException {
+        String dateStr = "2018-06-25T00:00:00-03:00";
+        Date date = ISO8601Utils.parse(dateStr, new ParsePosition(0));
+        GregorianCalendar calendar = createUtcCalendar();
+        calendar.set(2018, Calendar.JUNE, 25, 3, 0);
+        Date expectedDate = calendar.getTime();
+        assertEquals(expectedDate, date);
+    }
+
+    @Test
+    public void testDateParseSpecialTimezone() throws ParseException {
+        String dateStr = "2018-06-25T00:02:00-02:58";
+        Date date = ISO8601Utils.parse(dateStr, new ParsePosition(0));
+        GregorianCalendar calendar = createUtcCalendar();
+        calendar.set(2018, Calendar.JUNE, 25, 3, 0);
+        Date expectedDate = calendar.getTime();
+        assertEquals(expectedDate, date);
+    }
+
+    @Test
+    public void testDateParseInvalidTime() throws ParseException {
+        final String dateStr = "2018-06-25T61:60:62-03:00";
+        assertThrows(ParseException.class, new ThrowingRunnable() {
+          @Override
+          public void run() throws Throwable {
+            ISO8601Utils.parse(dateStr, new ParsePosition(0));
+          }
+        });
+    }
+}
diff --git a/gson/src/test/java/com/google/gson/internal/sql/SqlTypesGsonTest.java b/gson/src/test/java/com/google/gson/internal/sql/SqlTypesGsonTest.java
new file mode 100644
index 0000000..03e2185
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/internal/sql/SqlTypesGsonTest.java
@@ -0,0 +1,124 @@
+package com.google.gson.internal.sql;
+
+import java.sql.Date;
+import java.sql.Time;
+import java.sql.Timestamp;
+import java.util.Locale;
+import java.util.TimeZone;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.functional.DefaultTypeAdaptersTest;
+import com.google.gson.internal.JavaVersion;
+
+import junit.framework.TestCase;
+
+public class SqlTypesGsonTest extends TestCase {
+  private Gson gson;
+  private TimeZone oldTimeZone;
+  private Locale oldLocale;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    this.oldTimeZone = TimeZone.getDefault();
+    TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles"));
+    this.oldLocale = Locale.getDefault();
+    Locale.setDefault(Locale.US);
+    gson = new Gson();
+  }
+
+  @Override
+  protected void tearDown() throws Exception {
+    super.tearDown();
+    TimeZone.setDefault(oldTimeZone);
+    Locale.setDefault(oldLocale);
+  }
+
+  public void testNullSerializationAndDeserialization() {
+    testNullSerializationAndDeserialization(Date.class);
+    testNullSerializationAndDeserialization(Time.class);
+    testNullSerializationAndDeserialization(Timestamp.class);
+  }
+
+  private void testNullSerializationAndDeserialization(Class<?> c) {
+    DefaultTypeAdaptersTest.testNullSerializationAndDeserialization(gson, c);
+  }
+
+  public void testDefaultSqlDateSerialization() {
+    java.sql.Date instant = new java.sql.Date(1259875082000L);
+    String json = gson.toJson(instant);
+    assertEquals("\"Dec 3, 2009\"", json);
+  }
+
+  public void testDefaultSqlDateDeserialization() {
+    String json = "'Dec 3, 2009'";
+    java.sql.Date extracted = gson.fromJson(json, java.sql.Date.class);
+    DefaultTypeAdaptersTest.assertEqualsDate(extracted, 2009, 11, 3);
+  }
+
+  // http://code.google.com/p/google-gson/issues/detail?id=230
+  public void testSqlDateSerialization() throws Exception {
+    TimeZone defaultTimeZone = TimeZone.getDefault();
+    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
+    Locale defaultLocale = Locale.getDefault();
+    Locale.setDefault(Locale.US);
+    try {
+      java.sql.Date sqlDate = new java.sql.Date(0L);
+      Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
+      String json = gson.toJson(sqlDate, Timestamp.class);
+      assertEquals("\"1970-01-01\"", json);
+      assertEquals(0, gson.fromJson("\"1970-01-01\"", java.sql.Date.class).getTime());
+    } finally {
+      TimeZone.setDefault(defaultTimeZone);
+      Locale.setDefault(defaultLocale);
+    }
+  }
+
+  public void testDefaultSqlTimeSerialization() {
+    Time now = new Time(1259875082000L);
+    String json = gson.toJson(now);
+    assertEquals("\"01:18:02 PM\"", json);
+  }
+
+  public void testDefaultSqlTimeDeserialization() {
+    String json = "'1:18:02 PM'";
+    Time extracted = gson.fromJson(json, Time.class);
+    DefaultTypeAdaptersTest.assertEqualsTime(extracted, 13, 18, 2);
+  }
+
+  public void testDefaultSqlTimestampSerialization() {
+    Timestamp now = new java.sql.Timestamp(1259875082000L);
+    String json = gson.toJson(now);
+    if (JavaVersion.isJava9OrLater()) {
+      assertEquals("\"Dec 3, 2009, 1:18:02 PM\"", json);
+    } else {
+      assertEquals("\"Dec 3, 2009 1:18:02 PM\"", json);
+    }
+  }
+
+  public void testDefaultSqlTimestampDeserialization() {
+    String json = "'Dec 3, 2009 1:18:02 PM'";
+    Timestamp extracted = gson.fromJson(json, Timestamp.class);
+    DefaultTypeAdaptersTest.assertEqualsDate(extracted, 2009, 11, 3);
+    DefaultTypeAdaptersTest.assertEqualsTime(extracted, 13, 18, 2);
+  }
+
+  // http://code.google.com/p/google-gson/issues/detail?id=230
+  public void testTimestampSerialization() throws Exception {
+    TimeZone defaultTimeZone = TimeZone.getDefault();
+    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
+    Locale defaultLocale = Locale.getDefault();
+    Locale.setDefault(Locale.US);
+    try {
+      Timestamp timestamp = new Timestamp(0L);
+      Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
+      String json = gson.toJson(timestamp, Timestamp.class);
+      assertEquals("\"1970-01-01\"", json);
+      assertEquals(0, gson.fromJson("\"1970-01-01\"", Timestamp.class).getTime());
+    } finally {
+      TimeZone.setDefault(defaultTimeZone);
+      Locale.setDefault(defaultLocale);
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/internal/sql/SqlTypesSupportTest.java b/gson/src/test/java/com/google/gson/internal/sql/SqlTypesSupportTest.java
new file mode 100644
index 0000000..ea496f4
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/internal/sql/SqlTypesSupportTest.java
@@ -0,0 +1,16 @@
+package com.google.gson.internal.sql;
+
+import junit.framework.TestCase;
+
+public class SqlTypesSupportTest extends TestCase {
+  public void testSupported() {
+    assertTrue(SqlTypesSupport.SUPPORTS_SQL_TYPES);
+
+    assertNotNull(SqlTypesSupport.DATE_DATE_TYPE);
+    assertNotNull(SqlTypesSupport.TIMESTAMP_DATE_TYPE);
+
+    assertNotNull(SqlTypesSupport.DATE_FACTORY);
+    assertNotNull(SqlTypesSupport.TIME_FACTORY);
+    assertNotNull(SqlTypesSupport.TIMESTAMP_FACTORY);
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/metrics/PerformanceTest.java b/gson/src/test/java/com/google/gson/metrics/PerformanceTest.java
new file mode 100644
index 0000000..61e69a3
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/metrics/PerformanceTest.java
@@ -0,0 +1,346 @@
+/*
+ * Copyright (C) 2008 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.metrics;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonParseException;
+import com.google.gson.annotations.Expose;
+import com.google.gson.reflect.TypeToken;
+
+import junit.framework.TestCase;
+
+import java.io.StringWriter;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Tests to measure performance for Gson. All tests in this file will be disabled in code. To run
+ * them remove disabled_ prefix from the tests and run them.
+ * 
+ * @author Inderjeet Singh
+ * @author Joel Leitch
+ */
+public class PerformanceTest extends TestCase {
+  private static final int COLLECTION_SIZE = 5000;
+
+  private static final int NUM_ITERATIONS = 100;
+
+  private Gson gson;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    gson = new Gson();
+  }
+  
+  public void testDummy() {
+    // This is here to prevent Junit for complaining when we disable all tests.
+  }
+
+  public void disabled_testStringDeserialization() {
+    StringBuilder sb = new StringBuilder(8096);
+    sb.append("Error Yippie");
+
+    while (true) {
+      try {
+        String stackTrace = sb.toString();
+        sb.append(stackTrace);
+        String json = "{\"message\":\"Error message.\"," + "\"stackTrace\":\"" + stackTrace + "\"}";
+        parseLongJson(json);
+        System.out.println("Gson could handle a string of size: " + stackTrace.length());
+      } catch (JsonParseException expected) {
+        break;
+      }
+    }
+  }
+  
+  private void parseLongJson(String json) throws JsonParseException {
+    ExceptionHolder target = gson.fromJson(json, ExceptionHolder.class);
+    assertTrue(target.message.contains("Error"));
+    assertTrue(target.stackTrace.contains("Yippie"));
+  }
+
+  private static class ExceptionHolder {
+    public final String message;
+    public final String stackTrace;
+    
+    // For use by Gson
+    @SuppressWarnings("unused")
+    private ExceptionHolder() {
+      this("", "");
+    }
+    public ExceptionHolder(String message, String stackTrace) {
+      this.message = message;
+      this.stackTrace = stackTrace;
+    }
+  }
+
+  @SuppressWarnings("unused")
+  private static class CollectionEntry {
+    final String name;
+    final String value;
+
+    // For use by Gson
+    private CollectionEntry() {
+      this(null, null);
+    }
+
+    CollectionEntry(String name, String value) {
+      this.name = name;
+      this.value = value;
+    }
+  }
+  
+  /**
+   * Created in response to http://code.google.com/p/google-gson/issues/detail?id=96
+   */
+  public void disabled_testLargeCollectionSerialization() {
+    int count = 1400000;
+    List<CollectionEntry> list = new ArrayList<>(count);
+    for (int i = 0; i < count; ++i) {
+      list.add(new CollectionEntry("name"+i,"value"+i));
+    }    
+    gson.toJson(list);
+  }
+  
+  /**
+   * Created in response to http://code.google.com/p/google-gson/issues/detail?id=96
+   */
+  public void disabled_testLargeCollectionDeserialization() {
+    StringBuilder sb = new StringBuilder();
+    int count = 87000;
+    boolean first = true;
+    sb.append('[');
+    for (int i = 0; i < count; ++i) {
+      if (first) {
+        first = false;
+      } else {
+        sb.append(',');
+      }
+      sb.append("{name:'name").append(i).append("',value:'value").append(i).append("'}");
+    }    
+    sb.append(']');
+    String json = sb.toString();
+    Type collectionType = new TypeToken<ArrayList<CollectionEntry>>(){}.getType();
+    List<CollectionEntry> list = gson.fromJson(json, collectionType);
+    assertEquals(count, list.size());
+  }
+
+  /**
+   * Created in response to http://code.google.com/p/google-gson/issues/detail?id=96
+   */
+  // Last I tested, Gson was able to serialize upto 14MB byte array
+  public void disabled_testByteArraySerialization() {
+    for (int size = 4145152; true; size += 1036288) {
+      byte[] ba = new byte[size];
+      for (int i = 0; i < size; ++i) {
+        ba[i] = 0x05;
+      }
+      gson.toJson(ba);
+      System.out.printf("Gson could serialize a byte array of size: %d\n", size);
+    }
+  }
+  
+  /**
+   * Created in response to http://code.google.com/p/google-gson/issues/detail?id=96
+   */
+  // Last I tested, Gson was able to deserialize a byte array of 11MB
+  public void disable_testByteArrayDeserialization() {
+    for (int numElements = 10639296; true; numElements += 16384) {
+      StringBuilder sb = new StringBuilder(numElements*2);
+      sb.append("[");
+      boolean first = true;
+      for (int i = 0; i < numElements; ++i) {
+        if (first) {
+          first = false;
+        } else {
+          sb.append(",");
+        }
+        sb.append("5");
+      }
+      sb.append("]");
+      String json = sb.toString();
+      byte[] ba = gson.fromJson(json, byte[].class);
+      System.out.printf("Gson could deserialize a byte array of size: %d\n", ba.length);
+    }
+  }
+
+// The tests to measure serialization and deserialization performance of Gson
+// Based on the discussion at
+// http://groups.google.com/group/google-gson/browse_thread/thread/7a50b17a390dfaeb
+// Test results: 10/19/2009 
+// Serialize classes avg time: 60 ms
+// Deserialized classes avg time: 70 ms
+// Serialize exposed classes avg time: 159 ms
+// Deserialized exposed classes avg time: 173 ms
+  
+  public void disabled_testSerializeClasses() {
+    ClassWithList c = new ClassWithList("str"); 
+    for (int i = 0; i < COLLECTION_SIZE; ++i) { 
+      c.list.add(new ClassWithField("element-" + i)); 
+    }
+    StringWriter w = new StringWriter(); 
+    long t1 = System.currentTimeMillis(); 
+    for (int i = 0; i < NUM_ITERATIONS; ++i) { 
+      gson.toJson(c, w); 
+    } 
+    long t2 = System.currentTimeMillis(); 
+    long avg = (t2 - t1) / NUM_ITERATIONS;
+    System.out.printf("Serialize classes avg time: %d ms\n", avg);
+  }
+
+  public void disabled_testDeserializeClasses() {
+    String json = buildJsonForClassWithList();
+    ClassWithList[] target = new ClassWithList[NUM_ITERATIONS];
+    long t1 = System.currentTimeMillis(); 
+    for (int i = 0; i < NUM_ITERATIONS; ++i) {
+      target[i] = gson.fromJson(json, ClassWithList.class);
+    }
+    long t2 = System.currentTimeMillis(); 
+    long avg = (t2 - t1) / NUM_ITERATIONS;
+    System.out.printf("Deserialize classes avg time: %d ms\n", avg);
+  }
+  
+  public void disable_testLargeObjectSerializationAndDeserialization() {
+    Map<String, Long> largeObject = new HashMap<>();
+    for (long l = 0; l < 100000; l++) {
+      largeObject.put("field" + l, l);
+    }
+    
+    long t1 = System.currentTimeMillis(); 
+    String json = gson.toJson(largeObject);
+    long t2 = System.currentTimeMillis();
+    System.out.printf("Large object serialized in: %d ms\n", (t2 - t1));
+
+    t1 = System.currentTimeMillis(); 
+    gson.fromJson(json, new TypeToken<Map<String, Long>>() {}.getType());
+    t2 = System.currentTimeMillis();
+    System.out.printf("Large object deserialized in: %d ms\n", (t2 - t1));
+    
+  }
+
+  public void disabled_testSerializeExposedClasses() {
+    ClassWithListOfObjects c1 = new ClassWithListOfObjects("str"); 
+    for (int i1 = 0; i1 < COLLECTION_SIZE; ++i1) { 
+      c1.list.add(new ClassWithExposedField("element-" + i1)); 
+    }
+    ClassWithListOfObjects c = c1; 
+    StringWriter w = new StringWriter(); 
+    long t1 = System.currentTimeMillis(); 
+    for (int i = 0; i < NUM_ITERATIONS; ++i) { 
+      gson.toJson(c, w); 
+    } 
+    long t2 = System.currentTimeMillis(); 
+    long avg = (t2 - t1) / NUM_ITERATIONS;
+    System.out.printf("Serialize exposed classes avg time: %d ms\n", avg);
+  }
+
+  public void disabled_testDeserializeExposedClasses() {
+    String json = buildJsonForClassWithList();
+    ClassWithListOfObjects[] target = new ClassWithListOfObjects[NUM_ITERATIONS];
+    long t1 = System.currentTimeMillis(); 
+    for (int i = 0; i < NUM_ITERATIONS; ++i) {
+      target[i] = gson.fromJson(json, ClassWithListOfObjects.class);
+    }
+    long t2 = System.currentTimeMillis(); 
+    long avg = (t2 - t1) / NUM_ITERATIONS;
+    System.out.printf("Deserialize exposed classes avg time: %d ms\n", avg);
+  }
+
+  public void disabled_testLargeGsonMapRoundTrip() throws Exception {
+    Map<Long, Long> original = new HashMap<>();
+    for (long i = 0; i < 1000000; i++) {
+      original.put(i, i + 1);
+    }
+
+    Gson gson = new Gson();
+    String json = gson.toJson(original);
+    Type longToLong = new TypeToken<Map<Long, Long>>(){}.getType();
+    gson.fromJson(json, longToLong);
+  }
+
+  private String buildJsonForClassWithList() {
+    StringBuilder sb = new StringBuilder("{");
+    sb.append("field:").append("'str',");
+    sb.append("list:[");
+    boolean first = true;
+    for (int i = 0; i < COLLECTION_SIZE; ++i) {
+      if (first) {
+        first = false;
+      } else {
+        sb.append(",");
+      }
+      sb.append("{field:'element-" + i + "'}");
+    }
+    sb.append("]");
+    sb.append("}");
+    String json = sb.toString();
+    return json;
+  }
+
+  @SuppressWarnings("unused")
+  private static final class ClassWithList { 
+    final String field; 
+    final List<ClassWithField> list = new ArrayList<>(COLLECTION_SIZE);
+    ClassWithList() {
+      this(null);
+    }
+    ClassWithList(String field) {
+      this.field = field;
+    }
+  } 
+
+  @SuppressWarnings("unused")
+  private static final class ClassWithField { 
+    final String field;
+    ClassWithField() {
+      this("");
+    }
+    public ClassWithField(String field) { 
+      this.field = field; 
+    } 
+  }
+
+  @SuppressWarnings("unused")
+  private static final class ClassWithListOfObjects { 
+    @Expose 
+    final String field; 
+    @Expose 
+    final List<ClassWithExposedField> list = new ArrayList<>(COLLECTION_SIZE);
+    ClassWithListOfObjects() {
+      this(null);
+    }
+    ClassWithListOfObjects(String field) {
+      this.field = field;
+    }
+  } 
+
+  @SuppressWarnings("unused")
+  private static final class ClassWithExposedField { 
+    @Expose 
+    final String field;
+    ClassWithExposedField() {
+      this("");
+    }
+    ClassWithExposedField(String field) { 
+      this.field = field; 
+    } 
+  }
+}
\ No newline at end of file
diff --git a/gson/src/test/java/com/google/gson/reflect/TypeTokenTest.java b/gson/src/test/java/com/google/gson/reflect/TypeTokenTest.java
new file mode 100644
index 0000000..1cdd736
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/reflect/TypeTokenTest.java
@@ -0,0 +1,160 @@
+/*
+ * Copyright (C) 2010 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.reflect;
+
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.RandomAccess;
+import java.util.Set;
+import junit.framework.TestCase;
+
+/**
+ * @author Jesse Wilson
+ */
+public final class TypeTokenTest extends TestCase {
+  // These fields are accessed using reflection by the tests below
+  List<Integer> listOfInteger = null;
+  List<Number> listOfNumber = null;
+  List<String> listOfString = null;
+  List<?> listOfUnknown = null;
+  List<Set<String>> listOfSetOfString = null;
+  List<Set<?>> listOfSetOfUnknown = null;
+
+  @SuppressWarnings({"deprecation"})
+  public void testIsAssignableFromRawTypes() {
+    assertTrue(TypeToken.get(Object.class).isAssignableFrom(String.class));
+    assertFalse(TypeToken.get(String.class).isAssignableFrom(Object.class));
+    assertTrue(TypeToken.get(RandomAccess.class).isAssignableFrom(ArrayList.class));
+    assertFalse(TypeToken.get(ArrayList.class).isAssignableFrom(RandomAccess.class));
+  }
+
+  @SuppressWarnings({"deprecation"})
+  public void testIsAssignableFromWithTypeParameters() throws Exception {
+    Type a = getClass().getDeclaredField("listOfInteger").getGenericType();
+    Type b = getClass().getDeclaredField("listOfNumber").getGenericType();
+    assertTrue(TypeToken.get(a).isAssignableFrom(a));
+    assertTrue(TypeToken.get(b).isAssignableFrom(b));
+
+    // listOfInteger = listOfNumber; // doesn't compile; must be false
+    assertFalse(TypeToken.get(a).isAssignableFrom(b));
+    // listOfNumber = listOfInteger; // doesn't compile; must be false
+    assertFalse(TypeToken.get(b).isAssignableFrom(a));
+  }
+
+  @SuppressWarnings({"deprecation"})
+  public void testIsAssignableFromWithBasicWildcards() throws Exception {
+    Type a = getClass().getDeclaredField("listOfString").getGenericType();
+    Type b = getClass().getDeclaredField("listOfUnknown").getGenericType();
+    assertTrue(TypeToken.get(a).isAssignableFrom(a));
+    assertTrue(TypeToken.get(b).isAssignableFrom(b));
+
+    // listOfString = listOfUnknown  // doesn't compile; must be false
+    assertFalse(TypeToken.get(a).isAssignableFrom(b));
+    listOfUnknown = listOfString; // compiles; must be true
+    // The following assertion is too difficult to support reliably, so disabling
+    // assertTrue(TypeToken.get(b).isAssignableFrom(a));
+  }
+
+  @SuppressWarnings({"deprecation"})
+  public void testIsAssignableFromWithNestedWildcards() throws Exception {
+    Type a = getClass().getDeclaredField("listOfSetOfString").getGenericType();
+    Type b = getClass().getDeclaredField("listOfSetOfUnknown").getGenericType();
+    assertTrue(TypeToken.get(a).isAssignableFrom(a));
+    assertTrue(TypeToken.get(b).isAssignableFrom(b));
+
+    // listOfSetOfString = listOfSetOfUnknown; // doesn't compile; must be false
+    assertFalse(TypeToken.get(a).isAssignableFrom(b));
+    // listOfSetOfUnknown = listOfSetOfString; // doesn't compile; must be false
+    assertFalse(TypeToken.get(b).isAssignableFrom(a));
+  }
+
+  public void testArrayFactory() {
+    TypeToken<?> expectedStringArray = new TypeToken<String[]>() {};
+    assertEquals(expectedStringArray, TypeToken.getArray(String.class));
+
+    TypeToken<?> expectedListOfStringArray = new TypeToken<List<String>[]>() {};
+    Type listOfString = new TypeToken<List<String>>() {}.getType();
+    assertEquals(expectedListOfStringArray, TypeToken.getArray(listOfString));
+  }
+
+  public void testParameterizedFactory() {
+    TypeToken<?> expectedListOfString = new TypeToken<List<String>>() {};
+    assertEquals(expectedListOfString, TypeToken.getParameterized(List.class, String.class));
+
+    TypeToken<?> expectedMapOfStringToString = new TypeToken<Map<String, String>>() {};
+    assertEquals(expectedMapOfStringToString, TypeToken.getParameterized(Map.class, String.class, String.class));
+
+    TypeToken<?> expectedListOfListOfListOfString = new TypeToken<List<List<List<String>>>>() {};
+    Type listOfString = TypeToken.getParameterized(List.class, String.class).getType();
+    Type listOfListOfString = TypeToken.getParameterized(List.class, listOfString).getType();
+    assertEquals(expectedListOfListOfListOfString, TypeToken.getParameterized(List.class, listOfListOfString));
+  }
+
+  private static class CustomTypeToken extends TypeToken<String> {
+  }
+
+  public void testTypeTokenNonAnonymousSubclass() {
+    TypeToken<?> typeToken = new CustomTypeToken();
+    assertEquals(String.class, typeToken.getRawType());
+    assertEquals(String.class, typeToken.getType());
+  }
+
+  /**
+   * User must only create direct subclasses of TypeToken, but not subclasses
+   * of subclasses (...) of TypeToken.
+   */
+  public void testTypeTokenSubSubClass() {
+    class SubTypeToken<T> extends TypeToken<String> {}
+    class SubSubTypeToken1<T> extends SubTypeToken<T> {}
+    class SubSubTypeToken2 extends SubTypeToken<Integer> {}
+
+    try {
+      new SubTypeToken<Integer>() {};
+      fail();
+    } catch (IllegalStateException expected) {
+      assertEquals("Must only create direct subclasses of TypeToken", expected.getMessage());
+    }
+
+    try {
+      new SubSubTypeToken1<Integer>();
+      fail();
+    } catch (IllegalStateException expected) {
+      assertEquals("Must only create direct subclasses of TypeToken", expected.getMessage());
+    }
+
+    try {
+      new SubSubTypeToken2();
+      fail();
+    } catch (IllegalStateException expected) {
+      assertEquals("Must only create direct subclasses of TypeToken", expected.getMessage());
+    }
+  }
+
+  @SuppressWarnings("rawtypes")
+  public void testTypeTokenRaw() {
+    try {
+      new TypeToken() {};
+      fail();
+    } catch (IllegalStateException expected) {
+      assertEquals("TypeToken must be created with a type argument: new TypeToken<...>() {}; "
+          + "When using code shrinkers (ProGuard, R8, ...) make sure that generic signatures are preserved.",
+          expected.getMessage());
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/regression/JsonAdapterNullSafeTest.java b/gson/src/test/java/com/google/gson/regression/JsonAdapterNullSafeTest.java
new file mode 100644
index 0000000..e327895
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/regression/JsonAdapterNullSafeTest.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2016 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.regression;
+
+import com.google.gson.Gson;
+import com.google.gson.TypeAdapter;
+import com.google.gson.TypeAdapterFactory;
+import com.google.gson.annotations.JsonAdapter;
+import com.google.gson.reflect.TypeToken;
+
+import junit.framework.TestCase;
+
+public class JsonAdapterNullSafeTest extends TestCase {
+  private final Gson gson = new Gson();
+
+  public void testNullSafeBugSerialize() throws Exception {
+    Device device = new Device("ec57803e");
+    gson.toJson(device);
+  }
+
+  public void testNullSafeBugDeserialize() throws Exception {
+    Device device = gson.fromJson("{'id':'ec57803e2'}", Device.class);
+    assertEquals("ec57803e2", device.id);
+  }
+
+  @JsonAdapter(Device.JsonAdapterFactory.class)
+  private static final class Device {
+    String id;
+    Device(String id) {
+      this.id = id;
+    }
+
+    static final class JsonAdapterFactory implements TypeAdapterFactory {
+      // The recursiveCall in {@link Device.JsonAdapterFactory} is the source of this bug
+      // because we use it to return a null type adapter on a recursive call.
+      private static final ThreadLocal<Boolean> recursiveCall = new ThreadLocal<>();
+
+      @Override public <T> TypeAdapter<T> create(final Gson gson, TypeToken<T> type) {
+        if (type.getRawType() != Device.class || recursiveCall.get() != null) {
+          recursiveCall.set(null); // clear for subsequent use
+          return null;
+        }
+        recursiveCall.set(Boolean.TRUE);
+        return gson.getDelegateAdapter(this, type);
+      }
+    }
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/regression/OSGiTest.java b/gson/src/test/java/com/google/gson/regression/OSGiTest.java
new file mode 100644
index 0000000..c41b12f
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/regression/OSGiTest.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2016 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.regression;
+
+import java.io.InputStream;
+import java.io.IOException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.jar.Manifest;
+
+import junit.framework.TestCase;
+
+public class OSGiTest extends TestCase {
+    public void testComGoogleGsonAnnotationsPackage() throws Exception {
+        Manifest mf = findManifest("com.google.gson");
+        String importPkg = mf.getMainAttributes().getValue("Import-Package");
+        assertNotNull("Import-Package statement is there", importPkg);
+        assertSubstring("There should be com.google.gson.annotations dependency", importPkg, "com.google.gson.annotations");
+    }
+
+    public void testSunMiscImportPackage() throws Exception {
+        Manifest mf = findManifest("com.google.gson");
+        String importPkg = mf.getMainAttributes().getValue("Import-Package");
+        assertNotNull("Import-Package statement is there", importPkg);
+        for (String dep : importPkg.split(",")) {
+            if (dep.contains("sun.misc")) {
+                assertSubstring("sun.misc import is optional", dep, "resolution:=optional");
+                return;
+            }
+        }
+        fail("There should be sun.misc dependency, but was: " + importPkg);
+    }
+
+    private Manifest findManifest(String pkg) throws IOException {
+        List<URL> urls = new ArrayList<>();
+        for (URL u : Collections.list(getClass().getClassLoader().getResources("META-INF/MANIFEST.MF"))) {
+            InputStream is = u.openStream();
+            Manifest mf = new Manifest(is);
+            is.close();
+            if (pkg.equals(mf.getMainAttributes().getValue("Bundle-SymbolicName"))) {
+                return mf;
+            }
+            urls.add(u);
+        }
+        fail("Cannot find " + pkg + " OSGi bundle manifest among: " + urls);
+        return null;
+    }
+
+    private static void assertSubstring(String msg, String wholeText, String subString) {
+        if (wholeText.contains(subString)) {
+            return;
+        }
+        fail(msg + ". Expecting " + subString + " but was: " + wholeText);
+    }
+}
diff --git a/gson/src/test/java/com/google/gson/stream/JsonReaderPathTest.java b/gson/src/test/java/com/google/gson/stream/JsonReaderPathTest.java
new file mode 100644
index 0000000..ab802be
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/stream/JsonReaderPathTest.java
@@ -0,0 +1,325 @@
+/*
+ * Copyright (C) 2014 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.stream;
+
+import com.google.gson.JsonElement;
+import com.google.gson.internal.Streams;
+import com.google.gson.internal.bind.JsonTreeReader;
+import java.io.IOException;
+import java.io.StringReader;
+import java.util.Arrays;
+import java.util.List;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assume.assumeTrue;
+
+@SuppressWarnings("resource")
+@RunWith(Parameterized.class)
+public class JsonReaderPathTest {
+  @Parameterized.Parameters(name = "{0}")
+  public static List<Object[]> parameters() {
+    return Arrays.asList(
+        new Object[] { Factory.STRING_READER },
+        new Object[] { Factory.OBJECT_READER }
+    );
+  }
+
+  @Parameterized.Parameter
+  public Factory factory;
+
+  @Test public void path() throws IOException {
+    JsonReader reader = factory.create("{\"a\":[2,true,false,null,\"b\",{\"c\":\"d\"},[3]]}");
+    assertEquals("$", reader.getPreviousPath());
+    assertEquals("$", reader.getPath());
+    reader.beginObject();
+    assertEquals("$.", reader.getPreviousPath());
+    assertEquals("$.", reader.getPath());
+    reader.nextName();
+    assertEquals("$.a", reader.getPreviousPath());
+    assertEquals("$.a", reader.getPath());
+    reader.beginArray();
+    assertEquals("$.a[0]", reader.getPreviousPath());
+    assertEquals("$.a[0]", reader.getPath());
+    reader.nextInt();
+    assertEquals("$.a[0]", reader.getPreviousPath());
+    assertEquals("$.a[1]", reader.getPath());
+    reader.nextBoolean();
+    assertEquals("$.a[1]", reader.getPreviousPath());
+    assertEquals("$.a[2]", reader.getPath());
+    reader.nextBoolean();
+    assertEquals("$.a[2]", reader.getPreviousPath());
+    assertEquals("$.a[3]", reader.getPath());
+    reader.nextNull();
+    assertEquals("$.a[3]", reader.getPreviousPath());
+    assertEquals("$.a[4]", reader.getPath());
+    reader.nextString();
+    assertEquals("$.a[4]", reader.getPreviousPath());
+    assertEquals("$.a[5]", reader.getPath());
+    reader.beginObject();
+    assertEquals("$.a[5].", reader.getPreviousPath());
+    assertEquals("$.a[5].", reader.getPath());
+    reader.nextName();
+    assertEquals("$.a[5].c", reader.getPreviousPath());
+    assertEquals("$.a[5].c", reader.getPath());
+    reader.nextString();
+    assertEquals("$.a[5].c", reader.getPreviousPath());
+    assertEquals("$.a[5].c", reader.getPath());
+    reader.endObject();
+    assertEquals("$.a[5]", reader.getPreviousPath());
+    assertEquals("$.a[6]", reader.getPath());
+    reader.beginArray();
+    assertEquals("$.a[6][0]", reader.getPreviousPath());
+    assertEquals("$.a[6][0]", reader.getPath());
+    reader.nextInt();
+    assertEquals("$.a[6][0]", reader.getPreviousPath());
+    assertEquals("$.a[6][1]", reader.getPath());
+    reader.endArray();
+    assertEquals("$.a[6]", reader.getPreviousPath());
+    assertEquals("$.a[7]", reader.getPath());
+    reader.endArray();
+    assertEquals("$.a", reader.getPreviousPath());
+    assertEquals("$.a", reader.getPath());
+    reader.endObject();
+    assertEquals("$", reader.getPreviousPath());
+    assertEquals("$", reader.getPath());
+  }
+
+  @Test public void objectPath() throws IOException {
+    JsonReader reader = factory.create("{\"a\":1,\"b\":2}");
+    assertEquals("$", reader.getPreviousPath());
+    assertEquals("$", reader.getPath());
+
+    reader.peek();
+    assertEquals("$", reader.getPreviousPath());
+    assertEquals("$", reader.getPath());
+    reader.beginObject();
+    assertEquals("$.", reader.getPreviousPath());
+    assertEquals("$.", reader.getPath());
+
+    reader.peek();
+    assertEquals("$.", reader.getPreviousPath());
+    assertEquals("$.", reader.getPath());
+    reader.nextName();
+    assertEquals("$.a", reader.getPreviousPath());
+    assertEquals("$.a", reader.getPath());
+
+    reader.peek();
+    assertEquals("$.a", reader.getPreviousPath());
+    assertEquals("$.a", reader.getPath());
+    reader.nextInt();
+    assertEquals("$.a", reader.getPreviousPath());
+    assertEquals("$.a", reader.getPath());
+
+    reader.peek();
+    assertEquals("$.a", reader.getPreviousPath());
+    assertEquals("$.a", reader.getPath());
+    reader.nextName();
+    assertEquals("$.b", reader.getPreviousPath());
+    assertEquals("$.b", reader.getPath());
+
+    reader.peek();
+    assertEquals("$.b", reader.getPreviousPath());
+    assertEquals("$.b", reader.getPath());
+    reader.nextInt();
+    assertEquals("$.b", reader.getPreviousPath());
+    assertEquals("$.b", reader.getPath());
+
+    reader.peek();
+    assertEquals("$.b", reader.getPreviousPath());
+    assertEquals("$.b", reader.getPath());
+    reader.endObject();
+    assertEquals("$", reader.getPreviousPath());
+    assertEquals("$", reader.getPath());
+
+    reader.peek();
+    assertEquals("$", reader.getPreviousPath());
+    assertEquals("$", reader.getPath());
+    reader.close();
+    assertEquals("$", reader.getPreviousPath());
+    assertEquals("$", reader.getPath());
+  }
+
+  @Test public void arrayPath() throws IOException {
+    JsonReader reader = factory.create("[1,2]");
+    assertEquals("$", reader.getPreviousPath());
+    assertEquals("$", reader.getPath());
+
+    reader.peek();
+    assertEquals("$", reader.getPreviousPath());
+    assertEquals("$", reader.getPath());
+    reader.beginArray();
+    assertEquals("$[0]", reader.getPreviousPath());
+    assertEquals("$[0]", reader.getPath());
+
+    reader.peek();
+    assertEquals("$[0]", reader.getPreviousPath());
+    assertEquals("$[0]", reader.getPath());
+    reader.nextInt();
+    assertEquals("$[0]", reader.getPreviousPath());
+    assertEquals("$[1]", reader.getPath());
+
+    reader.peek();
+    assertEquals("$[0]", reader.getPreviousPath());
+    assertEquals("$[1]", reader.getPath());
+    reader.nextInt();
+    assertEquals("$[1]", reader.getPreviousPath());
+    assertEquals("$[2]", reader.getPath());
+
+    reader.peek();
+    assertEquals("$[1]", reader.getPreviousPath());
+    assertEquals("$[2]", reader.getPath());
+    reader.endArray();
+    assertEquals("$", reader.getPreviousPath());
+    assertEquals("$", reader.getPath());
+
+    reader.peek();
+    assertEquals("$", reader.getPreviousPath());
+    assertEquals("$", reader.getPath());
+    reader.close();
+    assertEquals("$", reader.getPreviousPath());
+    assertEquals("$", reader.getPath());
+  }
+
+  @Test public void multipleTopLevelValuesInOneDocument() throws IOException {
+    assumeTrue(factory == Factory.STRING_READER);
+
+    JsonReader reader = factory.create("[][]");
+    reader.setLenient(true);
+    reader.beginArray();
+    reader.endArray();
+    assertEquals("$", reader.getPreviousPath());
+    assertEquals("$", reader.getPath());
+    reader.beginArray();
+    reader.endArray();
+    assertEquals("$", reader.getPreviousPath());
+    assertEquals("$", reader.getPath());
+  }
+
+  @Test public void skipArrayElements() throws IOException {
+    JsonReader reader = factory.create("[1,2,3]");
+    reader.beginArray();
+    reader.skipValue();
+    reader.skipValue();
+    assertEquals("$[1]", reader.getPreviousPath());
+    assertEquals("$[2]", reader.getPath());
+  }
+
+  @Test public void skipObjectNames() throws IOException {
+    JsonReader reader = factory.create("{\"a\":1}");
+    reader.beginObject();
+    reader.skipValue();
+    assertEquals("$.null", reader.getPreviousPath());
+    assertEquals("$.null", reader.getPath());
+  }
+
+  @Test public void skipObjectValues() throws IOException {
+    JsonReader reader = factory.create("{\"a\":1,\"b\":2}");
+    reader.beginObject();
+    assertEquals("$.", reader.getPreviousPath());
+    assertEquals("$.", reader.getPath());
+    reader.nextName();
+    reader.skipValue();
+    assertEquals("$.null", reader.getPreviousPath());
+    assertEquals("$.null", reader.getPath());
+    reader.nextName();
+    assertEquals("$.b", reader.getPreviousPath());
+    assertEquals("$.b", reader.getPath());
+  }
+
+  @Test public void skipNestedStructures() throws IOException {
+    JsonReader reader = factory.create("[[1,2,3],4]");
+    reader.beginArray();
+    reader.skipValue();
+    assertEquals("$[0]", reader.getPreviousPath());
+    assertEquals("$[1]", reader.getPath());
+  }
+
+  @Test public void arrayOfObjects() throws IOException {
+    JsonReader reader = factory.create("[{},{},{}]");
+    reader.beginArray();
+    assertEquals("$[0]", reader.getPreviousPath());
+    assertEquals("$[0]", reader.getPath());
+    reader.beginObject();
+    assertEquals("$[0].", reader.getPreviousPath());
+    assertEquals("$[0].", reader.getPath());
+    reader.endObject();
+    assertEquals("$[0]", reader.getPreviousPath());
+    assertEquals("$[1]", reader.getPath());
+    reader.beginObject();
+    assertEquals("$[1].", reader.getPreviousPath());
+    assertEquals("$[1].", reader.getPath());
+    reader.endObject();
+    assertEquals("$[1]", reader.getPreviousPath());
+    assertEquals("$[2]", reader.getPath());
+    reader.beginObject();
+    assertEquals("$[2].", reader.getPreviousPath());
+    assertEquals("$[2].", reader.getPath());
+    reader.endObject();
+    assertEquals("$[2]", reader.getPreviousPath());
+    assertEquals("$[3]", reader.getPath());
+    reader.endArray();
+    assertEquals("$", reader.getPreviousPath());
+    assertEquals("$", reader.getPath());
+  }
+
+  @Test public void arrayOfArrays() throws IOException {
+    JsonReader reader = factory.create("[[],[],[]]");
+    reader.beginArray();
+    assertEquals("$[0]", reader.getPreviousPath());
+    assertEquals("$[0]", reader.getPath());
+    reader.beginArray();
+    assertEquals("$[0][0]", reader.getPreviousPath());
+    assertEquals("$[0][0]", reader.getPath());
+    reader.endArray();
+    assertEquals("$[0]", reader.getPreviousPath());
+    assertEquals("$[1]", reader.getPath());
+    reader.beginArray();
+    assertEquals("$[1][0]", reader.getPreviousPath());
+    assertEquals("$[1][0]", reader.getPath());
+    reader.endArray();
+    assertEquals("$[1]", reader.getPreviousPath());
+    assertEquals("$[2]", reader.getPath());
+    reader.beginArray();
+    assertEquals("$[2][0]", reader.getPreviousPath());
+    assertEquals("$[2][0]", reader.getPath());
+    reader.endArray();
+    assertEquals("$[2]", reader.getPreviousPath());
+    assertEquals("$[3]", reader.getPath());
+    reader.endArray();
+    assertEquals("$", reader.getPreviousPath());
+    assertEquals("$", reader.getPath());
+  }
+
+  public enum Factory {
+    STRING_READER {
+      @Override public JsonReader create(String data) {
+        return new JsonReader(new StringReader(data));
+      }
+    },
+    OBJECT_READER {
+      @Override public JsonReader create(String data) {
+        JsonElement element = Streams.parse(new JsonReader(new StringReader(data)));
+        return new JsonTreeReader(element);
+      }
+    };
+
+    abstract JsonReader create(String data);
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/stream/JsonReaderTest.java b/gson/src/test/java/com/google/gson/stream/JsonReaderTest.java
new file mode 100644
index 0000000..7ec5e46
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/stream/JsonReaderTest.java
@@ -0,0 +1,1840 @@
+/*
+ * Copyright (C) 2010 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.stream;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.io.Reader;
+import java.io.StringReader;
+import java.util.Arrays;
+import junit.framework.TestCase;
+
+import static com.google.gson.stream.JsonToken.BEGIN_ARRAY;
+import static com.google.gson.stream.JsonToken.BEGIN_OBJECT;
+import static com.google.gson.stream.JsonToken.BOOLEAN;
+import static com.google.gson.stream.JsonToken.END_ARRAY;
+import static com.google.gson.stream.JsonToken.END_OBJECT;
+import static com.google.gson.stream.JsonToken.NAME;
+import static com.google.gson.stream.JsonToken.NULL;
+import static com.google.gson.stream.JsonToken.NUMBER;
+import static com.google.gson.stream.JsonToken.STRING;
+
+@SuppressWarnings("resource")
+public final class JsonReaderTest extends TestCase {
+  public void testReadArray() throws IOException {
+    JsonReader reader = new JsonReader(reader("[true, true]"));
+    reader.beginArray();
+    assertEquals(true, reader.nextBoolean());
+    assertEquals(true, reader.nextBoolean());
+    reader.endArray();
+    assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+  }
+
+  public void testReadEmptyArray() throws IOException {
+    JsonReader reader = new JsonReader(reader("[]"));
+    reader.beginArray();
+    assertFalse(reader.hasNext());
+    reader.endArray();
+    assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+  }
+
+  public void testReadObject() throws IOException {
+    JsonReader reader = new JsonReader(reader(
+        "{\"a\": \"android\", \"b\": \"banana\"}"));
+    reader.beginObject();
+    assertEquals("a", reader.nextName());
+    assertEquals("android", reader.nextString());
+    assertEquals("b", reader.nextName());
+    assertEquals("banana", reader.nextString());
+    reader.endObject();
+    assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+  }
+
+  public void testReadEmptyObject() throws IOException {
+    JsonReader reader = new JsonReader(reader("{}"));
+    reader.beginObject();
+    assertFalse(reader.hasNext());
+    reader.endObject();
+    assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+  }
+
+  public void testHasNextEndOfDocument() throws IOException {
+    JsonReader reader = new JsonReader(reader("{}"));
+    reader.beginObject();
+    reader.endObject();
+    assertFalse(reader.hasNext());
+  }
+
+  public void testSkipArray() throws IOException {
+    JsonReader reader = new JsonReader(reader(
+        "{\"a\": [\"one\", \"two\", \"three\"], \"b\": 123}"));
+    reader.beginObject();
+    assertEquals("a", reader.nextName());
+    reader.skipValue();
+    assertEquals("b", reader.nextName());
+    assertEquals(123, reader.nextInt());
+    reader.endObject();
+    assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+  }
+
+  public void testSkipArrayAfterPeek() throws Exception {
+    JsonReader reader = new JsonReader(reader(
+        "{\"a\": [\"one\", \"two\", \"three\"], \"b\": 123}"));
+    reader.beginObject();
+    assertEquals("a", reader.nextName());
+    assertEquals(BEGIN_ARRAY, reader.peek());
+    reader.skipValue();
+    assertEquals("b", reader.nextName());
+    assertEquals(123, reader.nextInt());
+    reader.endObject();
+    assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+  }
+
+  public void testSkipTopLevelObject() throws Exception {
+    JsonReader reader = new JsonReader(reader(
+        "{\"a\": [\"one\", \"two\", \"three\"], \"b\": 123}"));
+    reader.skipValue();
+    assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+  }
+
+  public void testSkipObject() throws IOException {
+    JsonReader reader = new JsonReader(reader(
+        "{\"a\": { \"c\": [], \"d\": [true, true, {}] }, \"b\": \"banana\"}"));
+    reader.beginObject();
+    assertEquals("a", reader.nextName());
+    reader.skipValue();
+    assertEquals("b", reader.nextName());
+    reader.skipValue();
+    reader.endObject();
+    assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+  }
+
+  public void testSkipObjectAfterPeek() throws Exception {
+    String json = "{" + "  \"one\": { \"num\": 1 }"
+        + ", \"two\": { \"num\": 2 }" + ", \"three\": { \"num\": 3 }" + "}";
+    JsonReader reader = new JsonReader(reader(json));
+    reader.beginObject();
+    assertEquals("one", reader.nextName());
+    assertEquals(BEGIN_OBJECT, reader.peek());
+    reader.skipValue();
+    assertEquals("two", reader.nextName());
+    assertEquals(BEGIN_OBJECT, reader.peek());
+    reader.skipValue();
+    assertEquals("three", reader.nextName());
+    reader.skipValue();
+    reader.endObject();
+    assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+  }
+
+  public void testSkipInteger() throws IOException {
+    JsonReader reader = new JsonReader(reader(
+        "{\"a\":123456789,\"b\":-123456789}"));
+    reader.beginObject();
+    assertEquals("a", reader.nextName());
+    reader.skipValue();
+    assertEquals("b", reader.nextName());
+    reader.skipValue();
+    reader.endObject();
+    assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+  }
+
+  public void testSkipDouble() throws IOException {
+    JsonReader reader = new JsonReader(reader(
+        "{\"a\":-123.456e-789,\"b\":123456789.0}"));
+    reader.beginObject();
+    assertEquals("a", reader.nextName());
+    reader.skipValue();
+    assertEquals("b", reader.nextName());
+    reader.skipValue();
+    reader.endObject();
+    assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+  }
+
+  public void testHelloWorld() throws IOException {
+    String json = "{\n" +
+        "   \"hello\": true,\n" +
+        "   \"foo\": [\"world\"]\n" +
+        "}";
+    JsonReader reader = new JsonReader(reader(json));
+    reader.beginObject();
+    assertEquals("hello", reader.nextName());
+    assertEquals(true, reader.nextBoolean());
+    assertEquals("foo", reader.nextName());
+    reader.beginArray();
+    assertEquals("world", reader.nextString());
+    reader.endArray();
+    reader.endObject();
+    assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+  }
+
+  public void testInvalidJsonInput() throws IOException {
+    String json = "{\n"
+        + "   \"h\\ello\": true,\n"
+        + "   \"foo\": [\"world\"]\n"
+        + "}";
+
+    JsonReader reader = new JsonReader(reader(json));
+    reader.beginObject();
+    try {
+      reader.nextName();
+      fail();
+    } catch (IOException expected) {
+    }
+  }
+
+  @SuppressWarnings("unused")
+  public void testNulls() {
+    try {
+      new JsonReader(null);
+      fail();
+    } catch (NullPointerException expected) {
+    }
+  }
+
+  public void testEmptyString() {
+    try {
+      new JsonReader(reader("")).beginArray();
+      fail();
+    } catch (IOException expected) {
+    }
+    try {
+      new JsonReader(reader("")).beginObject();
+      fail();
+    } catch (IOException expected) {
+    }
+  }
+
+  public void testCharacterUnescaping() throws IOException {
+    String json = "[\"a\","
+        + "\"a\\\"\","
+        + "\"\\\"\","
+        + "\":\","
+        + "\",\","
+        + "\"\\b\","
+        + "\"\\f\","
+        + "\"\\n\","
+        + "\"\\r\","
+        + "\"\\t\","
+        + "\" \","
+        + "\"\\\\\","
+        + "\"{\","
+        + "\"}\","
+        + "\"[\","
+        + "\"]\","
+        + "\"\\u0000\","
+        + "\"\\u0019\","
+        + "\"\\u20AC\""
+        + "]";
+    JsonReader reader = new JsonReader(reader(json));
+    reader.beginArray();
+    assertEquals("a", reader.nextString());
+    assertEquals("a\"", reader.nextString());
+    assertEquals("\"", reader.nextString());
+    assertEquals(":", reader.nextString());
+    assertEquals(",", reader.nextString());
+    assertEquals("\b", reader.nextString());
+    assertEquals("\f", reader.nextString());
+    assertEquals("\n", reader.nextString());
+    assertEquals("\r", reader.nextString());
+    assertEquals("\t", reader.nextString());
+    assertEquals(" ", reader.nextString());
+    assertEquals("\\", reader.nextString());
+    assertEquals("{", reader.nextString());
+    assertEquals("}", reader.nextString());
+    assertEquals("[", reader.nextString());
+    assertEquals("]", reader.nextString());
+    assertEquals("\0", reader.nextString());
+    assertEquals("\u0019", reader.nextString());
+    assertEquals("\u20AC", reader.nextString());
+    reader.endArray();
+    assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+  }
+
+  public void testUnescapingInvalidCharacters() throws IOException {
+    String json = "[\"\\u000g\"]";
+    JsonReader reader = new JsonReader(reader(json));
+    reader.beginArray();
+    try {
+      reader.nextString();
+      fail();
+    } catch (NumberFormatException expected) {
+    }
+  }
+
+  public void testUnescapingTruncatedCharacters() throws IOException {
+    String json = "[\"\\u000";
+    JsonReader reader = new JsonReader(reader(json));
+    reader.beginArray();
+    try {
+      reader.nextString();
+      fail();
+    } catch (IOException expected) {
+    }
+  }
+
+  public void testUnescapingTruncatedSequence() throws IOException {
+    String json = "[\"\\";
+    JsonReader reader = new JsonReader(reader(json));
+    reader.beginArray();
+    try {
+      reader.nextString();
+      fail();
+    } catch (IOException expected) {
+    }
+  }
+
+  public void testIntegersWithFractionalPartSpecified() throws IOException {
+    JsonReader reader = new JsonReader(reader("[1.0,1.0,1.0]"));
+    reader.beginArray();
+    assertEquals(1.0, reader.nextDouble());
+    assertEquals(1, reader.nextInt());
+    assertEquals(1L, reader.nextLong());
+  }
+
+  public void testDoubles() throws IOException {
+    String json = "[-0.0,"
+        + "1.0,"
+        + "1.7976931348623157E308,"
+        + "4.9E-324,"
+        + "0.0,"
+        + "0.00,"
+        + "-0.5,"
+        + "2.2250738585072014E-308,"
+        + "3.141592653589793,"
+        + "2.718281828459045,"
+        + "0,"
+        + "0.01,"
+        + "0e0,"
+        + "1e+0,"
+        + "1e-0,"
+        + "1e0000," // leading 0 is allowed for exponent
+        + "1e00001,"
+        + "1e+1]";
+    JsonReader reader = new JsonReader(reader(json));
+    reader.beginArray();
+    assertEquals(-0.0, reader.nextDouble());
+    assertEquals(1.0, reader.nextDouble());
+    assertEquals(1.7976931348623157E308, reader.nextDouble());
+    assertEquals(4.9E-324, reader.nextDouble());
+    assertEquals(0.0, reader.nextDouble());
+    assertEquals(0.0, reader.nextDouble());
+    assertEquals(-0.5, reader.nextDouble());
+    assertEquals(2.2250738585072014E-308, reader.nextDouble());
+    assertEquals(3.141592653589793, reader.nextDouble());
+    assertEquals(2.718281828459045, reader.nextDouble());
+    assertEquals(0.0, reader.nextDouble());
+    assertEquals(0.01, reader.nextDouble());
+    assertEquals(0.0, reader.nextDouble());
+    assertEquals(1.0, reader.nextDouble());
+    assertEquals(1.0, reader.nextDouble());
+    assertEquals(1.0, reader.nextDouble());
+    assertEquals(10.0, reader.nextDouble());
+    assertEquals(10.0, reader.nextDouble());
+    reader.endArray();
+    assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+  }
+
+  public void testStrictNonFiniteDoubles() throws IOException {
+    String json = "[NaN]";
+    JsonReader reader = new JsonReader(reader(json));
+    reader.beginArray();
+    try {
+      reader.nextDouble();
+      fail();
+    } catch (MalformedJsonException expected) {
+    }
+  }
+
+  public void testStrictQuotedNonFiniteDoubles() throws IOException {
+    String json = "[\"NaN\"]";
+    JsonReader reader = new JsonReader(reader(json));
+    reader.beginArray();
+    try {
+      reader.nextDouble();
+      fail();
+    } catch (MalformedJsonException expected) {
+    }
+  }
+
+  public void testLenientNonFiniteDoubles() throws IOException {
+    String json = "[NaN, -Infinity, Infinity]";
+    JsonReader reader = new JsonReader(reader(json));
+    reader.setLenient(true);
+    reader.beginArray();
+    assertTrue(Double.isNaN(reader.nextDouble()));
+    assertEquals(Double.NEGATIVE_INFINITY, reader.nextDouble());
+    assertEquals(Double.POSITIVE_INFINITY, reader.nextDouble());
+    reader.endArray();
+  }
+
+  public void testLenientQuotedNonFiniteDoubles() throws IOException {
+    String json = "[\"NaN\", \"-Infinity\", \"Infinity\"]";
+    JsonReader reader = new JsonReader(reader(json));
+    reader.setLenient(true);
+    reader.beginArray();
+    assertTrue(Double.isNaN(reader.nextDouble()));
+    assertEquals(Double.NEGATIVE_INFINITY, reader.nextDouble());
+    assertEquals(Double.POSITIVE_INFINITY, reader.nextDouble());
+    reader.endArray();
+  }
+
+  public void testStrictNonFiniteDoublesWithSkipValue() throws IOException {
+    String json = "[NaN]";
+    JsonReader reader = new JsonReader(reader(json));
+    reader.beginArray();
+    try {
+      reader.skipValue();
+      fail();
+    } catch (MalformedJsonException expected) {
+    }
+  }
+
+  public void testLongs() throws IOException {
+    String json = "[0,0,0,"
+        + "1,1,1,"
+        + "-1,-1,-1,"
+        + "-9223372036854775808,"
+        + "9223372036854775807]";
+    JsonReader reader = new JsonReader(reader(json));
+    reader.beginArray();
+    assertEquals(0L, reader.nextLong());
+    assertEquals(0, reader.nextInt());
+    assertEquals(0.0, reader.nextDouble());
+    assertEquals(1L, reader.nextLong());
+    assertEquals(1, reader.nextInt());
+    assertEquals(1.0, reader.nextDouble());
+    assertEquals(-1L, reader.nextLong());
+    assertEquals(-1, reader.nextInt());
+    assertEquals(-1.0, reader.nextDouble());
+    try {
+      reader.nextInt();
+      fail();
+    } catch (NumberFormatException expected) {
+    }
+    assertEquals(Long.MIN_VALUE, reader.nextLong());
+    try {
+      reader.nextInt();
+      fail();
+    } catch (NumberFormatException expected) {
+    }
+    assertEquals(Long.MAX_VALUE, reader.nextLong());
+    reader.endArray();
+    assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+  }
+
+  public void disabled_testNumberWithOctalPrefix() throws IOException {
+    String json = "[01]";
+    JsonReader reader = new JsonReader(reader(json));
+    reader.beginArray();
+    try {
+      reader.peek();
+      fail();
+    } catch (MalformedJsonException expected) {
+    }
+    try {
+      reader.nextInt();
+      fail();
+    } catch (MalformedJsonException expected) {
+    }
+    try {
+      reader.nextLong();
+      fail();
+    } catch (MalformedJsonException expected) {
+    }
+    try {
+      reader.nextDouble();
+      fail();
+    } catch (MalformedJsonException expected) {
+    }
+    assertEquals("01", reader.nextString());
+    reader.endArray();
+    assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+  }
+
+  public void testBooleans() throws IOException {
+    JsonReader reader = new JsonReader(reader("[true,false]"));
+    reader.beginArray();
+    assertEquals(true, reader.nextBoolean());
+    assertEquals(false, reader.nextBoolean());
+    reader.endArray();
+    assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+  }
+
+  public void testPeekingUnquotedStringsPrefixedWithBooleans() throws IOException {
+    JsonReader reader = new JsonReader(reader("[truey]"));
+    reader.setLenient(true);
+    reader.beginArray();
+    assertEquals(STRING, reader.peek());
+    try {
+      reader.nextBoolean();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+    assertEquals("truey", reader.nextString());
+    reader.endArray();
+  }
+
+  public void testMalformedNumbers() throws IOException {
+    assertNotANumber("-");
+    assertNotANumber(".");
+
+    // plus sign is not allowed for integer part
+    assertNotANumber("+1");
+
+    // leading 0 is not allowed for integer part
+    assertNotANumber("00");
+    assertNotANumber("01");
+
+    // exponent lacks digit
+    assertNotANumber("e");
+    assertNotANumber("0e");
+    assertNotANumber(".e");
+    assertNotANumber("0.e");
+    assertNotANumber("-.0e");
+
+    // no integer
+    assertNotANumber("e1");
+    assertNotANumber(".e1");
+    assertNotANumber("-e1");
+
+    // trailing characters
+    assertNotANumber("1x");
+    assertNotANumber("1.1x");
+    assertNotANumber("1e1x");
+    assertNotANumber("1ex");
+    assertNotANumber("1.1ex");
+    assertNotANumber("1.1e1x");
+
+    // fraction has no digit
+    assertNotANumber("0.");
+    assertNotANumber("-0.");
+    assertNotANumber("0.e1");
+    assertNotANumber("-0.e1");
+
+    // no leading digit
+    assertNotANumber(".0");
+    assertNotANumber("-.0");
+    assertNotANumber(".0e1");
+    assertNotANumber("-.0e1");
+  }
+
+  private void assertNotANumber(String s) throws IOException {
+    JsonReader reader = new JsonReader(reader(s));
+    reader.setLenient(true);
+    assertEquals(JsonToken.STRING, reader.peek());
+    assertEquals(s, reader.nextString());
+
+    JsonReader strictReader = new JsonReader(reader(s));
+    try {
+      strictReader.nextDouble();
+      fail("Should have failed reading " + s + " as double");
+    } catch (MalformedJsonException e) {
+    }
+  }
+
+  public void testPeekingUnquotedStringsPrefixedWithIntegers() throws IOException {
+    JsonReader reader = new JsonReader(reader("[12.34e5x]"));
+    reader.setLenient(true);
+    reader.beginArray();
+    assertEquals(STRING, reader.peek());
+    try {
+      reader.nextInt();
+      fail();
+    } catch (NumberFormatException expected) {
+    }
+    assertEquals("12.34e5x", reader.nextString());
+  }
+
+  public void testPeekLongMinValue() throws IOException {
+    JsonReader reader = new JsonReader(reader("[-9223372036854775808]"));
+    reader.setLenient(true);
+    reader.beginArray();
+    assertEquals(NUMBER, reader.peek());
+    assertEquals(-9223372036854775808L, reader.nextLong());
+  }
+
+  public void testPeekLongMaxValue() throws IOException {
+    JsonReader reader = new JsonReader(reader("[9223372036854775807]"));
+    reader.setLenient(true);
+    reader.beginArray();
+    assertEquals(NUMBER, reader.peek());
+    assertEquals(9223372036854775807L, reader.nextLong());
+  }
+
+  public void testLongLargerThanMaxLongThatWrapsAround() throws IOException {
+    JsonReader reader = new JsonReader(reader("[22233720368547758070]"));
+    reader.setLenient(true);
+    reader.beginArray();
+    assertEquals(NUMBER, reader.peek());
+    try {
+      reader.nextLong();
+      fail();
+    } catch (NumberFormatException expected) {
+    }
+  }
+
+  public void testLongLargerThanMinLongThatWrapsAround() throws IOException {
+    JsonReader reader = new JsonReader(reader("[-22233720368547758070]"));
+    reader.setLenient(true);
+    reader.beginArray();
+    assertEquals(NUMBER, reader.peek());
+    try {
+      reader.nextLong();
+      fail();
+    } catch (NumberFormatException expected) {
+    }
+  }
+
+  /**
+   * Issue 1053, negative zero.
+   * @throws Exception
+   */
+  public void testNegativeZero() throws Exception {
+    JsonReader reader = new JsonReader(reader("[-0]"));
+    reader.setLenient(false);
+    reader.beginArray();
+    assertEquals(NUMBER, reader.peek());
+    assertEquals("-0", reader.nextString());
+  }
+
+  /**
+   * This test fails because there's no double for 9223372036854775808, and our
+   * long parsing uses Double.parseDouble() for fractional values.
+   */
+  public void disabled_testPeekLargerThanLongMaxValue() throws IOException {
+    JsonReader reader = new JsonReader(reader("[9223372036854775808]"));
+    reader.setLenient(true);
+    reader.beginArray();
+    assertEquals(NUMBER, reader.peek());
+    try {
+      reader.nextLong();
+      fail();
+    } catch (NumberFormatException e) {
+    }
+  }
+
+  /**
+   * This test fails because there's no double for -9223372036854775809, and our
+   * long parsing uses Double.parseDouble() for fractional values.
+   */
+  public void disabled_testPeekLargerThanLongMinValue() throws IOException {
+    JsonReader reader = new JsonReader(reader("[-9223372036854775809]"));
+    reader.setLenient(true);
+    reader.beginArray();
+    assertEquals(NUMBER, reader.peek());
+    try {
+      reader.nextLong();
+      fail();
+    } catch (NumberFormatException expected) {
+    }
+    assertEquals(-9223372036854775809d, reader.nextDouble());
+  }
+
+  /**
+   * This test fails because there's no double for 9223372036854775806, and
+   * our long parsing uses Double.parseDouble() for fractional values.
+   */
+  public void disabled_testHighPrecisionLong() throws IOException {
+    String json = "[9223372036854775806.000]";
+    JsonReader reader = new JsonReader(reader(json));
+    reader.beginArray();
+    assertEquals(9223372036854775806L, reader.nextLong());
+    reader.endArray();
+  }
+
+  public void testPeekMuchLargerThanLongMinValue() throws IOException {
+    JsonReader reader = new JsonReader(reader("[-92233720368547758080]"));
+    reader.setLenient(true);
+    reader.beginArray();
+    assertEquals(NUMBER, reader.peek());
+    try {
+      reader.nextLong();
+      fail();
+    } catch (NumberFormatException expected) {
+    }
+    assertEquals(-92233720368547758080d, reader.nextDouble());
+  }
+
+  public void testQuotedNumberWithEscape() throws IOException {
+    JsonReader reader = new JsonReader(reader("[\"12\u00334\"]"));
+    reader.setLenient(true);
+    reader.beginArray();
+    assertEquals(STRING, reader.peek());
+    assertEquals(1234, reader.nextInt());
+  }
+
+  public void testMixedCaseLiterals() throws IOException {
+    JsonReader reader = new JsonReader(reader("[True,TruE,False,FALSE,NULL,nulL]"));
+    reader.beginArray();
+    assertEquals(true, reader.nextBoolean());
+    assertEquals(true, reader.nextBoolean());
+    assertEquals(false, reader.nextBoolean());
+    assertEquals(false, reader.nextBoolean());
+    reader.nextNull();
+    reader.nextNull();
+    reader.endArray();
+    assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+  }
+
+  public void testMissingValue() throws IOException {
+    JsonReader reader = new JsonReader(reader("{\"a\":}"));
+    reader.beginObject();
+    assertEquals("a", reader.nextName());
+    try {
+      reader.nextString();
+      fail();
+    } catch (IOException expected) {
+    }
+  }
+
+  public void testPrematureEndOfInput() throws IOException {
+    JsonReader reader = new JsonReader(reader("{\"a\":true,"));
+    reader.beginObject();
+    assertEquals("a", reader.nextName());
+    assertEquals(true, reader.nextBoolean());
+    try {
+      reader.nextName();
+      fail();
+    } catch (IOException expected) {
+    }
+  }
+
+  public void testPrematurelyClosed() throws IOException {
+    try {
+      JsonReader reader = new JsonReader(reader("{\"a\":[]}"));
+      reader.beginObject();
+      reader.close();
+      reader.nextName();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+
+    try {
+      JsonReader reader = new JsonReader(reader("{\"a\":[]}"));
+      reader.close();
+      reader.beginObject();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+
+    try {
+      JsonReader reader = new JsonReader(reader("{\"a\":true}"));
+      reader.beginObject();
+      reader.nextName();
+      reader.peek();
+      reader.close();
+      reader.nextBoolean();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+  }
+
+  public void testNextFailuresDoNotAdvance() throws IOException {
+    JsonReader reader = new JsonReader(reader("{\"a\":true}"));
+    reader.beginObject();
+    try {
+      reader.nextString();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+    assertEquals("a", reader.nextName());
+    try {
+      reader.nextName();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+    try {
+      reader.beginArray();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+    try {
+      reader.endArray();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+    try {
+      reader.beginObject();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+    try {
+      reader.endObject();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+    assertEquals(true, reader.nextBoolean());
+    try {
+      reader.nextString();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+    try {
+      reader.nextName();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+    try {
+      reader.beginArray();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+    try {
+      reader.endArray();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+    reader.endObject();
+    assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+    reader.close();
+  }
+
+  public void testIntegerMismatchFailuresDoNotAdvance() throws IOException {
+    JsonReader reader = new JsonReader(reader("[1.5]"));
+    reader.beginArray();
+    try {
+      reader.nextInt();
+      fail();
+    } catch (NumberFormatException expected) {
+    }
+    assertEquals(1.5d, reader.nextDouble());
+    reader.endArray();
+  }
+
+  public void testStringNullIsNotNull() throws IOException {
+    JsonReader reader = new JsonReader(reader("[\"null\"]"));
+    reader.beginArray();
+    try {
+      reader.nextNull();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+  }
+
+  public void testNullLiteralIsNotAString() throws IOException {
+    JsonReader reader = new JsonReader(reader("[null]"));
+    reader.beginArray();
+    try {
+      reader.nextString();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+  }
+
+  public void testStrictNameValueSeparator() throws IOException {
+    JsonReader reader = new JsonReader(reader("{\"a\"=true}"));
+    reader.beginObject();
+    assertEquals("a", reader.nextName());
+    try {
+      reader.nextBoolean();
+      fail();
+    } catch (IOException expected) {
+    }
+
+    reader = new JsonReader(reader("{\"a\"=>true}"));
+    reader.beginObject();
+    assertEquals("a", reader.nextName());
+    try {
+      reader.nextBoolean();
+      fail();
+    } catch (IOException expected) {
+    }
+  }
+
+  public void testLenientNameValueSeparator() throws IOException {
+    JsonReader reader = new JsonReader(reader("{\"a\"=true}"));
+    reader.setLenient(true);
+    reader.beginObject();
+    assertEquals("a", reader.nextName());
+    assertEquals(true, reader.nextBoolean());
+
+    reader = new JsonReader(reader("{\"a\"=>true}"));
+    reader.setLenient(true);
+    reader.beginObject();
+    assertEquals("a", reader.nextName());
+    assertEquals(true, reader.nextBoolean());
+  }
+
+  public void testStrictNameValueSeparatorWithSkipValue() throws IOException {
+    JsonReader reader = new JsonReader(reader("{\"a\"=true}"));
+    reader.beginObject();
+    assertEquals("a", reader.nextName());
+    try {
+      reader.skipValue();
+      fail();
+    } catch (IOException expected) {
+    }
+
+    reader = new JsonReader(reader("{\"a\"=>true}"));
+    reader.beginObject();
+    assertEquals("a", reader.nextName());
+    try {
+      reader.skipValue();
+      fail();
+    } catch (IOException expected) {
+    }
+  }
+
+  public void testCommentsInStringValue() throws Exception {
+    JsonReader reader = new JsonReader(reader("[\"// comment\"]"));
+    reader.beginArray();
+    assertEquals("// comment", reader.nextString());
+    reader.endArray();
+
+    reader = new JsonReader(reader("{\"a\":\"#someComment\"}"));
+    reader.beginObject();
+    assertEquals("a", reader.nextName());
+    assertEquals("#someComment", reader.nextString());
+    reader.endObject();
+
+    reader = new JsonReader(reader("{\"#//a\":\"#some //Comment\"}"));
+    reader.beginObject();
+    assertEquals("#//a", reader.nextName());
+    assertEquals("#some //Comment", reader.nextString());
+    reader.endObject();
+  }
+
+  public void testStrictComments() throws IOException {
+    JsonReader reader = new JsonReader(reader("[// comment \n true]"));
+    reader.beginArray();
+    try {
+      reader.nextBoolean();
+      fail();
+    } catch (IOException expected) {
+    }
+
+    reader = new JsonReader(reader("[# comment \n true]"));
+    reader.beginArray();
+    try {
+      reader.nextBoolean();
+      fail();
+    } catch (IOException expected) {
+    }
+
+    reader = new JsonReader(reader("[/* comment */ true]"));
+    reader.beginArray();
+    try {
+      reader.nextBoolean();
+      fail();
+    } catch (IOException expected) {
+    }
+  }
+
+  public void testLenientComments() throws IOException {
+    JsonReader reader = new JsonReader(reader("[// comment \n true]"));
+    reader.setLenient(true);
+    reader.beginArray();
+    assertEquals(true, reader.nextBoolean());
+
+    reader = new JsonReader(reader("[# comment \n true]"));
+    reader.setLenient(true);
+    reader.beginArray();
+    assertEquals(true, reader.nextBoolean());
+
+    reader = new JsonReader(reader("[/* comment */ true]"));
+    reader.setLenient(true);
+    reader.beginArray();
+    assertEquals(true, reader.nextBoolean());
+  }
+
+  public void testStrictCommentsWithSkipValue() throws IOException {
+    JsonReader reader = new JsonReader(reader("[// comment \n true]"));
+    reader.beginArray();
+    try {
+      reader.skipValue();
+      fail();
+    } catch (IOException expected) {
+    }
+
+    reader = new JsonReader(reader("[# comment \n true]"));
+    reader.beginArray();
+    try {
+      reader.skipValue();
+      fail();
+    } catch (IOException expected) {
+    }
+
+    reader = new JsonReader(reader("[/* comment */ true]"));
+    reader.beginArray();
+    try {
+      reader.skipValue();
+      fail();
+    } catch (IOException expected) {
+    }
+  }
+
+  public void testStrictUnquotedNames() throws IOException {
+    JsonReader reader = new JsonReader(reader("{a:true}"));
+    reader.beginObject();
+    try {
+      reader.nextName();
+      fail();
+    } catch (IOException expected) {
+    }
+  }
+
+  public void testLenientUnquotedNames() throws IOException {
+    JsonReader reader = new JsonReader(reader("{a:true}"));
+    reader.setLenient(true);
+    reader.beginObject();
+    assertEquals("a", reader.nextName());
+  }
+
+  public void testStrictUnquotedNamesWithSkipValue() throws IOException {
+    JsonReader reader = new JsonReader(reader("{a:true}"));
+    reader.beginObject();
+    try {
+      reader.skipValue();
+      fail();
+    } catch (IOException expected) {
+    }
+  }
+
+  public void testStrictSingleQuotedNames() throws IOException {
+    JsonReader reader = new JsonReader(reader("{'a':true}"));
+    reader.beginObject();
+    try {
+      reader.nextName();
+      fail();
+    } catch (IOException expected) {
+    }
+  }
+
+  public void testLenientSingleQuotedNames() throws IOException {
+    JsonReader reader = new JsonReader(reader("{'a':true}"));
+    reader.setLenient(true);
+    reader.beginObject();
+    assertEquals("a", reader.nextName());
+  }
+
+  public void testStrictSingleQuotedNamesWithSkipValue() throws IOException {
+    JsonReader reader = new JsonReader(reader("{'a':true}"));
+    reader.beginObject();
+    try {
+      reader.skipValue();
+      fail();
+    } catch (IOException expected) {
+    }
+  }
+
+  public void testStrictUnquotedStrings() throws IOException {
+    JsonReader reader = new JsonReader(reader("[a]"));
+    reader.beginArray();
+    try {
+      reader.nextString();
+      fail();
+    } catch (MalformedJsonException expected) {
+    }
+  }
+
+  public void testStrictUnquotedStringsWithSkipValue() throws IOException {
+    JsonReader reader = new JsonReader(reader("[a]"));
+    reader.beginArray();
+    try {
+      reader.skipValue();
+      fail();
+    } catch (MalformedJsonException expected) {
+    }
+  }
+
+  public void testLenientUnquotedStrings() throws IOException {
+    JsonReader reader = new JsonReader(reader("[a]"));
+    reader.setLenient(true);
+    reader.beginArray();
+    assertEquals("a", reader.nextString());
+  }
+
+  public void testStrictSingleQuotedStrings() throws IOException {
+    JsonReader reader = new JsonReader(reader("['a']"));
+    reader.beginArray();
+    try {
+      reader.nextString();
+      fail();
+    } catch (IOException expected) {
+    }
+  }
+
+  public void testLenientSingleQuotedStrings() throws IOException {
+    JsonReader reader = new JsonReader(reader("['a']"));
+    reader.setLenient(true);
+    reader.beginArray();
+    assertEquals("a", reader.nextString());
+  }
+
+  public void testStrictSingleQuotedStringsWithSkipValue() throws IOException {
+    JsonReader reader = new JsonReader(reader("['a']"));
+    reader.beginArray();
+    try {
+      reader.skipValue();
+      fail();
+    } catch (IOException expected) {
+    }
+  }
+
+  public void testStrictSemicolonDelimitedArray() throws IOException {
+    JsonReader reader = new JsonReader(reader("[true;true]"));
+    reader.beginArray();
+    try {
+      reader.nextBoolean();
+      reader.nextBoolean();
+      fail();
+    } catch (IOException expected) {
+    }
+  }
+
+  public void testLenientSemicolonDelimitedArray() throws IOException {
+    JsonReader reader = new JsonReader(reader("[true;true]"));
+    reader.setLenient(true);
+    reader.beginArray();
+    assertEquals(true, reader.nextBoolean());
+    assertEquals(true, reader.nextBoolean());
+  }
+
+  public void testStrictSemicolonDelimitedArrayWithSkipValue() throws IOException {
+    JsonReader reader = new JsonReader(reader("[true;true]"));
+    reader.beginArray();
+    try {
+      reader.skipValue();
+      reader.skipValue();
+      fail();
+    } catch (IOException expected) {
+    }
+  }
+
+  public void testStrictSemicolonDelimitedNameValuePair() throws IOException {
+    JsonReader reader = new JsonReader(reader("{\"a\":true;\"b\":true}"));
+    reader.beginObject();
+    assertEquals("a", reader.nextName());
+    try {
+      reader.nextBoolean();
+      reader.nextName();
+      fail();
+    } catch (IOException expected) {
+    }
+  }
+
+  public void testLenientSemicolonDelimitedNameValuePair() throws IOException {
+    JsonReader reader = new JsonReader(reader("{\"a\":true;\"b\":true}"));
+    reader.setLenient(true);
+    reader.beginObject();
+    assertEquals("a", reader.nextName());
+    assertEquals(true, reader.nextBoolean());
+    assertEquals("b", reader.nextName());
+  }
+
+  public void testStrictSemicolonDelimitedNameValuePairWithSkipValue() throws IOException {
+    JsonReader reader = new JsonReader(reader("{\"a\":true;\"b\":true}"));
+    reader.beginObject();
+    assertEquals("a", reader.nextName());
+    try {
+      reader.skipValue();
+      reader.skipValue();
+      fail();
+    } catch (IOException expected) {
+    }
+  }
+
+  public void testStrictUnnecessaryArraySeparators() throws IOException {
+    JsonReader reader = new JsonReader(reader("[true,,true]"));
+    reader.beginArray();
+    assertEquals(true, reader.nextBoolean());
+    try {
+      reader.nextNull();
+      fail();
+    } catch (IOException expected) {
+    }
+
+    reader = new JsonReader(reader("[,true]"));
+    reader.beginArray();
+    try {
+      reader.nextNull();
+      fail();
+    } catch (IOException expected) {
+    }
+
+    reader = new JsonReader(reader("[true,]"));
+    reader.beginArray();
+    assertEquals(true, reader.nextBoolean());
+    try {
+      reader.nextNull();
+      fail();
+    } catch (IOException expected) {
+    }
+
+    reader = new JsonReader(reader("[,]"));
+    reader.beginArray();
+    try {
+      reader.nextNull();
+      fail();
+    } catch (IOException expected) {
+    }
+  }
+
+  public void testLenientUnnecessaryArraySeparators() throws IOException {
+    JsonReader reader = new JsonReader(reader("[true,,true]"));
+    reader.setLenient(true);
+    reader.beginArray();
+    assertEquals(true, reader.nextBoolean());
+    reader.nextNull();
+    assertEquals(true, reader.nextBoolean());
+    reader.endArray();
+
+    reader = new JsonReader(reader("[,true]"));
+    reader.setLenient(true);
+    reader.beginArray();
+    reader.nextNull();
+    assertEquals(true, reader.nextBoolean());
+    reader.endArray();
+
+    reader = new JsonReader(reader("[true,]"));
+    reader.setLenient(true);
+    reader.beginArray();
+    assertEquals(true, reader.nextBoolean());
+    reader.nextNull();
+    reader.endArray();
+
+    reader = new JsonReader(reader("[,]"));
+    reader.setLenient(true);
+    reader.beginArray();
+    reader.nextNull();
+    reader.nextNull();
+    reader.endArray();
+  }
+
+  public void testStrictUnnecessaryArraySeparatorsWithSkipValue() throws IOException {
+    JsonReader reader = new JsonReader(reader("[true,,true]"));
+    reader.beginArray();
+    assertEquals(true, reader.nextBoolean());
+    try {
+      reader.skipValue();
+      fail();
+    } catch (IOException expected) {
+    }
+
+    reader = new JsonReader(reader("[,true]"));
+    reader.beginArray();
+    try {
+      reader.skipValue();
+      fail();
+    } catch (IOException expected) {
+    }
+
+    reader = new JsonReader(reader("[true,]"));
+    reader.beginArray();
+    assertEquals(true, reader.nextBoolean());
+    try {
+      reader.skipValue();
+      fail();
+    } catch (IOException expected) {
+    }
+
+    reader = new JsonReader(reader("[,]"));
+    reader.beginArray();
+    try {
+      reader.skipValue();
+      fail();
+    } catch (IOException expected) {
+    }
+  }
+
+  public void testStrictMultipleTopLevelValues() throws IOException {
+    JsonReader reader = new JsonReader(reader("[] []"));
+    reader.beginArray();
+    reader.endArray();
+    try {
+      reader.peek();
+      fail();
+    } catch (IOException expected) {
+    }
+  }
+
+  public void testLenientMultipleTopLevelValues() throws IOException {
+    JsonReader reader = new JsonReader(reader("[] true {}"));
+    reader.setLenient(true);
+    reader.beginArray();
+    reader.endArray();
+    assertEquals(true, reader.nextBoolean());
+    reader.beginObject();
+    reader.endObject();
+    assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+  }
+
+  public void testStrictMultipleTopLevelValuesWithSkipValue() throws IOException {
+    JsonReader reader = new JsonReader(reader("[] []"));
+    reader.beginArray();
+    reader.endArray();
+    try {
+      reader.skipValue();
+      fail();
+    } catch (IOException expected) {
+    }
+  }
+
+  public void testTopLevelValueTypes() throws IOException {
+    JsonReader reader1 = new JsonReader(reader("true"));
+    assertTrue(reader1.nextBoolean());
+    assertEquals(JsonToken.END_DOCUMENT, reader1.peek());
+
+    JsonReader reader2 = new JsonReader(reader("false"));
+    assertFalse(reader2.nextBoolean());
+    assertEquals(JsonToken.END_DOCUMENT, reader2.peek());
+
+    JsonReader reader3 = new JsonReader(reader("null"));
+    assertEquals(JsonToken.NULL, reader3.peek());
+    reader3.nextNull();
+    assertEquals(JsonToken.END_DOCUMENT, reader3.peek());
+
+    JsonReader reader4 = new JsonReader(reader("123"));
+    assertEquals(123, reader4.nextInt());
+    assertEquals(JsonToken.END_DOCUMENT, reader4.peek());
+
+    JsonReader reader5 = new JsonReader(reader("123.4"));
+    assertEquals(123.4, reader5.nextDouble());
+    assertEquals(JsonToken.END_DOCUMENT, reader5.peek());
+
+    JsonReader reader6 = new JsonReader(reader("\"a\""));
+    assertEquals("a", reader6.nextString());
+    assertEquals(JsonToken.END_DOCUMENT, reader6.peek());
+  }
+
+  public void testTopLevelValueTypeWithSkipValue() throws IOException {
+    JsonReader reader = new JsonReader(reader("true"));
+    reader.skipValue();
+    assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+  }
+
+  public void testStrictNonExecutePrefix() {
+    JsonReader reader = new JsonReader(reader(")]}'\n []"));
+    try {
+      reader.beginArray();
+      fail();
+    } catch (IOException expected) {
+    }
+  }
+
+  public void testStrictNonExecutePrefixWithSkipValue() {
+    JsonReader reader = new JsonReader(reader(")]}'\n []"));
+    try {
+      reader.skipValue();
+      fail();
+    } catch (IOException expected) {
+    }
+  }
+
+  public void testLenientNonExecutePrefix() throws IOException {
+    JsonReader reader = new JsonReader(reader(")]}'\n []"));
+    reader.setLenient(true);
+    reader.beginArray();
+    reader.endArray();
+    assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+  }
+
+  public void testLenientNonExecutePrefixWithLeadingWhitespace() throws IOException {
+    JsonReader reader = new JsonReader(reader("\r\n \t)]}'\n []"));
+    reader.setLenient(true);
+    reader.beginArray();
+    reader.endArray();
+    assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+  }
+
+  public void testLenientPartialNonExecutePrefix() {
+    JsonReader reader = new JsonReader(reader(")]}' []"));
+    reader.setLenient(true);
+    try {
+      assertEquals(")", reader.nextString());
+      reader.nextString();
+      fail();
+    } catch (IOException expected) {
+    }
+  }
+
+  public void testBomIgnoredAsFirstCharacterOfDocument() throws IOException {
+    JsonReader reader = new JsonReader(reader("\ufeff[]"));
+    reader.beginArray();
+    reader.endArray();
+  }
+
+  public void testBomForbiddenAsOtherCharacterInDocument() throws IOException {
+    JsonReader reader = new JsonReader(reader("[\ufeff]"));
+    reader.beginArray();
+    try {
+      reader.endArray();
+      fail();
+    } catch (IOException expected) {
+    }
+  }
+
+  public void testFailWithPosition() throws IOException {
+    testFailWithPosition("Expected value at line 6 column 5 path $[1]",
+        "[\n\n\n\n\n\"a\",}]");
+  }
+
+  public void testFailWithPositionGreaterThanBufferSize() throws IOException {
+    String spaces = repeat(' ', 8192);
+    testFailWithPosition("Expected value at line 6 column 5 path $[1]",
+        "[\n\n" + spaces + "\n\n\n\"a\",}]");
+  }
+
+  public void testFailWithPositionOverSlashSlashEndOfLineComment() throws IOException {
+    testFailWithPosition("Expected value at line 5 column 6 path $[1]",
+        "\n// foo\n\n//bar\r\n[\"a\",}");
+  }
+
+  public void testFailWithPositionOverHashEndOfLineComment() throws IOException {
+    testFailWithPosition("Expected value at line 5 column 6 path $[1]",
+        "\n# foo\n\n#bar\r\n[\"a\",}");
+  }
+
+  public void testFailWithPositionOverCStyleComment() throws IOException {
+    testFailWithPosition("Expected value at line 6 column 12 path $[1]",
+        "\n\n/* foo\n*\n*\r\nbar */[\"a\",}");
+  }
+
+  public void testFailWithPositionOverQuotedString() throws IOException {
+    testFailWithPosition("Expected value at line 5 column 3 path $[1]",
+        "[\"foo\nbar\r\nbaz\n\",\n  }");
+  }
+
+  public void testFailWithPositionOverUnquotedString() throws IOException {
+    testFailWithPosition("Expected value at line 5 column 2 path $[1]", "[\n\nabcd\n\n,}");
+  }
+
+  public void testFailWithEscapedNewlineCharacter() throws IOException {
+    testFailWithPosition("Expected value at line 5 column 3 path $[1]", "[\n\n\"\\\n\n\",}");
+  }
+
+  public void testFailWithPositionIsOffsetByBom() throws IOException {
+    testFailWithPosition("Expected value at line 1 column 6 path $[1]",
+        "\ufeff[\"a\",}]");
+  }
+
+  private void testFailWithPosition(String message, String json) throws IOException {
+    // Validate that it works reading the string normally.
+    JsonReader reader1 = new JsonReader(reader(json));
+    reader1.setLenient(true);
+    reader1.beginArray();
+    reader1.nextString();
+    try {
+      reader1.peek();
+      fail();
+    } catch (IOException expected) {
+      assertEquals(message, expected.getMessage());
+    }
+
+    // Also validate that it works when skipping.
+    JsonReader reader2 = new JsonReader(reader(json));
+    reader2.setLenient(true);
+    reader2.beginArray();
+    reader2.skipValue();
+    try {
+      reader2.peek();
+      fail();
+    } catch (IOException expected) {
+      assertEquals(message, expected.getMessage());
+    }
+  }
+
+  public void testFailWithPositionDeepPath() throws IOException {
+    JsonReader reader = new JsonReader(reader("[1,{\"a\":[2,3,}"));
+    reader.beginArray();
+    reader.nextInt();
+    reader.beginObject();
+    reader.nextName();
+    reader.beginArray();
+    reader.nextInt();
+    reader.nextInt();
+    try {
+      reader.peek();
+      fail();
+    } catch (IOException expected) {
+      assertEquals("Expected value at line 1 column 14 path $[1].a[2]", expected.getMessage());
+    }
+  }
+
+  public void testStrictVeryLongNumber() throws IOException {
+    JsonReader reader = new JsonReader(reader("[0." + repeat('9', 8192) + "]"));
+    reader.beginArray();
+    try {
+      assertEquals(1d, reader.nextDouble());
+      fail();
+    } catch (MalformedJsonException expected) {
+    }
+  }
+
+  public void testLenientVeryLongNumber() throws IOException {
+    JsonReader reader = new JsonReader(reader("[0." + repeat('9', 8192) + "]"));
+    reader.setLenient(true);
+    reader.beginArray();
+    assertEquals(JsonToken.STRING, reader.peek());
+    assertEquals(1d, reader.nextDouble());
+    reader.endArray();
+    assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+  }
+
+  public void testVeryLongUnquotedLiteral() throws IOException {
+    String literal = "a" + repeat('b', 8192) + "c";
+    JsonReader reader = new JsonReader(reader("[" + literal + "]"));
+    reader.setLenient(true);
+    reader.beginArray();
+    assertEquals(literal, reader.nextString());
+    reader.endArray();
+  }
+
+  public void testDeeplyNestedArrays() throws IOException {
+    // this is nested 40 levels deep; Gson is tuned for nesting is 30 levels deep or fewer
+    JsonReader reader = new JsonReader(reader(
+        "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]"));
+    for (int i = 0; i < 40; i++) {
+      reader.beginArray();
+    }
+    assertEquals("$[0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0]"
+        + "[0][0][0][0][0][0][0][0][0][0][0][0][0][0]", reader.getPath());
+    for (int i = 0; i < 40; i++) {
+      reader.endArray();
+    }
+    assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+  }
+
+  public void testDeeplyNestedObjects() throws IOException {
+    // Build a JSON document structured like {"a":{"a":{"a":{"a":true}}}}, but 40 levels deep
+    String array = "{\"a\":%s}";
+    String json = "true";
+    for (int i = 0; i < 40; i++) {
+      json = String.format(array, json);
+    }
+
+    JsonReader reader = new JsonReader(reader(json));
+    for (int i = 0; i < 40; i++) {
+      reader.beginObject();
+      assertEquals("a", reader.nextName());
+    }
+    assertEquals("$.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a"
+        + ".a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a", reader.getPath());
+    assertEquals(true, reader.nextBoolean());
+    for (int i = 0; i < 40; i++) {
+      reader.endObject();
+    }
+    assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+  }
+
+  // http://code.google.com/p/google-gson/issues/detail?id=409
+  public void testStringEndingInSlash() throws IOException {
+    JsonReader reader = new JsonReader(reader("/"));
+    reader.setLenient(true);
+    try {
+      reader.peek();
+      fail();
+    } catch (MalformedJsonException expected) {
+    }
+  }
+
+  public void testDocumentWithCommentEndingInSlash() throws IOException {
+    JsonReader reader = new JsonReader(reader("/* foo *//"));
+    reader.setLenient(true);
+    try {
+      reader.peek();
+      fail();
+    } catch (MalformedJsonException expected) {
+    }
+  }
+
+  public void testStringWithLeadingSlash() throws IOException {
+    JsonReader reader = new JsonReader(reader("/x"));
+    reader.setLenient(true);
+    try {
+      reader.peek();
+      fail();
+    } catch (MalformedJsonException expected) {
+    }
+  }
+
+  public void testUnterminatedObject() throws IOException {
+    JsonReader reader = new JsonReader(reader("{\"a\":\"android\"x"));
+    reader.setLenient(true);
+    reader.beginObject();
+    assertEquals("a", reader.nextName());
+    assertEquals("android", reader.nextString());
+    try {
+      reader.peek();
+      fail();
+    } catch (MalformedJsonException expected) {
+    }
+  }
+
+  public void testVeryLongQuotedString() throws IOException {
+    char[] stringChars = new char[1024 * 16];
+    Arrays.fill(stringChars, 'x');
+    String string = new String(stringChars);
+    String json = "[\"" + string + "\"]";
+    JsonReader reader = new JsonReader(reader(json));
+    reader.beginArray();
+    assertEquals(string, reader.nextString());
+    reader.endArray();
+  }
+
+  public void testVeryLongUnquotedString() throws IOException {
+    char[] stringChars = new char[1024 * 16];
+    Arrays.fill(stringChars, 'x');
+    String string = new String(stringChars);
+    String json = "[" + string + "]";
+    JsonReader reader = new JsonReader(reader(json));
+    reader.setLenient(true);
+    reader.beginArray();
+    assertEquals(string, reader.nextString());
+    reader.endArray();
+  }
+
+  public void testVeryLongUnterminatedString() throws IOException {
+    char[] stringChars = new char[1024 * 16];
+    Arrays.fill(stringChars, 'x');
+    String string = new String(stringChars);
+    String json = "[" + string;
+    JsonReader reader = new JsonReader(reader(json));
+    reader.setLenient(true);
+    reader.beginArray();
+    assertEquals(string, reader.nextString());
+    try {
+      reader.peek();
+      fail();
+    } catch (EOFException expected) {
+    }
+  }
+
+  public void testSkipVeryLongUnquotedString() throws IOException {
+    JsonReader reader = new JsonReader(reader("[" + repeat('x', 8192) + "]"));
+    reader.setLenient(true);
+    reader.beginArray();
+    reader.skipValue();
+    reader.endArray();
+  }
+
+  public void testSkipTopLevelUnquotedString() throws IOException {
+    JsonReader reader = new JsonReader(reader(repeat('x', 8192)));
+    reader.setLenient(true);
+    reader.skipValue();
+    assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+  }
+
+  public void testSkipVeryLongQuotedString() throws IOException {
+    JsonReader reader = new JsonReader(reader("[\"" + repeat('x', 8192) + "\"]"));
+    reader.beginArray();
+    reader.skipValue();
+    reader.endArray();
+  }
+
+  public void testSkipTopLevelQuotedString() throws IOException {
+    JsonReader reader = new JsonReader(reader("\"" + repeat('x', 8192) + "\""));
+    reader.setLenient(true);
+    reader.skipValue();
+    assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+  }
+
+  public void testStringAsNumberWithTruncatedExponent() throws IOException {
+    JsonReader reader = new JsonReader(reader("[123e]"));
+    reader.setLenient(true);
+    reader.beginArray();
+    assertEquals(STRING, reader.peek());
+  }
+
+  public void testStringAsNumberWithDigitAndNonDigitExponent() throws IOException {
+    JsonReader reader = new JsonReader(reader("[123e4b]"));
+    reader.setLenient(true);
+    reader.beginArray();
+    assertEquals(STRING, reader.peek());
+  }
+
+  public void testStringAsNumberWithNonDigitExponent() throws IOException {
+    JsonReader reader = new JsonReader(reader("[123eb]"));
+    reader.setLenient(true);
+    reader.beginArray();
+    assertEquals(STRING, reader.peek());
+  }
+
+  public void testEmptyStringName() throws IOException {
+    JsonReader reader = new JsonReader(reader("{\"\":true}"));
+    reader.setLenient(true);
+    assertEquals(BEGIN_OBJECT, reader.peek());
+    reader.beginObject();
+    assertEquals(NAME, reader.peek());
+    assertEquals("", reader.nextName());
+    assertEquals(JsonToken.BOOLEAN, reader.peek());
+    assertEquals(true, reader.nextBoolean());
+    assertEquals(JsonToken.END_OBJECT, reader.peek());
+    reader.endObject();
+    assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+  }
+
+  public void testStrictExtraCommasInMaps() throws IOException {
+    JsonReader reader = new JsonReader(reader("{\"a\":\"b\",}"));
+    reader.beginObject();
+    assertEquals("a", reader.nextName());
+    assertEquals("b", reader.nextString());
+    try {
+      reader.peek();
+      fail();
+    } catch (IOException expected) {
+    }
+  }
+
+  public void testLenientExtraCommasInMaps() throws IOException {
+    JsonReader reader = new JsonReader(reader("{\"a\":\"b\",}"));
+    reader.setLenient(true);
+    reader.beginObject();
+    assertEquals("a", reader.nextName());
+    assertEquals("b", reader.nextString());
+    try {
+      reader.peek();
+      fail();
+    } catch (IOException expected) {
+    }
+  }
+
+  private String repeat(char c, int count) {
+    char[] array = new char[count];
+    Arrays.fill(array, c);
+    return new String(array);
+  }
+
+  public void testMalformedDocuments() throws IOException {
+    assertDocument("{]", BEGIN_OBJECT, IOException.class);
+    assertDocument("{,", BEGIN_OBJECT, IOException.class);
+    assertDocument("{{", BEGIN_OBJECT, IOException.class);
+    assertDocument("{[", BEGIN_OBJECT, IOException.class);
+    assertDocument("{:", BEGIN_OBJECT, IOException.class);
+    assertDocument("{\"name\",", BEGIN_OBJECT, NAME, IOException.class);
+    assertDocument("{\"name\",", BEGIN_OBJECT, NAME, IOException.class);
+    assertDocument("{\"name\":}", BEGIN_OBJECT, NAME, IOException.class);
+    assertDocument("{\"name\"::", BEGIN_OBJECT, NAME, IOException.class);
+    assertDocument("{\"name\":,", BEGIN_OBJECT, NAME, IOException.class);
+    assertDocument("{\"name\"=}", BEGIN_OBJECT, NAME, IOException.class);
+    assertDocument("{\"name\"=>}", BEGIN_OBJECT, NAME, IOException.class);
+    assertDocument("{\"name\"=>\"string\":", BEGIN_OBJECT, NAME, STRING, IOException.class);
+    assertDocument("{\"name\"=>\"string\"=", BEGIN_OBJECT, NAME, STRING, IOException.class);
+    assertDocument("{\"name\"=>\"string\"=>", BEGIN_OBJECT, NAME, STRING, IOException.class);
+    assertDocument("{\"name\"=>\"string\",", BEGIN_OBJECT, NAME, STRING, IOException.class);
+    assertDocument("{\"name\"=>\"string\",\"name\"", BEGIN_OBJECT, NAME, STRING, NAME);
+    assertDocument("[}", BEGIN_ARRAY, IOException.class);
+    assertDocument("[,]", BEGIN_ARRAY, NULL, NULL, END_ARRAY);
+    assertDocument("{", BEGIN_OBJECT, IOException.class);
+    assertDocument("{\"name\"", BEGIN_OBJECT, NAME, IOException.class);
+    assertDocument("{\"name\",", BEGIN_OBJECT, NAME, IOException.class);
+    assertDocument("{'name'", BEGIN_OBJECT, NAME, IOException.class);
+    assertDocument("{'name',", BEGIN_OBJECT, NAME, IOException.class);
+    assertDocument("{name", BEGIN_OBJECT, NAME, IOException.class);
+    assertDocument("[", BEGIN_ARRAY, IOException.class);
+    assertDocument("[string", BEGIN_ARRAY, STRING, IOException.class);
+    assertDocument("[\"string\"", BEGIN_ARRAY, STRING, IOException.class);
+    assertDocument("['string'", BEGIN_ARRAY, STRING, IOException.class);
+    assertDocument("[123", BEGIN_ARRAY, NUMBER, IOException.class);
+    assertDocument("[123,", BEGIN_ARRAY, NUMBER, IOException.class);
+    assertDocument("{\"name\":123", BEGIN_OBJECT, NAME, NUMBER, IOException.class);
+    assertDocument("{\"name\":123,", BEGIN_OBJECT, NAME, NUMBER, IOException.class);
+    assertDocument("{\"name\":\"string\"", BEGIN_OBJECT, NAME, STRING, IOException.class);
+    assertDocument("{\"name\":\"string\",", BEGIN_OBJECT, NAME, STRING, IOException.class);
+    assertDocument("{\"name\":'string'", BEGIN_OBJECT, NAME, STRING, IOException.class);
+    assertDocument("{\"name\":'string',", BEGIN_OBJECT, NAME, STRING, IOException.class);
+    assertDocument("{\"name\":false", BEGIN_OBJECT, NAME, BOOLEAN, IOException.class);
+    assertDocument("{\"name\":false,,", BEGIN_OBJECT, NAME, BOOLEAN, IOException.class);
+  }
+
+  /**
+   * This test behave slightly differently in Gson 2.2 and earlier. It fails
+   * during peek rather than during nextString().
+   */
+  public void testUnterminatedStringFailure() throws IOException {
+    JsonReader reader = new JsonReader(reader("[\"string"));
+    reader.setLenient(true);
+    reader.beginArray();
+    assertEquals(JsonToken.STRING, reader.peek());
+    try {
+      reader.nextString();
+      fail();
+    } catch (MalformedJsonException expected) {
+    }
+  }
+
+  /**
+   * Regression test for an issue with buffer filling and consumeNonExecutePrefix.
+   */
+  public void testReadAcrossBuffers() throws IOException {
+    StringBuilder sb = new StringBuilder("#");
+    for (int i = 0; i < JsonReader.BUFFER_SIZE - 3; i++) {
+      sb.append(' ');
+    }
+    sb.append("\n)]}'\n3");
+    JsonReader reader = new JsonReader(reader(sb.toString()));
+    reader.setLenient(true);
+    JsonToken token = reader.peek();
+    assertEquals(JsonToken.NUMBER, token);
+  }
+
+  private void assertDocument(String document, Object... expectations) throws IOException {
+    JsonReader reader = new JsonReader(reader(document));
+    reader.setLenient(true);
+    for (Object expectation : expectations) {
+      if (expectation == BEGIN_OBJECT) {
+        reader.beginObject();
+      } else if (expectation == BEGIN_ARRAY) {
+        reader.beginArray();
+      } else if (expectation == END_OBJECT) {
+        reader.endObject();
+      } else if (expectation == END_ARRAY) {
+        reader.endArray();
+      } else if (expectation == NAME) {
+        assertEquals("name", reader.nextName());
+      } else if (expectation == BOOLEAN) {
+        assertEquals(false, reader.nextBoolean());
+      } else if (expectation == STRING) {
+        assertEquals("string", reader.nextString());
+      } else if (expectation == NUMBER) {
+        assertEquals(123, reader.nextInt());
+      } else if (expectation == NULL) {
+        reader.nextNull();
+      } else if (expectation == IOException.class) {
+        try {
+          reader.peek();
+          fail();
+        } catch (IOException expected) {
+        }
+      } else {
+        throw new AssertionError();
+      }
+    }
+  }
+
+  /**
+   * Returns a reader that returns one character at a time.
+   */
+  private Reader reader(final String s) {
+    /* if (true) */ return new StringReader(s);
+    /* return new Reader() {
+      int position = 0;
+      @Override public int read(char[] buffer, int offset, int count) throws IOException {
+        if (position == s.length()) {
+          return -1;
+        } else if (count > 0) {
+          buffer[offset] = s.charAt(position++);
+          return 1;
+        } else {
+          throw new IllegalArgumentException();
+        }
+      }
+      @Override public void close() throws IOException {
+      }
+    }; */
+  }
+}
diff --git a/gson/src/test/java/com/google/gson/stream/JsonWriterTest.java b/gson/src/test/java/com/google/gson/stream/JsonWriterTest.java
new file mode 100644
index 0000000..5c57fd1
--- /dev/null
+++ b/gson/src/test/java/com/google/gson/stream/JsonWriterTest.java
@@ -0,0 +1,802 @@
+/*
+ * Copyright (C) 2010 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.stream;
+
+import com.google.gson.internal.LazilyParsedNumber;
+import java.io.IOException;
+import java.io.StringWriter;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import junit.framework.TestCase;
+
+@SuppressWarnings("resource")
+public final class JsonWriterTest extends TestCase {
+
+  public void testTopLevelValueTypes() throws IOException {
+    StringWriter string1 = new StringWriter();
+    JsonWriter writer1 = new JsonWriter(string1);
+    writer1.value(true);
+    writer1.close();
+    assertEquals("true", string1.toString());
+
+    StringWriter string2 = new StringWriter();
+    JsonWriter writer2 = new JsonWriter(string2);
+    writer2.nullValue();
+    writer2.close();
+    assertEquals("null", string2.toString());
+
+    StringWriter string3 = new StringWriter();
+    JsonWriter writer3 = new JsonWriter(string3);
+    writer3.value(123);
+    writer3.close();
+    assertEquals("123", string3.toString());
+
+    StringWriter string4 = new StringWriter();
+    JsonWriter writer4 = new JsonWriter(string4);
+    writer4.value(123.4);
+    writer4.close();
+    assertEquals("123.4", string4.toString());
+
+    StringWriter string5 = new StringWriter();
+    JsonWriter writert = new JsonWriter(string5);
+    writert.value("a");
+    writert.close();
+    assertEquals("\"a\"", string5.toString());
+  }
+
+  public void testInvalidTopLevelTypes() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter jsonWriter = new JsonWriter(stringWriter);
+    jsonWriter.name("hello");
+    try {
+      jsonWriter.value("world");
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+  }
+
+  public void testTwoNames() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter jsonWriter = new JsonWriter(stringWriter);
+    jsonWriter.beginObject();
+    jsonWriter.name("a");
+    try {
+      jsonWriter.name("a");
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+  }
+
+  public void testNameWithoutValue() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter jsonWriter = new JsonWriter(stringWriter);
+    jsonWriter.beginObject();
+    jsonWriter.name("a");
+    try {
+      jsonWriter.endObject();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+  }
+
+  public void testValueWithoutName() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter jsonWriter = new JsonWriter(stringWriter);
+    jsonWriter.beginObject();
+    try {
+      jsonWriter.value(true);
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+  }
+
+  public void testMultipleTopLevelValues() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter jsonWriter = new JsonWriter(stringWriter);
+    jsonWriter.beginArray().endArray();
+    try {
+      jsonWriter.beginArray();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+  }
+
+  public void testBadNestingObject() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter jsonWriter = new JsonWriter(stringWriter);
+    jsonWriter.beginArray();
+    jsonWriter.beginObject();
+    try {
+      jsonWriter.endArray();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+  }
+
+  public void testBadNestingArray() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter jsonWriter = new JsonWriter(stringWriter);
+    jsonWriter.beginArray();
+    jsonWriter.beginArray();
+    try {
+      jsonWriter.endObject();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+  }
+
+  public void testNullName() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter jsonWriter = new JsonWriter(stringWriter);
+    jsonWriter.beginObject();
+    try {
+      jsonWriter.name(null);
+      fail();
+    } catch (NullPointerException expected) {
+    }
+  }
+
+  public void testNullStringValue() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter jsonWriter = new JsonWriter(stringWriter);
+    jsonWriter.beginObject();
+    jsonWriter.name("a");
+    jsonWriter.value((String) null);
+    jsonWriter.endObject();
+    assertEquals("{\"a\":null}", stringWriter.toString());
+  }
+
+  public void testJsonValue() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter jsonWriter = new JsonWriter(stringWriter);
+    jsonWriter.beginObject();
+    jsonWriter.name("a");
+    jsonWriter.jsonValue("{\"b\":true}");
+    jsonWriter.name("c");
+    jsonWriter.value(1);
+    jsonWriter.endObject();
+    assertEquals("{\"a\":{\"b\":true},\"c\":1}", stringWriter.toString());
+  }
+
+  public void testNonFiniteFloats() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter jsonWriter = new JsonWriter(stringWriter);
+    jsonWriter.beginArray();
+    try {
+      jsonWriter.value(Float.NaN);
+      fail();
+    } catch (IllegalArgumentException expected) {
+      assertEquals("Numeric values must be finite, but was NaN", expected.getMessage());
+    }
+    try {
+      jsonWriter.value(Float.NEGATIVE_INFINITY);
+      fail();
+    } catch (IllegalArgumentException expected) {
+      assertEquals("Numeric values must be finite, but was -Infinity", expected.getMessage());
+    }
+    try {
+      jsonWriter.value(Float.POSITIVE_INFINITY);
+      fail();
+    } catch (IllegalArgumentException expected) {
+      assertEquals("Numeric values must be finite, but was Infinity", expected.getMessage());
+    }
+  }
+
+  public void testNonFiniteDoubles() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter jsonWriter = new JsonWriter(stringWriter);
+    jsonWriter.beginArray();
+    try {
+      jsonWriter.value(Double.NaN);
+      fail();
+    } catch (IllegalArgumentException expected) {
+      assertEquals("Numeric values must be finite, but was NaN", expected.getMessage());
+    }
+    try {
+      jsonWriter.value(Double.NEGATIVE_INFINITY);
+      fail();
+    } catch (IllegalArgumentException expected) {
+      assertEquals("Numeric values must be finite, but was -Infinity", expected.getMessage());
+    }
+    try {
+      jsonWriter.value(Double.POSITIVE_INFINITY);
+      fail();
+    } catch (IllegalArgumentException expected) {
+      assertEquals("Numeric values must be finite, but was Infinity", expected.getMessage());
+    }
+  }
+
+  public void testNonFiniteNumbers() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter jsonWriter = new JsonWriter(stringWriter);
+    jsonWriter.beginArray();
+    try {
+      jsonWriter.value(Double.valueOf(Double.NaN));
+      fail();
+    } catch (IllegalArgumentException expected) {
+      assertEquals("Numeric values must be finite, but was NaN", expected.getMessage());
+    }
+    try {
+      jsonWriter.value(Double.valueOf(Double.NEGATIVE_INFINITY));
+      fail();
+    } catch (IllegalArgumentException expected) {
+      assertEquals("Numeric values must be finite, but was -Infinity", expected.getMessage());
+    }
+    try {
+      jsonWriter.value(Double.valueOf(Double.POSITIVE_INFINITY));
+      fail();
+    } catch (IllegalArgumentException expected) {
+      assertEquals("Numeric values must be finite, but was Infinity", expected.getMessage());
+    }
+    try {
+      jsonWriter.value(new LazilyParsedNumber("Infinity"));
+      fail();
+    } catch (IllegalArgumentException expected) {
+      assertEquals("Numeric values must be finite, but was Infinity", expected.getMessage());
+    }
+  }
+
+  public void testNonFiniteFloatsWhenLenient() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter jsonWriter = new JsonWriter(stringWriter);
+    jsonWriter.setLenient(true);
+    jsonWriter.beginArray();
+    jsonWriter.value(Float.NaN);
+    jsonWriter.value(Float.NEGATIVE_INFINITY);
+    jsonWriter.value(Float.POSITIVE_INFINITY);
+    jsonWriter.endArray();
+    assertEquals("[NaN,-Infinity,Infinity]", stringWriter.toString());
+  }
+
+  public void testNonFiniteDoublesWhenLenient() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter jsonWriter = new JsonWriter(stringWriter);
+    jsonWriter.setLenient(true);
+    jsonWriter.beginArray();
+    jsonWriter.value(Double.NaN);
+    jsonWriter.value(Double.NEGATIVE_INFINITY);
+    jsonWriter.value(Double.POSITIVE_INFINITY);
+    jsonWriter.endArray();
+    assertEquals("[NaN,-Infinity,Infinity]", stringWriter.toString());
+  }
+
+  public void testNonFiniteNumbersWhenLenient() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter jsonWriter = new JsonWriter(stringWriter);
+    jsonWriter.setLenient(true);
+    jsonWriter.beginArray();
+    jsonWriter.value(Double.valueOf(Double.NaN));
+    jsonWriter.value(Double.valueOf(Double.NEGATIVE_INFINITY));
+    jsonWriter.value(Double.valueOf(Double.POSITIVE_INFINITY));
+    jsonWriter.value(new LazilyParsedNumber("Infinity"));
+    jsonWriter.endArray();
+    assertEquals("[NaN,-Infinity,Infinity,Infinity]", stringWriter.toString());
+  }
+
+  public void testFloats() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter jsonWriter = new JsonWriter(stringWriter);
+    jsonWriter.beginArray();
+    jsonWriter.value(-0.0f);
+    jsonWriter.value(1.0f);
+    jsonWriter.value(Float.MAX_VALUE);
+    jsonWriter.value(Float.MIN_VALUE);
+    jsonWriter.value(0.0f);
+    jsonWriter.value(-0.5f);
+    jsonWriter.value(2.2250739E-38f);
+    jsonWriter.value(3.723379f);
+    jsonWriter.value((float) Math.PI);
+    jsonWriter.value((float) Math.E);
+    jsonWriter.endArray();
+    jsonWriter.close();
+    assertEquals(
+        "[-0.0,"
+            + "1.0,"
+            + "3.4028235E38,"
+            + "1.4E-45,"
+            + "0.0,"
+            + "-0.5,"
+            + "2.2250739E-38,"
+            + "3.723379,"
+            + "3.1415927,"
+            + "2.7182817]",
+        stringWriter.toString());
+  }
+
+  public void testDoubles() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter jsonWriter = new JsonWriter(stringWriter);
+    jsonWriter.beginArray();
+    jsonWriter.value(-0.0);
+    jsonWriter.value(1.0);
+    jsonWriter.value(Double.MAX_VALUE);
+    jsonWriter.value(Double.MIN_VALUE);
+    jsonWriter.value(0.0);
+    jsonWriter.value(-0.5);
+    jsonWriter.value(2.2250738585072014E-308);
+    jsonWriter.value(Math.PI);
+    jsonWriter.value(Math.E);
+    jsonWriter.endArray();
+    jsonWriter.close();
+    assertEquals("[-0.0,"
+        + "1.0,"
+        + "1.7976931348623157E308,"
+        + "4.9E-324,"
+        + "0.0,"
+        + "-0.5,"
+        + "2.2250738585072014E-308,"
+        + "3.141592653589793,"
+        + "2.718281828459045]", stringWriter.toString());
+  }
+
+  public void testLongs() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter jsonWriter = new JsonWriter(stringWriter);
+    jsonWriter.beginArray();
+    jsonWriter.value(0);
+    jsonWriter.value(1);
+    jsonWriter.value(-1);
+    jsonWriter.value(Long.MIN_VALUE);
+    jsonWriter.value(Long.MAX_VALUE);
+    jsonWriter.endArray();
+    jsonWriter.close();
+    assertEquals("[0,"
+        + "1,"
+        + "-1,"
+        + "-9223372036854775808,"
+        + "9223372036854775807]", stringWriter.toString());
+  }
+
+  public void testNumbers() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter jsonWriter = new JsonWriter(stringWriter);
+    jsonWriter.beginArray();
+    jsonWriter.value(new BigInteger("0"));
+    jsonWriter.value(new BigInteger("9223372036854775808"));
+    jsonWriter.value(new BigInteger("-9223372036854775809"));
+    jsonWriter.value(new BigDecimal("3.141592653589793238462643383"));
+    jsonWriter.endArray();
+    jsonWriter.close();
+    assertEquals("[0,"
+        + "9223372036854775808,"
+        + "-9223372036854775809,"
+        + "3.141592653589793238462643383]", stringWriter.toString());
+  }
+
+  /**
+   * Tests writing {@code Number} instances which are not one of the standard JDK ones.
+   */
+  public void testNumbersCustomClass() throws IOException {
+    String[] validNumbers = {
+        "-0.0",
+        "1.0",
+        "1.7976931348623157E308",
+        "4.9E-324",
+        "0.0",
+        "0.00",
+        "-0.5",
+        "2.2250738585072014E-308",
+        "3.141592653589793",
+        "2.718281828459045",
+        "0",
+        "0.01",
+        "0e0",
+        "1e+0",
+        "1e-0",
+        "1e0000", // leading 0 is allowed for exponent
+        "1e00001",
+        "1e+1",
+    };
+
+    for (String validNumber : validNumbers) {
+      StringWriter stringWriter = new StringWriter();
+      JsonWriter jsonWriter = new JsonWriter(stringWriter);
+
+      jsonWriter.value(new LazilyParsedNumber(validNumber));
+      jsonWriter.close();
+
+      assertEquals(validNumber, stringWriter.toString());
+    }
+  }
+
+  public void testMalformedNumbers() throws IOException {
+    String[] malformedNumbers = {
+        "some text",
+        "",
+        ".",
+        "00",
+        "01",
+        "-00",
+        "-",
+        "--1",
+        "+1", // plus sign is not allowed for integer part
+        "+",
+        "1,0",
+        "1,000",
+        "0.", // decimal digit is required
+        ".1", // integer part is required
+        "e1",
+        ".e1",
+        ".1e1",
+        "1e-",
+        "1e+",
+        "1e--1",
+        "1e+-1",
+        "1e1e1",
+        "1+e1",
+        "1e1.0",
+    };
+
+    for (String malformedNumber : malformedNumbers) {
+      JsonWriter jsonWriter = new JsonWriter(new StringWriter());
+      try {
+        jsonWriter.value(new LazilyParsedNumber(malformedNumber));
+        fail("Should have failed writing malformed number: " + malformedNumber);
+      } catch (IllegalArgumentException e) {
+        assertEquals("String created by class com.google.gson.internal.LazilyParsedNumber is not a valid JSON number: " + malformedNumber, e.getMessage());
+      }
+    }
+  }
+
+  public void testBooleans() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter jsonWriter = new JsonWriter(stringWriter);
+    jsonWriter.beginArray();
+    jsonWriter.value(true);
+    jsonWriter.value(false);
+    jsonWriter.endArray();
+    assertEquals("[true,false]", stringWriter.toString());
+  }
+
+  public void testBoxedBooleans() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter jsonWriter = new JsonWriter(stringWriter);
+    jsonWriter.beginArray();
+    jsonWriter.value((Boolean) true);
+    jsonWriter.value((Boolean) false);
+    jsonWriter.value((Boolean) null);
+    jsonWriter.endArray();
+    assertEquals("[true,false,null]", stringWriter.toString());
+  }
+
+  public void testNulls() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter jsonWriter = new JsonWriter(stringWriter);
+    jsonWriter.beginArray();
+    jsonWriter.nullValue();
+    jsonWriter.endArray();
+    assertEquals("[null]", stringWriter.toString());
+  }
+
+  public void testStrings() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter jsonWriter = new JsonWriter(stringWriter);
+    jsonWriter.beginArray();
+    jsonWriter.value("a");
+    jsonWriter.value("a\"");
+    jsonWriter.value("\"");
+    jsonWriter.value(":");
+    jsonWriter.value(",");
+    jsonWriter.value("\b");
+    jsonWriter.value("\f");
+    jsonWriter.value("\n");
+    jsonWriter.value("\r");
+    jsonWriter.value("\t");
+    jsonWriter.value(" ");
+    jsonWriter.value("\\");
+    jsonWriter.value("{");
+    jsonWriter.value("}");
+    jsonWriter.value("[");
+    jsonWriter.value("]");
+    jsonWriter.value("\0");
+    jsonWriter.value("\u0019");
+    jsonWriter.endArray();
+    assertEquals("[\"a\","
+        + "\"a\\\"\","
+        + "\"\\\"\","
+        + "\":\","
+        + "\",\","
+        + "\"\\b\","
+        + "\"\\f\","
+        + "\"\\n\","
+        + "\"\\r\","
+        + "\"\\t\","
+        + "\" \","
+        + "\"\\\\\","
+        + "\"{\","
+        + "\"}\","
+        + "\"[\","
+        + "\"]\","
+        + "\"\\u0000\","
+        + "\"\\u0019\"]", stringWriter.toString());
+  }
+
+  public void testUnicodeLineBreaksEscaped() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter jsonWriter = new JsonWriter(stringWriter);
+    jsonWriter.beginArray();
+    jsonWriter.value("\u2028 \u2029");
+    jsonWriter.endArray();
+    assertEquals("[\"\\u2028 \\u2029\"]", stringWriter.toString());
+  }
+
+  public void testEmptyArray() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter jsonWriter = new JsonWriter(stringWriter);
+    jsonWriter.beginArray();
+    jsonWriter.endArray();
+    assertEquals("[]", stringWriter.toString());
+  }
+
+  public void testEmptyObject() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter jsonWriter = new JsonWriter(stringWriter);
+    jsonWriter.beginObject();
+    jsonWriter.endObject();
+    assertEquals("{}", stringWriter.toString());
+  }
+
+  public void testObjectsInArrays() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter jsonWriter = new JsonWriter(stringWriter);
+    jsonWriter.beginArray();
+    jsonWriter.beginObject();
+    jsonWriter.name("a").value(5);
+    jsonWriter.name("b").value(false);
+    jsonWriter.endObject();
+    jsonWriter.beginObject();
+    jsonWriter.name("c").value(6);
+    jsonWriter.name("d").value(true);
+    jsonWriter.endObject();
+    jsonWriter.endArray();
+    assertEquals("[{\"a\":5,\"b\":false},"
+        + "{\"c\":6,\"d\":true}]", stringWriter.toString());
+  }
+
+  public void testArraysInObjects() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter jsonWriter = new JsonWriter(stringWriter);
+    jsonWriter.beginObject();
+    jsonWriter.name("a");
+    jsonWriter.beginArray();
+    jsonWriter.value(5);
+    jsonWriter.value(false);
+    jsonWriter.endArray();
+    jsonWriter.name("b");
+    jsonWriter.beginArray();
+    jsonWriter.value(6);
+    jsonWriter.value(true);
+    jsonWriter.endArray();
+    jsonWriter.endObject();
+    assertEquals("{\"a\":[5,false],"
+        + "\"b\":[6,true]}", stringWriter.toString());
+  }
+
+  public void testDeepNestingArrays() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter jsonWriter = new JsonWriter(stringWriter);
+    for (int i = 0; i < 20; i++) {
+      jsonWriter.beginArray();
+    }
+    for (int i = 0; i < 20; i++) {
+      jsonWriter.endArray();
+    }
+    assertEquals("[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]", stringWriter.toString());
+  }
+
+  public void testDeepNestingObjects() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter jsonWriter = new JsonWriter(stringWriter);
+    jsonWriter.beginObject();
+    for (int i = 0; i < 20; i++) {
+      jsonWriter.name("a");
+      jsonWriter.beginObject();
+    }
+    for (int i = 0; i < 20; i++) {
+      jsonWriter.endObject();
+    }
+    jsonWriter.endObject();
+    assertEquals("{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":"
+        + "{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{"
+        + "}}}}}}}}}}}}}}}}}}}}}", stringWriter.toString());
+  }
+
+  public void testRepeatedName() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter jsonWriter = new JsonWriter(stringWriter);
+    jsonWriter.beginObject();
+    jsonWriter.name("a").value(true);
+    jsonWriter.name("a").value(false);
+    jsonWriter.endObject();
+    // JsonWriter doesn't attempt to detect duplicate names
+    assertEquals("{\"a\":true,\"a\":false}", stringWriter.toString());
+  }
+
+  public void testPrettyPrintObject() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter jsonWriter = new JsonWriter(stringWriter);
+    jsonWriter.setIndent("   ");
+
+    jsonWriter.beginObject();
+    jsonWriter.name("a").value(true);
+    jsonWriter.name("b").value(false);
+    jsonWriter.name("c").value(5.0);
+    jsonWriter.name("e").nullValue();
+    jsonWriter.name("f").beginArray();
+    jsonWriter.value(6.0);
+    jsonWriter.value(7.0);
+    jsonWriter.endArray();
+    jsonWriter.name("g").beginObject();
+    jsonWriter.name("h").value(8.0);
+    jsonWriter.name("i").value(9.0);
+    jsonWriter.endObject();
+    jsonWriter.endObject();
+
+    String expected = "{\n"
+        + "   \"a\": true,\n"
+        + "   \"b\": false,\n"
+        + "   \"c\": 5.0,\n"
+        + "   \"e\": null,\n"
+        + "   \"f\": [\n"
+        + "      6.0,\n"
+        + "      7.0\n"
+        + "   ],\n"
+        + "   \"g\": {\n"
+        + "      \"h\": 8.0,\n"
+        + "      \"i\": 9.0\n"
+        + "   }\n"
+        + "}";
+    assertEquals(expected, stringWriter.toString());
+  }
+
+  public void testPrettyPrintArray() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter jsonWriter = new JsonWriter(stringWriter);
+    jsonWriter.setIndent("   ");
+
+    jsonWriter.beginArray();
+    jsonWriter.value(true);
+    jsonWriter.value(false);
+    jsonWriter.value(5.0);
+    jsonWriter.nullValue();
+    jsonWriter.beginObject();
+    jsonWriter.name("a").value(6.0);
+    jsonWriter.name("b").value(7.0);
+    jsonWriter.endObject();
+    jsonWriter.beginArray();
+    jsonWriter.value(8.0);
+    jsonWriter.value(9.0);
+    jsonWriter.endArray();
+    jsonWriter.endArray();
+
+    String expected = "[\n"
+        + "   true,\n"
+        + "   false,\n"
+        + "   5.0,\n"
+        + "   null,\n"
+        + "   {\n"
+        + "      \"a\": 6.0,\n"
+        + "      \"b\": 7.0\n"
+        + "   },\n"
+        + "   [\n"
+        + "      8.0,\n"
+        + "      9.0\n"
+        + "   ]\n"
+        + "]";
+    assertEquals(expected, stringWriter.toString());
+  }
+
+  public void testLenientWriterPermitsMultipleTopLevelValues() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter writer = new JsonWriter(stringWriter);
+    writer.setLenient(true);
+    writer.beginArray();
+    writer.endArray();
+    writer.beginArray();
+    writer.endArray();
+    writer.close();
+    assertEquals("[][]", stringWriter.toString());
+  }
+
+  public void testStrictWriterDoesNotPermitMultipleTopLevelValues() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter writer = new JsonWriter(stringWriter);
+    writer.beginArray();
+    writer.endArray();
+    try {
+      writer.beginArray();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+  }
+
+  public void testClosedWriterThrowsOnStructure() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter writer = new JsonWriter(stringWriter);
+    writer.beginArray();
+    writer.endArray();
+    writer.close();
+    try {
+      writer.beginArray();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+    try {
+      writer.endArray();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+    try {
+      writer.beginObject();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+    try {
+      writer.endObject();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+  }
+
+  public void testClosedWriterThrowsOnName() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter writer = new JsonWriter(stringWriter);
+    writer.beginArray();
+    writer.endArray();
+    writer.close();
+    try {
+      writer.name("a");
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+  }
+
+  public void testClosedWriterThrowsOnValue() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter writer = new JsonWriter(stringWriter);
+    writer.beginArray();
+    writer.endArray();
+    writer.close();
+    try {
+      writer.value("a");
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+  }
+
+  public void testClosedWriterThrowsOnFlush() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter writer = new JsonWriter(stringWriter);
+    writer.beginArray();
+    writer.endArray();
+    writer.close();
+    try {
+      writer.flush();
+      fail();
+    } catch (IllegalStateException expected) {
+    }
+  }
+
+  public void testWriterCloseIsIdempotent() throws IOException {
+    StringWriter stringWriter = new StringWriter();
+    JsonWriter writer = new JsonWriter(stringWriter);
+    writer.beginArray();
+    writer.endArray();
+    writer.close();
+    writer.close();
+  }
+}
diff --git a/gson/src/test/resources/testcases-proguard.conf b/gson/src/test/resources/testcases-proguard.conf
new file mode 100644
index 0000000..19def61
--- /dev/null
+++ b/gson/src/test/resources/testcases-proguard.conf
@@ -0,0 +1,23 @@
+# Options from Android Gradle Plugins
+# https://android.googlesource.com/platform/tools/base/+/refs/heads/studio-master-dev/build-system/gradle-core/src/main/resources/com/android/build/gradle
+-optimizations !code/simplification/arithmetic,!code/simplification/cast,!field/*,!class/merging/*
+-optimizationpasses 5
+-allowaccessmodification
+# On Windows mixed case class names might cause problems
+-dontusemixedcaseclassnames
+-keepattributes *Annotation*,Signature,InnerClasses,EnclosingMethod
+-keepclassmembers enum * {
+  public static **[] values();
+  public static ** valueOf(java.lang.String);
+}
+
+-keep enum com.google.gson.functional.EnumWithObfuscatedTest$Gender
+-keep class com.google.gson.functional.EnumWithObfuscatedTest {
+  public void test*();
+  protected void setUp();
+}
+
+-dontwarn com.google.gson.functional.EnumWithObfuscatedTest
+-dontwarn junit.framework.TestCase
+# Ignore notes about duplicate JDK classes
+-dontnote module-info,jdk.internal.**
diff --git a/lib/gson-cleanup-styles.xml b/lib/gson-cleanup-styles.xml
new file mode 100644
index 0000000..9e20cb9
--- /dev/null
+++ b/lib/gson-cleanup-styles.xml
@@ -0,0 +1,51 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>

+<profiles version="2">

+<profile kind="CleanUpProfile" name="Gson" version="2">

+<setting id="cleanup.add_missing_nls_tags" value="false"/>

+<setting id="cleanup.format_source_code" value="false"/>

+<setting id="cleanup.add_missing_override_annotations" value="true"/>

+<setting id="cleanup.qualify_static_method_accesses_with_declaring_class" value="false"/>

+<setting id="cleanup.remove_unused_private_types" value="true"/>

+<setting id="cleanup.remove_unused_private_fields" value="true"/>

+<setting id="cleanup.always_use_parentheses_in_expressions" value="false"/>

+<setting id="cleanup.never_use_blocks" value="false"/>

+<setting id="cleanup.make_local_variable_final" value="true"/>

+<setting id="cleanup.add_missing_deprecated_annotations" value="true"/>

+<setting id="cleanup.remove_unused_private_methods" value="true"/>

+<setting id="cleanup.convert_to_enhanced_for_loop" value="true"/>

+<setting id="cleanup.remove_unnecessary_nls_tags" value="true"/>

+<setting id="cleanup.remove_unused_imports" value="true"/>

+<setting id="cleanup.remove_trailing_whitespaces_ignore_empty" value="false"/>

+<setting id="cleanup.make_private_fields_final" value="true"/>

+<setting id="cleanup.sort_members" value="false"/>

+<setting id="cleanup.add_generated_serial_version_id" value="false"/>

+<setting id="cleanup.remove_unused_local_variables" value="true"/>

+<setting id="cleanup.organize_imports" value="false"/>

+<setting id="cleanup.remove_unused_private_members" value="false"/>

+<setting id="cleanup.remove_trailing_whitespaces" value="true"/>

+<setting id="cleanup.never_use_parentheses_in_expressions" value="true"/>

+<setting id="cleanup.sort_members_all" value="false"/>

+<setting id="cleanup.remove_unnecessary_casts" value="true"/>

+<setting id="cleanup.make_parameters_final" value="false"/>

+<setting id="cleanup.use_blocks_only_for_return_and_throw" value="false"/>

+<setting id="cleanup.use_this_for_non_static_field_access" value="false"/>

+<setting id="cleanup.remove_private_constructors" value="true"/>

+<setting id="cleanup.use_blocks" value="false"/>

+<setting id="cleanup.add_missing_annotations" value="true"/>

+<setting id="cleanup.always_use_this_for_non_static_method_access" value="false"/>

+<setting id="cleanup.use_parentheses_in_expressions" value="false"/>

+<setting id="cleanup.remove_trailing_whitespaces_all" value="true"/>

+<setting id="cleanup.always_use_this_for_non_static_field_access" value="false"/>

+<setting id="cleanup.use_this_for_non_static_field_access_only_if_necessary" value="true"/>

+<setting id="cleanup.qualify_static_field_accesses_with_declaring_class" value="false"/>

+<setting id="cleanup.add_default_serial_version_id" value="true"/>

+<setting id="cleanup.use_this_for_non_static_method_access_only_if_necessary" value="true"/>

+<setting id="cleanup.use_this_for_non_static_method_access" value="false"/>

+<setting id="cleanup.qualify_static_member_accesses_through_instances_with_declaring_class" value="true"/>

+<setting id="cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class" value="true"/>

+<setting id="cleanup.add_serial_version_id" value="false"/>

+<setting id="cleanup.make_variable_declarations_final" value="false"/>

+<setting id="cleanup.always_use_blocks" value="true"/>

+<setting id="cleanup.qualify_static_member_accesses_with_declaring_class" value="true"/>

+</profile>

+</profiles>

diff --git a/lib/gson-formatting-styles.xml b/lib/gson-formatting-styles.xml
new file mode 100644
index 0000000..177e999
--- /dev/null
+++ b/lib/gson-formatting-styles.xml
@@ -0,0 +1,267 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<profiles version="11">
+<profile kind="CodeFormatterProfile" name="Gson" version="11">
+<setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_field" value="0"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_ellipsis" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_multiple_fields" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_conditional_expression" value="80"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_binary_operator" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_array_initializer" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_after_package" value="1"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.continuation_indentation" value="2"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk" value="1"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_binary_operator" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_package" value="0"/>
+<setting id="org.eclipse.jdt.core.compiler.source" value="1.5"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.format_line_comments" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_member_type" value="1"/>
+<setting id="org.eclipse.jdt.core.formatter.align_type_members_on_columns" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_unary_operator" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.indent_parameter_description" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.lineSplit" value="100"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration" value="0"/>
+<setting id="org.eclipse.jdt.core.formatter.indentation.size" value="4"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_assignment" value="16"/>
+<setting id="org.eclipse.jdt.core.compiler.problem.assertIdentifier" value="error"/>
+<setting id="org.eclipse.jdt.core.formatter.tabulation.char" value="space"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_body" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_method" value="1"/>
+<setting id="org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_switch" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.compiler.problem.enumIdentifier" value="error"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_ellipsis" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_block" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_method_declaration" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.compact_else_if" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_enum_constant" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.indent_root_tags" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.tabulation.size" value="2"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_empty_lines" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_block_in_case" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve" value="1"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression" value="16"/>
+<setting id="org.eclipse.jdt.core.compiler.compliance" value="1.5"/>
+<setting id="org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer" value="2"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_unary_operator" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_binary_expression" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode" value="enabled"/>
+<setting id="org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.format_javadoc_comments" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.line_length" value="80"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_between_import_groups" value="1"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body" value="0"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.wrap_before_binary_operator" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations" value="1"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_block" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_compact_if" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_imports" value="1"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.format_html" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.format_source_code" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer" value="insert"/>
+<setting id="org.eclipse.jdt.core.compiler.codegen.targetPlatform" value="1.5"/>
+<setting id="org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_member" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.format_header" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.format_block_comments" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_enum_constants" value="0"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_type_declaration" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_after_imports" value="1"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line" value="false"/>
+</profile>
+</profiles>
diff --git a/metrics/README.md b/metrics/README.md
new file mode 100644
index 0000000..8c95485
--- /dev/null
+++ b/metrics/README.md
@@ -0,0 +1,3 @@
+# metrics
+
+This Maven module contains the source code for running internal benchmark tests against Gson.
diff --git a/metrics/pom.xml b/metrics/pom.xml
new file mode 100644
index 0000000..9073e96
--- /dev/null
+++ b/metrics/pom.xml
@@ -0,0 +1,74 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+  <modelVersion>4.0.0</modelVersion>
+  <parent>
+    <groupId>com.google.code.gson</groupId>
+    <artifactId>gson-parent</artifactId>
+    <version>2.9.1</version>
+  </parent>
+
+  <artifactId>gson-metrics</artifactId>
+  <inceptionYear>2011</inceptionYear>
+  <name>Gson Metrics</name>
+  <description>Performance Metrics for Google Gson library</description>
+
+  <licenses>
+    <license>
+      <name>Apache-2.0</name>
+      <url>https://www.apache.org/licenses/LICENSE-2.0.txt</url>
+    </license>
+  </licenses>
+
+  <organization>
+    <name>Google, Inc.</name>
+    <url>https://www.google.com</url>
+  </organization>
+
+  <dependencies>
+    <dependency>
+      <groupId>com.google.code.gson</groupId>
+      <artifactId>gson</artifactId>
+      <version>${project.parent.version}</version>
+    </dependency>
+    <dependency>
+      <groupId>com.fasterxml.jackson.core</groupId>
+      <artifactId>jackson-databind</artifactId>
+      <version>2.13.3</version>
+    </dependency>
+    <dependency>
+      <groupId>com.google.caliper</groupId>
+      <artifactId>caliper</artifactId>
+      <version>1.0-beta-3</version>
+    </dependency>
+  </dependencies>
+
+  <build>
+    <pluginManagement>
+      <plugins>
+        <plugin>
+          <groupId>org.apache.maven.plugins</groupId>
+          <artifactId>maven-deploy-plugin</artifactId>
+          <version>3.0.0</version>
+          <configuration>
+            <!-- Not deployed -->
+            <skip>true</skip>
+          </configuration>
+        </plugin>
+      </plugins>
+    </pluginManagement>
+  </build>
+
+  <developers>
+    <developer>
+      <name>Inderjeet Singh</name>
+      <organization>Google Inc.</organization>
+    </developer>
+    <developer>
+      <name>Joel Leitch</name>
+      <organization>Google Inc.</organization>
+    </developer>
+    <developer>
+      <name>Jesse Wilson</name>
+      <organization>Google Inc.</organization>
+    </developer>
+  </developers>
+</project>
diff --git a/metrics/src/main/java/com/google/gson/metrics/BagOfPrimitives.java b/metrics/src/main/java/com/google/gson/metrics/BagOfPrimitives.java
new file mode 100644
index 0000000..008e31f
--- /dev/null
+++ b/metrics/src/main/java/com/google/gson/metrics/BagOfPrimitives.java
@@ -0,0 +1,88 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.metrics;
+
+/**
+ * Class with a bunch of primitive fields
+ *
+ * @author Inderjeet Singh
+ */
+public class BagOfPrimitives {
+  public static final long DEFAULT_VALUE = 0;
+  public long longValue;
+  public int intValue;
+  public boolean booleanValue;
+  public String stringValue;
+
+  public BagOfPrimitives() {
+    this(DEFAULT_VALUE, 0, false, "");
+  }
+
+  public BagOfPrimitives(long longValue, int intValue, boolean booleanValue, String stringValue) {
+    this.longValue = longValue;
+    this.intValue = intValue;
+    this.booleanValue = booleanValue;
+    this.stringValue = stringValue;
+  }
+
+  public int getIntValue() {
+    return intValue;
+  }
+
+  public String getExpectedJson() {
+    StringBuilder sb = new StringBuilder();
+    sb.append("{");
+    sb.append("\"longValue\":").append(longValue).append(",");
+    sb.append("\"intValue\":").append(intValue).append(",");
+    sb.append("\"booleanValue\":").append(booleanValue).append(",");
+    sb.append("\"stringValue\":\"").append(stringValue).append("\"");
+    sb.append("}");
+    return sb.toString();
+  }
+
+  @Override
+  public int hashCode() {
+    final int prime = 31;
+    int result = 1;
+    result = prime * result + (booleanValue ? 1231 : 1237);
+    result = prime * result + intValue;
+    result = prime * result + (int) (longValue ^ (longValue >>> 32));
+    result = prime * result + ((stringValue == null) ? 0 : stringValue.hashCode());
+    return result;
+  }
+
+  @Override
+  public boolean equals(Object obj) {
+    if (this == obj) return true;
+    if (obj == null) return false;
+    if (getClass() != obj.getClass()) return false;
+    BagOfPrimitives other = (BagOfPrimitives) obj;
+    if (booleanValue != other.booleanValue) return false;
+    if (intValue != other.intValue) return false;
+    if (longValue != other.longValue) return false;
+    if (stringValue == null) {
+      return other.stringValue == null;
+    } else {
+      return stringValue.equals(other.stringValue);
+    }
+  }
+
+  @Override
+  public String toString() {
+    return String.format("(longValue=%d,intValue=%d,booleanValue=%b,stringValue=%s)",
+        longValue, intValue, booleanValue, stringValue);
+  }
+}
diff --git a/metrics/src/main/java/com/google/gson/metrics/BagOfPrimitivesDeserializationBenchmark.java b/metrics/src/main/java/com/google/gson/metrics/BagOfPrimitivesDeserializationBenchmark.java
new file mode 100644
index 0000000..80881dc
--- /dev/null
+++ b/metrics/src/main/java/com/google/gson/metrics/BagOfPrimitivesDeserializationBenchmark.java
@@ -0,0 +1,121 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.metrics;
+
+import com.google.caliper.BeforeExperiment;
+import com.google.gson.Gson;
+import com.google.gson.stream.JsonReader;
+import java.io.IOException;
+import java.io.StringReader;
+import java.lang.reflect.Field;
+
+/**
+ * Caliper based micro benchmarks for Gson
+ *
+ * @author Inderjeet Singh
+ * @author Jesse Wilson
+ * @author Joel Leitch
+ */
+public class BagOfPrimitivesDeserializationBenchmark {
+
+  private Gson gson;
+  private String json;
+
+  public static void main(String[] args) {
+    NonUploadingCaliperRunner.run(BagOfPrimitivesDeserializationBenchmark.class, args);
+  }
+  
+  @BeforeExperiment
+  void setUp() throws Exception {
+    this.gson = new Gson();
+    BagOfPrimitives bag = new BagOfPrimitives(10L, 1, false, "foo");
+    this.json = gson.toJson(bag);
+  }
+
+  /** 
+   * Benchmark to measure Gson performance for deserializing an object
+   */
+  public void timeBagOfPrimitivesDefault(int reps) {
+    for (int i=0; i<reps; ++i) {
+      gson.fromJson(json, BagOfPrimitives.class);
+    }
+  }
+
+  /**
+   * Benchmark to measure deserializing objects by hand
+   */
+  public void timeBagOfPrimitivesStreaming(int reps) throws IOException {
+    for (int i=0; i<reps; ++i) {
+      StringReader reader = new StringReader(json);
+      JsonReader jr = new JsonReader(reader);
+      jr.beginObject();
+      long longValue = 0;
+      int intValue = 0;
+      boolean booleanValue = false;
+      String stringValue = null;
+      while(jr.hasNext()) {
+        String name = jr.nextName();
+        if (name.equals("longValue")) {
+          longValue = jr.nextLong();
+        } else if (name.equals("intValue")) {
+          intValue = jr.nextInt();
+        } else if (name.equals("booleanValue")) {
+          booleanValue = jr.nextBoolean();
+        } else if (name.equals("stringValue")) {
+          stringValue = jr.nextString();
+        } else {
+          throw new IOException("Unexpected name: " + name);
+        }
+      }
+      jr.endObject();
+      new BagOfPrimitives(longValue, intValue, booleanValue, stringValue);
+    }
+  }
+
+  /**
+   * This benchmark measures the ideal Gson performance: the cost of parsing a JSON stream and
+   * setting object values by reflection. We should strive to reduce the discrepancy between this
+   * and {@link #timeBagOfPrimitivesDefault(int)} .
+   */
+  public void timeBagOfPrimitivesReflectionStreaming(int reps) throws Exception {
+    for (int i=0; i<reps; ++i) {
+      StringReader reader = new StringReader(json);
+      JsonReader jr = new JsonReader(reader);
+      jr.beginObject();
+      BagOfPrimitives bag = new BagOfPrimitives();
+      while(jr.hasNext()) {
+        String name = jr.nextName();
+        for (Field field : BagOfPrimitives.class.getDeclaredFields()) {
+          if (field.getName().equals(name)) {
+            Class<?> fieldType = field.getType();
+            if (fieldType.equals(long.class)) {
+              field.setLong(bag, jr.nextLong());
+            } else if (fieldType.equals(int.class)) {
+              field.setInt(bag, jr.nextInt());
+            } else if (fieldType.equals(boolean.class)) {
+              field.setBoolean(bag, jr.nextBoolean());
+            } else if (fieldType.equals(String.class)) {
+              field.set(bag, jr.nextString());
+            } else {
+              throw new RuntimeException("Unexpected: type: " + fieldType + ", name: " + name);
+            }
+          }
+        }
+      }
+      jr.endObject();
+    }
+  }
+}
diff --git a/metrics/src/main/java/com/google/gson/metrics/CollectionsDeserializationBenchmark.java b/metrics/src/main/java/com/google/gson/metrics/CollectionsDeserializationBenchmark.java
new file mode 100644
index 0000000..dad0d99
--- /dev/null
+++ b/metrics/src/main/java/com/google/gson/metrics/CollectionsDeserializationBenchmark.java
@@ -0,0 +1,138 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.metrics;
+
+import com.google.caliper.BeforeExperiment;
+import com.google.gson.Gson;
+import com.google.gson.reflect.TypeToken;
+import com.google.gson.stream.JsonReader;
+import java.io.IOException;
+import java.io.StringReader;
+import java.lang.reflect.Field;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Caliper based micro benchmarks for Gson
+ *
+ * @author Inderjeet Singh
+ */
+public class CollectionsDeserializationBenchmark {
+
+  private static final Type LIST_TYPE = new TypeToken<List<BagOfPrimitives>>(){}.getType();
+  private Gson gson;
+  private String json;
+
+  public static void main(String[] args) {
+    NonUploadingCaliperRunner.run(CollectionsDeserializationBenchmark.class, args);
+  }
+  
+  @BeforeExperiment
+  void setUp() throws Exception {
+    this.gson = new Gson();
+    List<BagOfPrimitives> bags = new ArrayList<>();
+    for (int i = 0; i < 100; ++i) {
+      bags.add(new BagOfPrimitives(10L, 1, false, "foo"));
+    }
+    this.json = gson.toJson(bags, LIST_TYPE);
+  }
+
+  /** 
+   * Benchmark to measure Gson performance for deserializing an object
+   */
+  public void timeCollectionsDefault(int reps) {
+    for (int i=0; i<reps; ++i) {
+      gson.fromJson(json, LIST_TYPE);
+    }
+  }
+
+  /**
+   * Benchmark to measure deserializing objects by hand
+   */
+  public void timeCollectionsStreaming(int reps) throws IOException {
+    for (int i=0; i<reps; ++i) {
+      StringReader reader = new StringReader(json);
+      JsonReader jr = new JsonReader(reader);
+      jr.beginArray();
+      List<BagOfPrimitives> bags = new ArrayList<>();
+      while(jr.hasNext()) {
+        jr.beginObject();
+        long longValue = 0;
+        int intValue = 0;
+        boolean booleanValue = false;
+        String stringValue = null;
+        while(jr.hasNext()) {
+          String name = jr.nextName();
+          if (name.equals("longValue")) {
+            longValue = jr.nextLong();
+          } else if (name.equals("intValue")) {
+            intValue = jr.nextInt();
+          } else if (name.equals("booleanValue")) {
+            booleanValue = jr.nextBoolean();
+          } else if (name.equals("stringValue")) {
+            stringValue = jr.nextString();
+          } else {
+            throw new IOException("Unexpected name: " + name);
+          }
+        }
+        jr.endObject();
+        bags.add(new BagOfPrimitives(longValue, intValue, booleanValue, stringValue));
+      }
+      jr.endArray();
+    }
+  }
+
+  /**
+   * This benchmark measures the ideal Gson performance: the cost of parsing a JSON stream and
+   * setting object values by reflection. We should strive to reduce the discrepancy between this
+   * and {@link #timeCollectionsDefault(int)} .
+   */
+  public void timeCollectionsReflectionStreaming(int reps) throws Exception {
+    for (int i=0; i<reps; ++i) {
+      StringReader reader = new StringReader(json);
+      JsonReader jr = new JsonReader(reader);
+      jr.beginArray();
+      List<BagOfPrimitives> bags = new ArrayList<>();
+      while(jr.hasNext()) {
+        jr.beginObject();
+        BagOfPrimitives bag = new BagOfPrimitives();
+        while(jr.hasNext()) {
+          String name = jr.nextName();
+          for (Field field : BagOfPrimitives.class.getDeclaredFields()) {
+            if (field.getName().equals(name)) {
+              Class<?> fieldType = field.getType();
+              if (fieldType.equals(long.class)) {
+                field.setLong(bag, jr.nextLong());
+              } else if (fieldType.equals(int.class)) {
+                field.setInt(bag, jr.nextInt());
+              } else if (fieldType.equals(boolean.class)) {
+                field.setBoolean(bag, jr.nextBoolean());
+              } else if (fieldType.equals(String.class)) {
+                field.set(bag, jr.nextString());
+              } else {
+                throw new RuntimeException("Unexpected: type: " + fieldType + ", name: " + name);
+              }
+            }
+          }
+        }
+        jr.endObject();
+        bags.add(bag);
+      }
+      jr.endArray();
+    }
+  }
+}
diff --git a/metrics/src/main/java/com/google/gson/metrics/NonUploadingCaliperRunner.java b/metrics/src/main/java/com/google/gson/metrics/NonUploadingCaliperRunner.java
new file mode 100644
index 0000000..80633e1
--- /dev/null
+++ b/metrics/src/main/java/com/google/gson/metrics/NonUploadingCaliperRunner.java
@@ -0,0 +1,21 @@
+package com.google.gson.metrics;
+
+import com.google.caliper.runner.CaliperMain;
+
+class NonUploadingCaliperRunner {
+  private static String[] concat(String first, String... others) {
+    if (others.length == 0) {
+      return new String[] { first };
+    } else {
+      String[] result = new String[others.length + 1];
+      result[0] = first;
+      System.arraycopy(others, 0, result, 1, others.length);
+      return result;
+    }
+  }
+
+  public static void run(Class<?> c, String[] args) {
+    // Disable result upload; Caliper uploads results to webapp by default, see https://github.com/google/caliper/issues/356
+    CaliperMain.main(c, concat("-Cresults.upload.options.url=", args));
+  }
+}
diff --git a/metrics/src/main/java/com/google/gson/metrics/ParseBenchmark.java b/metrics/src/main/java/com/google/gson/metrics/ParseBenchmark.java
new file mode 100644
index 0000000..c00dbdc
--- /dev/null
+++ b/metrics/src/main/java/com/google/gson/metrics/ParseBenchmark.java
@@ -0,0 +1,428 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.metrics;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.core.JsonFactoryBuilder;
+import com.fasterxml.jackson.core.JsonToken;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.MapperFeature;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.json.JsonMapper;
+import com.google.caliper.BeforeExperiment;
+import com.google.caliper.Param;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonParser;
+import com.google.gson.annotations.SerializedName;
+import com.google.gson.reflect.TypeToken;
+import java.io.CharArrayReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.Reader;
+import java.io.StringWriter;
+import java.lang.reflect.Type;
+import java.net.URL;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.List;
+import java.util.Locale;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+/**
+ * Measure Gson and Jackson parsing and binding performance.
+ *
+ * <p>This benchmark requires that ParseBenchmarkData.zip is on the classpath.
+ * That file contains Twitter feed data, which is representative of what
+ * applications will be parsing.
+ */
+public final class ParseBenchmark {
+  @Param Document document;
+  @Param Api api;
+
+  private enum Document {
+    TWEETS(new TypeToken<List<Tweet>>() {}, new TypeReference<List<Tweet>>() {}),
+    READER_SHORT(new TypeToken<Feed>() {}, new TypeReference<Feed>() {}),
+    READER_LONG(new TypeToken<Feed>() {}, new TypeReference<Feed>() {});
+
+    private final Type gsonType;
+    private final TypeReference<?> jacksonType;
+
+    private Document(TypeToken<?> typeToken, TypeReference<?> typeReference) {
+      this.gsonType = typeToken.getType();
+      this.jacksonType = typeReference;
+    }
+  }
+
+  private enum Api {
+    JACKSON_STREAM {
+      @Override Parser newParser() {
+        return new JacksonStreamParser();
+      }
+    },
+    JACKSON_BIND {
+      @Override Parser newParser() {
+        return new JacksonBindParser();
+      }
+    },
+    GSON_STREAM {
+      @Override Parser newParser() {
+        return new GsonStreamParser();
+      }
+    },
+    GSON_SKIP {
+      @Override Parser newParser() {
+        return new GsonSkipParser();
+      }
+    },
+    GSON_DOM {
+      @Override Parser newParser() {
+        return new GsonDomParser();
+      }
+    },
+    GSON_BIND {
+      @Override Parser newParser() {
+        return new GsonBindParser();
+      }
+    };
+    abstract Parser newParser();
+  }
+
+  private char[] text;
+  private Parser parser;
+
+  @BeforeExperiment
+  void setUp() throws Exception {
+    text = resourceToString(document.name() + ".json").toCharArray();
+    parser = api.newParser();
+  }
+
+  public void timeParse(int reps) throws Exception {
+    for (int i = 0; i < reps; i++) {
+      parser.parse(text, document);
+    }
+  }
+
+  private static File getResourceFile(String path) throws Exception {
+    URL url = ParseBenchmark.class.getResource(path);
+    if (url == null) {
+      throw new IllegalArgumentException("Resource " + path + " does not exist");
+    }
+    File file = new File(url.toURI());
+    if (!file.isFile()) {
+      throw new IllegalArgumentException("Resource " + path + " is not a file");
+    }
+    return file;
+  }
+
+  private static String resourceToString(String fileName) throws Exception {
+    ZipFile zipFile = new ZipFile(getResourceFile("/ParseBenchmarkData.zip"));
+    try {
+      ZipEntry zipEntry = zipFile.getEntry(fileName);
+      Reader reader = new InputStreamReader(zipFile.getInputStream(zipEntry));
+      char[] buffer = new char[8192];
+      StringWriter writer = new StringWriter();
+      int count;
+      while ((count = reader.read(buffer)) != -1) {
+        writer.write(buffer, 0, count);
+      }
+      reader.close();
+      return writer.toString();
+
+    } finally {
+      zipFile.close();
+    }
+  }
+
+  public static void main(String[] args) throws Exception {
+    NonUploadingCaliperRunner.run(ParseBenchmark.class, args);
+  }
+
+  interface Parser {
+    void parse(char[] data, Document document) throws Exception;
+  }
+
+  private static class GsonStreamParser implements Parser {
+    @Override
+    public void parse(char[] data, Document document) throws Exception {
+      com.google.gson.stream.JsonReader jsonReader
+          = new com.google.gson.stream.JsonReader(new CharArrayReader(data));
+      readToken(jsonReader);
+      jsonReader.close();
+    }
+
+    private void readToken(com.google.gson.stream.JsonReader reader) throws IOException {
+      while (true) {
+        switch (reader.peek()) {
+        case BEGIN_ARRAY:
+          reader.beginArray();
+          break;
+        case END_ARRAY:
+          reader.endArray();
+          break;
+        case BEGIN_OBJECT:
+          reader.beginObject();
+          break;
+        case END_OBJECT:
+          reader.endObject();
+          break;
+        case NAME:
+          reader.nextName();
+          break;
+        case BOOLEAN:
+          reader.nextBoolean();
+          break;
+        case NULL:
+          reader.nextNull();
+          break;
+        case NUMBER:
+          reader.nextLong();
+          break;
+        case STRING:
+          reader.nextString();
+          break;
+        case END_DOCUMENT:
+          return;
+        default:
+          throw new IllegalArgumentException("Unexpected token" + reader.peek());
+        }
+      }
+    }
+  }
+
+  private static class GsonSkipParser implements Parser {
+    @Override
+    public void parse(char[] data, Document document) throws Exception {
+      com.google.gson.stream.JsonReader jsonReader
+          = new com.google.gson.stream.JsonReader(new CharArrayReader(data));
+      jsonReader.skipValue();
+      jsonReader.close();
+    }
+  }
+
+  private static class JacksonStreamParser implements Parser {
+    @Override
+    public void parse(char[] data, Document document) throws Exception {
+      JsonFactory jsonFactory = new JsonFactoryBuilder().configure(JsonFactory.Feature.CANONICALIZE_FIELD_NAMES, false).build();
+      com.fasterxml.jackson.core.JsonParser jp = jsonFactory.createParser(new CharArrayReader(data));
+      int depth = 0;
+      do {
+        JsonToken token = jp.nextToken();
+        switch (token) {
+        case START_OBJECT:
+        case START_ARRAY:
+          depth++;
+          break;
+        case END_OBJECT:
+        case END_ARRAY:
+          depth--;
+          break;
+        case FIELD_NAME:
+          jp.getCurrentName();
+          break;
+        case VALUE_STRING:
+          jp.getText();
+          break;
+        case VALUE_NUMBER_INT:
+        case VALUE_NUMBER_FLOAT:
+          jp.getLongValue();
+          break;
+        case VALUE_TRUE:
+        case VALUE_FALSE:
+          jp.getBooleanValue();
+          break;
+        case VALUE_NULL:
+          // Do nothing; nextToken() will advance in stream
+          break;
+        default:
+          throw new IllegalArgumentException("Unexpected token " + token);
+        }
+      } while (depth > 0);
+      jp.close();
+    }
+  }
+
+  private static class GsonDomParser implements Parser {
+    @Override
+    public void parse(char[] data, Document document) throws Exception {
+      JsonParser.parseReader(new CharArrayReader(data));
+    }
+  }
+
+  private static class GsonBindParser implements Parser {
+    private static Gson gson = new GsonBuilder()
+        .setDateFormat("EEE MMM dd HH:mm:ss Z yyyy")
+        .create();
+
+    @Override
+    public void parse(char[] data, Document document) throws Exception {
+      gson.fromJson(new CharArrayReader(data), document.gsonType);
+    }
+  }
+
+  private static class JacksonBindParser implements Parser {
+    private static final ObjectMapper mapper;
+
+    static {
+      mapper = JsonMapper.builder()
+        .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
+        .configure(MapperFeature.AUTO_DETECT_FIELDS, true)
+        .build();
+      mapper.setDateFormat(new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.ENGLISH));
+    }
+
+    @Override
+    public void parse(char[] data, Document document) throws Exception {
+      mapper.readValue(new CharArrayReader(data), document.jacksonType);
+    }
+  }
+
+  static class Tweet {
+    @JsonProperty String coordinates;
+    @JsonProperty boolean favorited;
+    @JsonProperty Date created_at;
+    @JsonProperty boolean truncated;
+    @JsonProperty Tweet retweeted_status;
+    @JsonProperty String id_str;
+    @JsonProperty String in_reply_to_id_str;
+    @JsonProperty String contributors;
+    @JsonProperty String text;
+    @JsonProperty long id;
+    @JsonProperty String retweet_count;
+    @JsonProperty String in_reply_to_status_id_str;
+    @JsonProperty Object geo;
+    @JsonProperty boolean retweeted;
+    @JsonProperty String in_reply_to_user_id;
+    @JsonProperty String in_reply_to_screen_name;
+    @JsonProperty Object place;
+    @JsonProperty User user;
+    @JsonProperty String source;
+    @JsonProperty String in_reply_to_user_id_str;
+  }
+
+  static class User {
+    @JsonProperty String name;
+    @JsonProperty String profile_sidebar_border_color;
+    @JsonProperty boolean profile_background_tile;
+    @JsonProperty String profile_sidebar_fill_color;
+    @JsonProperty Date created_at;
+    @JsonProperty String location;
+    @JsonProperty String profile_image_url;
+    @JsonProperty boolean follow_request_sent;
+    @JsonProperty String profile_link_color;
+    @JsonProperty boolean is_translator;
+    @JsonProperty String id_str;
+    @JsonProperty int favourites_count;
+    @JsonProperty boolean contributors_enabled;
+    @JsonProperty String url;
+    @JsonProperty boolean default_profile;
+    @JsonProperty long utc_offset;
+    @JsonProperty long id;
+    @JsonProperty boolean profile_use_background_image;
+    @JsonProperty int listed_count;
+    @JsonProperty String lang;
+    @JsonProperty("protected") @SerializedName("protected") boolean isProtected;
+    @JsonProperty int followers_count;
+    @JsonProperty String profile_text_color;
+    @JsonProperty String profile_background_color;
+    @JsonProperty String time_zone;
+    @JsonProperty String description;
+    @JsonProperty boolean notifications;
+    @JsonProperty boolean geo_enabled;
+    @JsonProperty boolean verified;
+    @JsonProperty String profile_background_image_url;
+    @JsonProperty boolean defalut_profile_image;
+    @JsonProperty int friends_count;
+    @JsonProperty int statuses_count;
+    @JsonProperty String screen_name;
+    @JsonProperty boolean following;
+    @JsonProperty boolean show_all_inline_media;
+  }
+
+  static class Feed {
+    @JsonProperty String id;
+    @JsonProperty String title;
+    @JsonProperty String description;
+    @JsonProperty("alternate") @SerializedName("alternate") List<Link> alternates;
+    @JsonProperty long updated;
+    @JsonProperty List<Item> items;
+
+    @Override public String toString() {
+      StringBuilder result = new StringBuilder()
+          .append(id)
+          .append("\n").append(title)
+          .append("\n").append(description)
+          .append("\n").append(alternates)
+          .append("\n").append(updated);
+      int i = 1;
+      for (Item item : items) {
+        result.append(i++).append(": ").append(item).append("\n\n");
+      }
+      return result.toString();
+    }
+  }
+
+  static class Link {
+    @JsonProperty String href;
+
+    @Override public String toString() {
+      return href;
+    }
+  }
+
+  static class Item {
+    @JsonProperty List<String> categories;
+    @JsonProperty String title;
+    @JsonProperty long published;
+    @JsonProperty long updated;
+    @JsonProperty("alternate") @SerializedName("alternate") List<Link> alternates;
+    @JsonProperty Content content;
+    @JsonProperty String author;
+    @JsonProperty List<ReaderUser> likingUsers;
+
+    @Override public String toString() {
+      return title
+          + "\nauthor: " + author
+          + "\npublished: " + published
+          + "\nupdated: " + updated
+          + "\n" + content
+          + "\nliking users: " + likingUsers
+          + "\nalternates: " + alternates
+          + "\ncategories: " + categories;
+    }
+  }
+
+  static class Content {
+    @JsonProperty String content;
+
+    @Override public String toString() {
+      return content;
+    }
+  }
+
+  static class ReaderUser {
+    @JsonProperty String userId;
+
+    @Override public String toString() {
+      return userId;
+    }
+  }
+}
diff --git a/metrics/src/main/java/com/google/gson/metrics/SerializationBenchmark.java b/metrics/src/main/java/com/google/gson/metrics/SerializationBenchmark.java
new file mode 100644
index 0000000..bf67a66
--- /dev/null
+++ b/metrics/src/main/java/com/google/gson/metrics/SerializationBenchmark.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.metrics;
+
+import com.google.caliper.BeforeExperiment;
+import com.google.caliper.Param;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+/**
+ * Caliper based micro benchmarks for Gson serialization
+ *
+ * @author Inderjeet Singh
+ * @author Jesse Wilson
+ * @author Joel Leitch
+ */
+public class SerializationBenchmark {
+
+  private Gson gson;
+  private BagOfPrimitives bag;
+  @Param
+  private boolean pretty;
+
+  public static void main(String[] args) {
+    NonUploadingCaliperRunner.run(SerializationBenchmark.class, args);
+  }
+  
+  @BeforeExperiment
+  void setUp() throws Exception {
+    this.gson = pretty ? new GsonBuilder().setPrettyPrinting().create() : new Gson();
+    this.bag = new BagOfPrimitives(10L, 1, false, "foo");
+  }
+
+  public void timeObjectSerialization(int reps) {
+    for (int i=0; i<reps; ++i) {
+      gson.toJson(bag);
+    }
+  }
+}
diff --git a/metrics/src/main/resources/ParseBenchmarkData.zip b/metrics/src/main/resources/ParseBenchmarkData.zip
new file mode 100644
index 0000000..58e08bb
--- /dev/null
+++ b/metrics/src/main/resources/ParseBenchmarkData.zip
Binary files differ
diff --git a/pom.xml b/pom.xml
new file mode 100644
index 0000000..5d21fb9
--- /dev/null
+++ b/pom.xml
@@ -0,0 +1,131 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+  <modelVersion>4.0.0</modelVersion>
+
+  <parent>
+    <groupId>org.sonatype.oss</groupId>
+    <artifactId>oss-parent</artifactId>
+    <version>9</version>
+  </parent>
+
+  <groupId>com.google.code.gson</groupId>
+  <artifactId>gson-parent</artifactId>
+  <version>2.9.1</version>
+  <packaging>pom</packaging>
+
+  <name>Gson Parent</name>
+  <description>Gson JSON library</description>
+  <url>https://github.com/google/gson</url>
+
+  <modules>
+    <module>gson</module>
+    <module>extras</module> 
+    <module>metrics</module>
+    <module>proto</module>
+  </modules>
+
+  <properties>
+    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+    <javaVersion>7</javaVersion>
+  </properties>
+
+  <scm>
+    <url>https://github.com/google/gson/</url>
+    <connection>scm:git:https://github.com/google/gson.git</connection>
+    <developerConnection>scm:git:git@github.com:google/gson.git</developerConnection>
+    <tag>gson-parent-2.9.1</tag>
+  </scm>
+
+  <issueManagement>
+    <system>GitHub Issues</system>
+    <url>https://github.com/google/gson/issues</url>
+  </issueManagement>
+
+  <licenses>
+    <license>
+      <name>Apache-2.0</name>
+      <url>https://www.apache.org/licenses/LICENSE-2.0.txt</url>
+    </license>
+  </licenses>
+
+  <dependencyManagement>
+    <dependencies>
+      <dependency>
+        <groupId>junit</groupId>
+        <artifactId>junit</artifactId>
+        <version>4.13.2</version>
+        <scope>test</scope>
+      </dependency>
+    </dependencies>
+  </dependencyManagement>
+
+  <build>
+    <pluginManagement>
+      <plugins>
+        <plugin>
+          <groupId>org.apache.maven.plugins</groupId>
+          <artifactId>maven-compiler-plugin</artifactId>
+          <version>3.10.1</version>
+          <configuration>
+            <release>${javaVersion}</release>
+            <jdkToolchain>
+              <version>[11,)</version>
+            </jdkToolchain>
+          </configuration>
+        </plugin>
+        <plugin>
+          <groupId>org.apache.maven.plugins</groupId>
+          <artifactId>maven-javadoc-plugin</artifactId>
+          <version>3.4.0</version>
+          <configuration>
+            <jdkToolchain>
+              <version>[11,)</version>
+            </jdkToolchain>
+            <!-- Exclude `missing` group because some tags have been omitted when they are redundant -->
+            <doclint>all,-missing</doclint>
+            <!-- Link against newer Java API Javadoc because most users likely 
+              use a newer Java version than the one used for building this project -->
+            <detectJavaApiLink>false</detectJavaApiLink>
+            <links>
+              <link>https://docs.oracle.com/en/java/javase/11/docs/api/</link>
+            </links>
+            <!-- Disable detection of offline links between Maven modules: 
+              (1) Only `gson` module is published, so for other modules Javadoc links don't 
+              matter much at the moment; (2) The derived URL for the modules is based on 
+              the project URL (= Gson GitHub repo) which is incorrect because it is not 
+              hosting the Javadoc (3) It might fail due to https://bugs.openjdk.java.net/browse/JDK-8212233 -->
+            <detectOfflineLinks>false</detectOfflineLinks>
+          </configuration>
+        </plugin>
+        <plugin>
+          <groupId>org.apache.maven.plugins</groupId>
+          <artifactId>maven-jar-plugin</artifactId>
+          <version>3.2.2</version>
+        </plugin>
+      </plugins>
+    </pluginManagement>
+    <plugins>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-release-plugin</artifactId>
+        <version>2.5.3</version>
+        <dependencies>
+          <dependency>
+            <groupId>org.apache.maven.scm</groupId>
+            <artifactId>maven-scm-api</artifactId>
+            <version>1.13.0</version>
+          </dependency>
+          <dependency>
+            <groupId>org.apache.maven.scm</groupId>
+            <artifactId>maven-scm-provider-gitexe</artifactId>
+            <version>1.13.0</version>
+          </dependency>
+        </dependencies>
+        <configuration>
+          <autoVersionSubmodules>true</autoVersionSubmodules>
+        </configuration>
+      </plugin>
+    </plugins>
+  </build>
+</project>
diff --git a/proto/.gitignore b/proto/.gitignore
new file mode 100644
index 0000000..f44578a
--- /dev/null
+++ b/proto/.gitignore
@@ -0,0 +1 @@
+src/main/java/com/google/gson/protobuf/generated/
diff --git a/proto/README.md b/proto/README.md
new file mode 100644
index 0000000..c6f7906
--- /dev/null
+++ b/proto/README.md
@@ -0,0 +1,7 @@
+# proto
+
+This Maven module contains the source code for a JSON serializer and deserializer for
+[Protocol Buffers (protobuf)](https://developers.google.com/protocol-buffers/docs/javatutorial)
+messages.
+
+The artifacts created by this module are currently not deployed to Maven Central.
diff --git a/proto/pom.xml b/proto/pom.xml
new file mode 100644
index 0000000..5bd3ecf
--- /dev/null
+++ b/proto/pom.xml
@@ -0,0 +1,106 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+
+  <modelVersion>4.0.0</modelVersion>
+  <parent>
+    <groupId>com.google.code.gson</groupId>
+    <artifactId>gson-parent</artifactId>
+    <version>2.9.1</version>
+  </parent>
+
+  <artifactId>proto</artifactId>
+  <name>Gson Protobuf Support</name>
+  <description>Gson support for Protobufs</description>
+
+  <licenses>
+    <license>
+      <name>Apache-2.0</name>
+      <url>https://www.apache.org/licenses/LICENSE-2.0.txt</url>
+    </license>
+  </licenses>
+
+  <dependencies>
+    <dependency>
+      <groupId>com.google.code.gson</groupId>
+      <artifactId>gson</artifactId>
+      <version>${project.parent.version}</version>
+    </dependency>
+
+    <dependency>
+      <groupId>com.google.protobuf</groupId>
+      <artifactId>protobuf-java</artifactId>
+      <version>4.0.0-rc-2</version>
+    </dependency>
+
+    <dependency>
+      <groupId>com.google.guava</groupId>
+      <artifactId>guava</artifactId>
+      <version>31.1-jre</version>
+    </dependency>
+
+    <dependency>
+      <groupId>junit</groupId>
+      <artifactId>junit</artifactId>
+      <scope>test</scope>
+    </dependency>
+
+    <dependency>
+      <groupId>com.google.truth</groupId>
+      <artifactId>truth</artifactId>
+      <version>1.1.3</version>
+      <scope>test</scope>
+    </dependency>
+  </dependencies>
+
+  <build>
+    <finalName>gson-proto</finalName>
+    <!-- Setup based on https://quarkus.io/guides/grpc-getting-started#generating-java-files-from-proto-with-protobuf-maven-plugin -->
+    <extensions>
+      <extension>
+        <groupId>kr.motd.maven</groupId>
+        <artifactId>os-maven-plugin</artifactId>
+        <version>1.7.0</version>
+      </extension>
+    </extensions>
+
+    <plugins>
+      <plugin>
+        <groupId>org.xolstice.maven.plugins</groupId>
+        <artifactId>protobuf-maven-plugin</artifactId>
+        <version>0.6.1</version>
+        <configuration>
+          <protocArtifact>com.google.protobuf:protoc:3.17.3:exe:${os.detected.classifier}</protocArtifact>
+        </configuration>
+        <executions>
+          <execution>
+            <goals>
+              <goal>test-compile</goal>
+            </goals>
+          </execution>
+        </executions>
+      </plugin>
+    </plugins>
+
+    <pluginManagement>
+      <plugins>
+        <plugin>
+          <groupId>org.apache.maven.plugins</groupId>
+          <artifactId>maven-deploy-plugin</artifactId>
+          <version>3.0.0</version>
+          <configuration>
+            <!-- Not deployed -->
+            <skip>true</skip>
+          </configuration>
+        </plugin>
+      </plugins>
+    </pluginManagement>
+  </build>
+
+  <developers>
+    <developer>
+      <name>Inderjeet Singh</name>
+      <organization>Google Inc.</organization>
+    </developer>
+  </developers>
+</project>
diff --git a/proto/src/main/java/com/google/gson/protobuf/ProtoTypeAdapter.java b/proto/src/main/java/com/google/gson/protobuf/ProtoTypeAdapter.java
new file mode 100644
index 0000000..4b38c7c
--- /dev/null
+++ b/proto/src/main/java/com/google/gson/protobuf/ProtoTypeAdapter.java
@@ -0,0 +1,416 @@
+/*
+ * Copyright (C) 2010 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.gson.protobuf;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import com.google.common.base.CaseFormat;
+import com.google.common.collect.MapMaker;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonDeserializationContext;
+import com.google.gson.JsonDeserializer;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParseException;
+import com.google.gson.JsonSerializationContext;
+import com.google.gson.JsonSerializer;
+import com.google.protobuf.DescriptorProtos.EnumValueOptions;
+import com.google.protobuf.DescriptorProtos.FieldOptions;
+import com.google.protobuf.Descriptors.Descriptor;
+import com.google.protobuf.Descriptors.EnumDescriptor;
+import com.google.protobuf.Descriptors.EnumValueDescriptor;
+import com.google.protobuf.Descriptors.FieldDescriptor;
+import com.google.protobuf.DynamicMessage;
+import com.google.protobuf.Extension;
+import com.google.protobuf.Message;
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentMap;
+
+/**
+ * GSON type adapter for protocol buffers that knows how to serialize enums either by using their
+ * values or their names, and also supports custom proto field names.
+ * <p>
+ * You can specify which case representation is used for the proto fields when writing/reading the
+ * JSON payload by calling {@link Builder#setFieldNameSerializationFormat(CaseFormat, CaseFormat)}.
+ * <p>
+ * An example of default serialization/deserialization using custom proto field names is shown
+ * below:
+ *
+ * <pre>
+ * message MyMessage {
+ *   // Will be serialized as 'osBuildID' instead of the default 'osBuildId'.
+ *   string os_build_id = 1 [(serialized_name) = "osBuildID"];
+ * }
+ * </pre>
+ * <p>
+ *
+ * @author Inderjeet Singh
+ * @author Emmanuel Cron
+ * @author Stanley Wang
+ */
+public class ProtoTypeAdapter
+    implements JsonSerializer<Message>, JsonDeserializer<Message> {
+  /**
+   * Determines how enum <u>values</u> should be serialized.
+   */
+  public enum EnumSerialization {
+    /**
+     * Serializes and deserializes enum values using their <b>number</b>. When this is used, custom
+     * value names set on enums are ignored.
+     */
+    NUMBER,
+    /** Serializes and deserializes enum values using their <b>name</b>. */
+    NAME;
+  }
+
+  /**
+   * Builder for {@link ProtoTypeAdapter}s.
+   */
+  public static class Builder {
+    private final Set<Extension<FieldOptions, String>> serializedNameExtensions;
+    private final Set<Extension<EnumValueOptions, String>> serializedEnumValueExtensions;
+    private EnumSerialization enumSerialization;
+    private CaseFormat protoFormat;
+    private CaseFormat jsonFormat;
+
+    private Builder(EnumSerialization enumSerialization, CaseFormat fromFieldNameFormat,
+        CaseFormat toFieldNameFormat) {
+      this.serializedNameExtensions = new HashSet<>();
+      this.serializedEnumValueExtensions = new HashSet<>();
+      setEnumSerialization(enumSerialization);
+      setFieldNameSerializationFormat(fromFieldNameFormat, toFieldNameFormat);
+    }
+
+    public Builder setEnumSerialization(EnumSerialization enumSerialization) {
+      this.enumSerialization = checkNotNull(enumSerialization);
+      return this;
+    }
+
+    /**
+     * Sets the field names serialization format. The first parameter defines how to read the format
+     * of the proto field names you are converting to JSON. The second parameter defines which
+     * format to use when serializing them.
+     * <p>
+     * For example, if you use the following parameters: {@link CaseFormat#LOWER_UNDERSCORE},
+     * {@link CaseFormat#LOWER_CAMEL}, the following conversion will occur:
+     *
+     * <pre>{@code
+     * PROTO     <->  JSON
+     * my_field       myField
+     * foo            foo
+     * n__id_ct       nIdCt
+     * }</pre>
+     */
+    public Builder setFieldNameSerializationFormat(CaseFormat fromFieldNameFormat,
+        CaseFormat toFieldNameFormat) {
+      this.protoFormat = fromFieldNameFormat;
+      this.jsonFormat = toFieldNameFormat;
+      return this;
+    }
+
+    /**
+     * Adds a field proto annotation that, when set, overrides the default field name
+     * serialization/deserialization. For example, if you add the '{@code serialized_name}'
+     * annotation and you define a field in your proto like the one below:
+     *
+     * <pre>
+     * string client_app_id = 1 [(serialized_name) = "appId"];
+     * </pre>
+     *
+     * ...the adapter will serialize the field using '{@code appId}' instead of the default '
+     * {@code clientAppId}'. This lets you customize the name serialization of any proto field.
+     */
+    public Builder addSerializedNameExtension(
+        Extension<FieldOptions, String> serializedNameExtension) {
+      serializedNameExtensions.add(checkNotNull(serializedNameExtension));
+      return this;
+    }
+
+    /**
+     * Adds an enum value proto annotation that, when set, overrides the default <b>enum</b> value
+     * serialization/deserialization of this adapter. For example, if you add the '
+     * {@code serialized_value}' annotation and you define an enum in your proto like the one below:
+     *
+     * <pre>
+     * enum MyEnum {
+     *   UNKNOWN = 0;
+     *   CLIENT_APP_ID = 1 [(serialized_value) = "APP_ID"];
+     *   TWO = 2 [(serialized_value) = "2"];
+     * }
+     * </pre>
+     *
+     * ...the adapter will serialize the value {@code CLIENT_APP_ID} as "{@code APP_ID}" and the
+     * value {@code TWO} as "{@code 2}". This works for both serialization and deserialization.
+     * <p>
+     * Note that you need to set the enum serialization of this adapter to
+     * {@link EnumSerialization#NAME}, otherwise these annotations will be ignored.
+     */
+    public Builder addSerializedEnumValueExtension(
+        Extension<EnumValueOptions, String> serializedEnumValueExtension) {
+      serializedEnumValueExtensions.add(checkNotNull(serializedEnumValueExtension));
+      return this;
+    }
+
+    public ProtoTypeAdapter build() {
+      return new ProtoTypeAdapter(enumSerialization, protoFormat, jsonFormat,
+          serializedNameExtensions, serializedEnumValueExtensions);
+    }
+  }
+
+  /**
+   * Creates a new {@link ProtoTypeAdapter} builder, defaulting enum serialization to
+   * {@link EnumSerialization#NAME} and converting field serialization from
+   * {@link CaseFormat#LOWER_UNDERSCORE} to {@link CaseFormat#LOWER_CAMEL}.
+   */
+  public static Builder newBuilder() {
+    return new Builder(EnumSerialization.NAME, CaseFormat.LOWER_UNDERSCORE, CaseFormat.LOWER_CAMEL);
+  }
+
+  private static final com.google.protobuf.Descriptors.FieldDescriptor.Type ENUM_TYPE =
+      com.google.protobuf.Descriptors.FieldDescriptor.Type.ENUM;
+
+  private static final ConcurrentMap<String, ConcurrentMap<Class<?>, Method>> mapOfMapOfMethods =
+      new MapMaker().makeMap();
+
+  private final EnumSerialization enumSerialization;
+  private final CaseFormat protoFormat;
+  private final CaseFormat jsonFormat;
+  private final Set<Extension<FieldOptions, String>> serializedNameExtensions;
+  private final Set<Extension<EnumValueOptions, String>> serializedEnumValueExtensions;
+
+  private ProtoTypeAdapter(EnumSerialization enumSerialization,
+      CaseFormat protoFormat,
+      CaseFormat jsonFormat,
+      Set<Extension<FieldOptions, String>> serializedNameExtensions,
+      Set<Extension<EnumValueOptions, String>> serializedEnumValueExtensions) {
+    this.enumSerialization = enumSerialization;
+    this.protoFormat = protoFormat;
+    this.jsonFormat = jsonFormat;
+    this.serializedNameExtensions = serializedNameExtensions;
+    this.serializedEnumValueExtensions = serializedEnumValueExtensions;
+  }
+
+  @Override
+  public JsonElement serialize(Message src, Type typeOfSrc,
+      JsonSerializationContext context) {
+    JsonObject ret = new JsonObject();
+    final Map<FieldDescriptor, Object> fields = src.getAllFields();
+
+    for (Map.Entry<FieldDescriptor, Object> fieldPair : fields.entrySet()) {
+      final FieldDescriptor desc = fieldPair.getKey();
+      String name = getCustSerializedName(desc.getOptions(), desc.getName());
+
+      if (desc.getType() == ENUM_TYPE) {
+        // Enum collections are also returned as ENUM_TYPE
+        if (fieldPair.getValue() instanceof Collection) {
+          // Build the array to avoid infinite loop
+          JsonArray array = new JsonArray();
+          @SuppressWarnings("unchecked")
+          Collection<EnumValueDescriptor> enumDescs =
+              (Collection<EnumValueDescriptor>) fieldPair.getValue();
+          for (EnumValueDescriptor enumDesc : enumDescs) {
+            array.add(context.serialize(getEnumValue(enumDesc)));
+            ret.add(name, array);
+          }
+        } else {
+          EnumValueDescriptor enumDesc = ((EnumValueDescriptor) fieldPair.getValue());
+          ret.add(name, context.serialize(getEnumValue(enumDesc)));
+        }
+      } else {
+        ret.add(name, context.serialize(fieldPair.getValue()));
+      }
+    }
+    return ret;
+  }
+
+  @Override
+  public Message deserialize(JsonElement json, Type typeOfT,
+      JsonDeserializationContext context) throws JsonParseException {
+    try {
+      JsonObject jsonObject = json.getAsJsonObject();
+      @SuppressWarnings("unchecked")
+      Class<? extends Message> protoClass = (Class<? extends Message>) typeOfT;
+
+      if (DynamicMessage.class.isAssignableFrom(protoClass)) {
+        throw new IllegalStateException("only generated messages are supported");
+      }
+
+      try {
+        // Invoke the ProtoClass.newBuilder() method
+        Message.Builder protoBuilder =
+            (Message.Builder) getCachedMethod(protoClass, "newBuilder").invoke(null);
+
+        Message defaultInstance =
+            (Message) getCachedMethod(protoClass, "getDefaultInstance").invoke(null);
+
+        Descriptor protoDescriptor =
+            (Descriptor) getCachedMethod(protoClass, "getDescriptor").invoke(null);
+        // Call setters on all of the available fields
+        for (FieldDescriptor fieldDescriptor : protoDescriptor.getFields()) {
+          String jsonFieldName =
+              getCustSerializedName(fieldDescriptor.getOptions(), fieldDescriptor.getName());
+
+          JsonElement jsonElement = jsonObject.get(jsonFieldName);
+          if (jsonElement != null && !jsonElement.isJsonNull()) {
+            // Do not reuse jsonFieldName here, it might have a custom value
+            Object fieldValue;
+            if (fieldDescriptor.getType() == ENUM_TYPE) {
+              if (jsonElement.isJsonArray()) {
+                // Handling array
+                Collection<EnumValueDescriptor> enumCollection =
+                    new ArrayList<>(jsonElement.getAsJsonArray().size());
+                for (JsonElement element : jsonElement.getAsJsonArray()) {
+                  enumCollection.add(
+                      findValueByNameAndExtension(fieldDescriptor.getEnumType(), element));
+                }
+                fieldValue = enumCollection;
+              } else {
+                // No array, just a plain value
+                fieldValue =
+                    findValueByNameAndExtension(fieldDescriptor.getEnumType(), jsonElement);
+              }
+              protoBuilder.setField(fieldDescriptor, fieldValue);
+            } else if (fieldDescriptor.isRepeated()) {
+              // If the type is an array, then we have to grab the type from the class.
+              // protobuf java field names are always lower camel case
+              String protoArrayFieldName =
+                  protoFormat.to(CaseFormat.LOWER_CAMEL, fieldDescriptor.getName()) + "_";
+              Field protoArrayField = protoClass.getDeclaredField(protoArrayFieldName);
+              Type protoArrayFieldType = protoArrayField.getGenericType();
+              fieldValue = context.deserialize(jsonElement, protoArrayFieldType);
+              protoBuilder.setField(fieldDescriptor, fieldValue);
+            } else {
+              Object field = defaultInstance.getField(fieldDescriptor);
+              fieldValue = context.deserialize(jsonElement, field.getClass());
+              protoBuilder.setField(fieldDescriptor, fieldValue);
+            }
+          }
+        }
+        return protoBuilder.build();
+      } catch (SecurityException e) {
+        throw new JsonParseException(e);
+      } catch (NoSuchMethodException e) {
+        throw new JsonParseException(e);
+      } catch (IllegalArgumentException e) {
+        throw new JsonParseException(e);
+      } catch (IllegalAccessException e) {
+        throw new JsonParseException(e);
+      } catch (InvocationTargetException e) {
+        throw new JsonParseException(e);
+      }
+    } catch (Exception e) {
+      throw new JsonParseException("Error while parsing proto", e);
+    }
+  }
+
+  /**
+   * Retrieves the custom field name from the given options, and if not found, returns the specified
+   * default name.
+   */
+  private String getCustSerializedName(FieldOptions options, String defaultName) {
+    for (Extension<FieldOptions, String> extension : serializedNameExtensions) {
+      if (options.hasExtension(extension)) {
+        return options.getExtension(extension);
+      }
+    }
+    return protoFormat.to(jsonFormat, defaultName);
+  }
+
+  /**
+   * Retrieves the custom enum value name from the given options, and if not found, returns the
+   * specified default value.
+   */
+  private String getCustSerializedEnumValue(EnumValueOptions options, String defaultValue) {
+    for (Extension<EnumValueOptions, String> extension : serializedEnumValueExtensions) {
+      if (options.hasExtension(extension)) {
+        return options.getExtension(extension);
+      }
+    }
+    return defaultValue;
+  }
+
+  /**
+   * Returns the enum value to use for serialization, depending on the value of
+   * {@link EnumSerialization} that was given to this adapter.
+   */
+  private Object getEnumValue(EnumValueDescriptor enumDesc) {
+    if (enumSerialization == EnumSerialization.NAME) {
+      return getCustSerializedEnumValue(enumDesc.getOptions(), enumDesc.getName());
+    } else {
+      return enumDesc.getNumber();
+    }
+  }
+
+  /**
+   * Finds an enum value in the given {@link EnumDescriptor} that matches the given JSON element,
+   * either by name if the current adapter is using {@link EnumSerialization#NAME}, otherwise by
+   * number. If matching by name, it uses the extension value if it is defined, otherwise it uses
+   * its default value.
+   *
+   * @throws IllegalArgumentException if a matching name/number was not found
+   */
+  private EnumValueDescriptor findValueByNameAndExtension(EnumDescriptor desc,
+      JsonElement jsonElement) {
+    if (enumSerialization == EnumSerialization.NAME) {
+      // With enum name
+      for (EnumValueDescriptor enumDesc : desc.getValues()) {
+        String enumValue = getCustSerializedEnumValue(enumDesc.getOptions(), enumDesc.getName());
+        if (enumValue.equals(jsonElement.getAsString())) {
+          return enumDesc;
+        }
+      }
+      throw new IllegalArgumentException(
+          String.format("Unrecognized enum name: %s", jsonElement.getAsString()));
+    } else {
+      // With enum value
+      EnumValueDescriptor fieldValue = desc.findValueByNumber(jsonElement.getAsInt());
+      if (fieldValue == null) {
+        throw new IllegalArgumentException(
+            String.format("Unrecognized enum value: %d", jsonElement.getAsInt()));
+      }
+      return fieldValue;
+    }
+  }
+
+  private static Method getCachedMethod(Class<?> clazz, String methodName,
+      Class<?>... methodParamTypes) throws NoSuchMethodException {
+    ConcurrentMap<Class<?>, Method> mapOfMethods = mapOfMapOfMethods.get(methodName);
+    if (mapOfMethods == null) {
+      mapOfMethods = new MapMaker().makeMap();
+      ConcurrentMap<Class<?>, Method> previous =
+          mapOfMapOfMethods.putIfAbsent(methodName, mapOfMethods);
+      mapOfMethods = previous == null ? mapOfMethods : previous;
+    }
+
+    Method method = mapOfMethods.get(clazz);
+    if (method == null) {
+      method = clazz.getMethod(methodName, methodParamTypes);
+      mapOfMethods.putIfAbsent(clazz, method);
+      // NB: it doesn't matter which method we return in the event of a race.
+    }
+    return method;
+  }
+
+}
diff --git a/proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithAnnotationsTest.java b/proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithAnnotationsTest.java
new file mode 100644
index 0000000..0a508f9
--- /dev/null
+++ b/proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithAnnotationsTest.java
@@ -0,0 +1,226 @@
+/*
+ * Copyright (C) 2010 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.protobuf.functional;
+
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
+import com.google.common.base.CaseFormat;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonParseException;
+import com.google.gson.protobuf.ProtoTypeAdapter;
+import com.google.gson.protobuf.ProtoTypeAdapter.EnumSerialization;
+import com.google.gson.protobuf.generated.Annotations;
+import com.google.gson.protobuf.generated.Bag.OuterMessage;
+import com.google.gson.protobuf.generated.Bag.ProtoWithAnnotations;
+import com.google.gson.protobuf.generated.Bag.ProtoWithAnnotations.InnerMessage;
+import com.google.gson.protobuf.generated.Bag.ProtoWithAnnotations.InnerMessage.Data;
+import com.google.gson.protobuf.generated.Bag.ProtoWithAnnotations.InnerMessage.Type;
+import com.google.protobuf.GeneratedMessageV3;
+import junit.framework.TestCase;
+
+/**
+ * Functional tests for protocol buffers using annotations for field names and enum values.
+ *
+ * @author Emmanuel Cron
+ */
+public class ProtosWithAnnotationsTest extends TestCase {
+  private Gson gson;
+  private Gson gsonWithEnumNumbers;
+  private Gson gsonWithLowerHyphen;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    ProtoTypeAdapter.Builder protoTypeAdapter = ProtoTypeAdapter.newBuilder()
+        .setEnumSerialization(EnumSerialization.NAME)
+        .addSerializedNameExtension(Annotations.serializedName)
+        .addSerializedEnumValueExtension(Annotations.serializedValue);
+    gson = new GsonBuilder()
+        .registerTypeHierarchyAdapter(GeneratedMessageV3.class, protoTypeAdapter.build())
+        .create();
+    gsonWithEnumNumbers = new GsonBuilder()
+        .registerTypeHierarchyAdapter(GeneratedMessageV3.class, protoTypeAdapter
+            .setEnumSerialization(EnumSerialization.NUMBER)
+            .build())
+        .create();
+    gsonWithLowerHyphen = new GsonBuilder()
+        .registerTypeHierarchyAdapter(GeneratedMessageV3.class, protoTypeAdapter
+            .setFieldNameSerializationFormat(CaseFormat.LOWER_UNDERSCORE, CaseFormat.LOWER_HYPHEN)
+            .build())
+        .create();
+  }
+
+  public void testProtoWithAnnotations_deserialize() {
+    String json = String.format("{  %n"
+        + "   \"id\":\"41e5e7fd6065d101b97018a465ffff01\",%n"
+        + "   \"expiration_date\":{  %n"
+        + "      \"month\":\"12\",%n"
+        + "      \"year\":\"2017\",%n"
+        + "      \"timeStamp\":\"9864653135687\",%n"
+        + "      \"countryCode5f55\":\"en_US\"%n"
+        + "   },%n"
+        // Don't define innerMessage1
+        + "   \"innerMessage2\":{  %n"
+        // Set a number as a string; it should work
+        + "      \"nIdCt\":\"98798465\",%n"
+        + "      \"content\":\"text/plain\",%n"
+        + "      \"$binary_data$\":[  %n"
+        + "         {  %n"
+        + "            \"data\":\"OFIN8e9fhwoeh8((⁹8efywoih\",%n"
+        // Don't define width
+        + "            \"height\":665%n"
+        + "         },%n"
+        + "         {  %n"
+        // Define as an int; it should work
+        + "            \"data\":65,%n"
+        + "            \"width\":-56684%n"
+        // Don't define height
+        + "         }%n"
+        + "      ]%n"
+        + "   },%n"
+        // Define a bunch of non recognizable data
+        + "   \"non_existing\":\"foobar\",%n"
+        + "   \"stillNot\":{  %n"
+        + "      \"bunch\":\"of_useless data\"%n"
+        + "   }%n"
+        + "}");
+    ProtoWithAnnotations proto = gson.fromJson(json, ProtoWithAnnotations.class);
+    assertThat(proto.getId()).isEqualTo("41e5e7fd6065d101b97018a465ffff01");
+    assertThat(proto.getOuterMessage()).isEqualTo(OuterMessage.newBuilder()
+        .setMonth(12)
+        .setYear(2017)
+        .setLongTimestamp(9864653135687L)
+        .setCountryCode5F55("en_US")
+        .build());
+    assertThat(proto.hasInnerMessage1()).isFalse();
+    assertThat(proto.getInnerMessage2()).isEqualTo(InnerMessage.newBuilder()
+        .setNIdCt(98798465)
+        .setContent(Type.TEXT)
+        .addData(Data.newBuilder()
+            .setData("OFIN8e9fhwoeh8((⁹8efywoih")
+            .setHeight(665))
+        .addData(Data.newBuilder()
+            .setData("65")
+            .setWidth(-56684))
+        .build());
+
+    String rebuilt = gson.toJson(proto);
+    assertThat(rebuilt).isEqualTo("{"
+        + "\"id\":\"41e5e7fd6065d101b97018a465ffff01\","
+        + "\"expiration_date\":{"
+        + "\"month\":12,"
+        + "\"year\":2017,"
+        + "\"timeStamp\":9864653135687,"
+        + "\"countryCode5f55\":\"en_US\""
+        + "},"
+        + "\"innerMessage2\":{"
+        + "\"nIdCt\":98798465,"
+        + "\"content\":\"text/plain\","
+        + "\"$binary_data$\":["
+        + "{"
+        + "\"data\":\"OFIN8e9fhwoeh8((⁹8efywoih\","
+        + "\"height\":665"
+        + "},"
+        + "{"
+        + "\"data\":\"65\","
+        + "\"width\":-56684"
+        + "}]}}");
+  }
+
+  public void testProtoWithAnnotations_deserializeUnknownEnumValue() {
+    String json = String.format("{  %n"
+        + "   \"content\":\"UNKNOWN\"%n"
+        + "}");
+    InnerMessage proto = gson.fromJson(json, InnerMessage.class);
+    assertThat(proto.getContent()).isEqualTo(Type.UNKNOWN);
+  }
+
+  public void testProtoWithAnnotations_deserializeUnrecognizedEnumValue() {
+    String json = String.format("{  %n"
+        + "   \"content\":\"UNRECOGNIZED\"%n"
+        + "}");
+    try {
+      gson.fromJson(json, InnerMessage.class);
+      assertWithMessage("Should have thrown").fail();
+    } catch (JsonParseException e) {
+      // expected
+    }
+  }
+
+  public void testProtoWithAnnotations_deserializeWithEnumNumbers() {
+    String json = String.format("{  %n"
+        + "   \"content\":\"0\"%n"
+        + "}");
+    InnerMessage proto = gsonWithEnumNumbers.fromJson(json, InnerMessage.class);
+    assertThat(proto.getContent()).isEqualTo(Type.UNKNOWN);
+    String rebuilt = gsonWithEnumNumbers.toJson(proto);
+    assertThat(rebuilt).isEqualTo("{\"content\":0}");
+
+    json = String.format("{  %n"
+        + "   \"content\":\"2\"%n"
+        + "}");
+    proto = gsonWithEnumNumbers.fromJson(json, InnerMessage.class);
+    assertThat(proto.getContent()).isEqualTo(Type.IMAGE);
+    rebuilt = gsonWithEnumNumbers.toJson(proto);
+    assertThat(rebuilt).isEqualTo("{\"content\":2}");
+  }
+
+  public void testProtoWithAnnotations_serialize() {
+    ProtoWithAnnotations proto = ProtoWithAnnotations.newBuilder()
+        .setId("09f3j20839h032y0329hf30932h0nffn")
+        .setOuterMessage(OuterMessage.newBuilder()
+            .setMonth(14)
+            .setYear(6650)
+            .setLongTimestamp(468406876880768L))
+        .setInnerMessage1(InnerMessage.newBuilder()
+            .setNIdCt(12)
+            .setContent(Type.IMAGE)
+            .addData(Data.newBuilder()
+                .setData("data$$")
+                .setWidth(200))
+            .addData(Data.newBuilder()
+                .setHeight(56)))
+        .build();
+
+    String json = gsonWithLowerHyphen.toJson(proto);
+    assertThat(json).isEqualTo(
+        "{\"id\":\"09f3j20839h032y0329hf30932h0nffn\","
+        + "\"expiration_date\":{"
+            + "\"month\":14,"
+            + "\"year\":6650,"
+            + "\"timeStamp\":468406876880768"
+        + "},"
+        // This field should be using hyphens
+        + "\"inner-message-1\":{"
+            + "\"n--id-ct\":12,"
+            + "\"content\":2,"
+            + "\"$binary_data$\":["
+              + "{"
+                  + "\"data\":\"data$$\","
+                  + "\"width\":200"
+              + "},"
+              + "{"
+                  + "\"height\":56"
+              + "}]"
+            + "}"
+        + "}");
+
+    ProtoWithAnnotations rebuilt = gsonWithLowerHyphen.fromJson(json, ProtoWithAnnotations.class);
+    assertThat(rebuilt).isEqualTo(proto);
+  }
+}
diff --git a/proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithComplexAndRepeatedFieldsTest.java b/proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithComplexAndRepeatedFieldsTest.java
new file mode 100644
index 0000000..8e59d5d
--- /dev/null
+++ b/proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithComplexAndRepeatedFieldsTest.java
@@ -0,0 +1,100 @@
+/*
+ * Copyright (C) 2010 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.protobuf.functional;
+
+import com.google.common.base.CaseFormat;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonObject;
+import com.google.gson.protobuf.ProtoTypeAdapter;
+import com.google.gson.protobuf.ProtoTypeAdapter.EnumSerialization;
+import com.google.gson.protobuf.generated.Bag.ProtoWithDifferentCaseFormat;
+import com.google.gson.protobuf.generated.Bag.ProtoWithRepeatedFields;
+import com.google.gson.protobuf.generated.Bag.SimpleProto;
+import com.google.protobuf.GeneratedMessageV3;
+import junit.framework.TestCase;
+
+/**
+ * Functional tests for protocol buffers using complex and repeated fields
+ *
+ * @author Inderjeet Singh
+ */
+public class ProtosWithComplexAndRepeatedFieldsTest extends TestCase {
+  private Gson gson;
+  private Gson upperCamelGson;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    gson =
+        new GsonBuilder()
+            .registerTypeHierarchyAdapter(GeneratedMessageV3.class,
+                ProtoTypeAdapter.newBuilder()
+                    .setEnumSerialization(EnumSerialization.NUMBER)
+                    .build())
+            .create();
+    upperCamelGson =
+        new GsonBuilder()
+            .registerTypeHierarchyAdapter(
+                GeneratedMessageV3.class, ProtoTypeAdapter.newBuilder()
+                    .setFieldNameSerializationFormat(
+                        CaseFormat.LOWER_UNDERSCORE, CaseFormat.UPPER_CAMEL)
+                    .build())
+            .create();
+  }
+
+  public void testSerializeRepeatedFields() {
+    ProtoWithRepeatedFields proto = ProtoWithRepeatedFields.newBuilder()
+      .addNumbers(2)
+      .addNumbers(3)
+      .addSimples(SimpleProto.newBuilder().setMsg("foo").build())
+      .addSimples(SimpleProto.newBuilder().setCount(3).build())
+      .build();
+    String json = gson.toJson(proto);
+    assertTrue(json.contains("[2,3]"));
+    assertTrue(json.contains("foo"));
+    assertTrue(json.contains("count"));
+  }
+
+  public void testDeserializeRepeatedFieldsProto() {
+    String json = "{numbers:[4,6],simples:[{msg:'bar'},{count:7}]}";
+    ProtoWithRepeatedFields proto =
+      gson.fromJson(json, ProtoWithRepeatedFields.class);
+    assertEquals(4, proto.getNumbers(0));
+    assertEquals(6, proto.getNumbers(1));
+    assertEquals("bar", proto.getSimples(0).getMsg());
+    assertEquals(7, proto.getSimples(1).getCount());
+  }
+
+  public void testSerializeDifferentCaseFormat() {
+    final ProtoWithDifferentCaseFormat proto =
+      ProtoWithDifferentCaseFormat.newBuilder()
+        .setAnotherField("foo")
+        .addNameThatTestsCaseFormat("bar")
+        .build();
+    final JsonObject json = upperCamelGson.toJsonTree(proto).getAsJsonObject();
+    assertEquals("foo", json.get("AnotherField").getAsString());
+    assertEquals("bar", json.get("NameThatTestsCaseFormat").getAsJsonArray().get(0).getAsString());
+  }
+
+  public void testDeserializeDifferentCaseFormat() {
+    final String json = "{NameThatTestsCaseFormat:['bar'],AnotherField:'foo'}";
+    ProtoWithDifferentCaseFormat proto =
+      upperCamelGson.fromJson(json, ProtoWithDifferentCaseFormat.class);
+    assertEquals("foo", proto.getAnotherField());
+    assertEquals("bar", proto.getNameThatTestsCaseFormat(0));
+  }
+}
diff --git a/proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithPrimitiveTypesTest.java b/proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithPrimitiveTypesTest.java
new file mode 100644
index 0000000..2e9d0e1
--- /dev/null
+++ b/proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithPrimitiveTypesTest.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright (C) 2010 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.google.gson.protobuf.functional;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.protobuf.ProtoTypeAdapter;
+import com.google.gson.protobuf.ProtoTypeAdapter.EnumSerialization;
+import com.google.gson.protobuf.generated.Bag.SimpleProto;
+import com.google.protobuf.Descriptors.Descriptor;
+import com.google.protobuf.GeneratedMessageV3;
+import junit.framework.TestCase;
+
+public class ProtosWithPrimitiveTypesTest extends TestCase {
+  private Gson gson;
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    gson = new GsonBuilder().registerTypeHierarchyAdapter(
+      GeneratedMessageV3.class, ProtoTypeAdapter.newBuilder()
+          .setEnumSerialization(EnumSerialization.NUMBER)
+          .build())
+      .create();
+  }
+
+  public void testSerializeEmptyProto() {
+    SimpleProto proto = SimpleProto.newBuilder().build();
+    String json = gson.toJson(proto);
+    assertEquals("{}", json);
+  }
+
+  public void testDeserializeEmptyProto() {
+    SimpleProto proto = gson.fromJson("{}", SimpleProto.class);
+    assertFalse(proto.hasCount());
+    assertFalse(proto.hasMsg());
+  }
+
+  public void testSerializeProto() {
+    Descriptor descriptor = SimpleProto.getDescriptor();
+    SimpleProto proto = SimpleProto.newBuilder()
+      .setCount(3)
+      .setMsg("foo")
+      .build();
+    String json = gson.toJson(proto);
+    assertTrue(json.contains("\"msg\":\"foo\""));
+    assertTrue(json.contains("\"count\":3"));
+  }
+
+  public void testDeserializeProto() {
+    SimpleProto proto = gson.fromJson("{msg:'foo',count:3}", SimpleProto.class);
+    assertEquals("foo", proto.getMsg());
+    assertEquals(3, proto.getCount());
+  }
+
+  public void testDeserializeWithExplicitNullValue() {
+    SimpleProto proto = gson.fromJson("{msg:'foo',count:null}", SimpleProto.class);
+    assertEquals("foo", proto.getMsg());
+    assertEquals(0, proto.getCount());
+  }
+
+}
diff --git a/proto/src/test/proto/annotations.proto b/proto/src/test/proto/annotations.proto
new file mode 100644
index 0000000..53b727a
--- /dev/null
+++ b/proto/src/test/proto/annotations.proto
@@ -0,0 +1,32 @@
+//
+// Copyright (C) 2010 Google Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+syntax = "proto2";
+
+package google.gson.protobuf.generated;
+option java_package = "com.google.gson.protobuf.generated";
+
+import "google/protobuf/descriptor.proto";
+
+extend google.protobuf.FieldOptions {
+  // Indicates a field name that overrides the default for serialization
+  optional string serialized_name = 92066888;
+}
+
+extend google.protobuf.EnumValueOptions {
+  // Indicates a field value that overrides the default for serialization
+  optional string serialized_value = 92066888;
+}
diff --git a/proto/src/test/proto/bag.proto b/proto/src/test/proto/bag.proto
new file mode 100644
index 0000000..3e4769e
--- /dev/null
+++ b/proto/src/test/proto/bag.proto
@@ -0,0 +1,72 @@
+//
+// Copyright (C) 2010 Google Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+syntax = "proto2";
+
+package google.gson.protobuf.generated;
+option java_package = "com.google.gson.protobuf.generated";
+
+import "annotations.proto";
+
+message SimpleProto {
+  optional string msg = 1;
+  optional int32 count = 2;
+}
+
+message ProtoWithDifferentCaseFormat {
+  repeated string name_that_tests_case_format = 1;
+  optional string another_field = 2;
+}
+
+message ProtoWithRepeatedFields {
+  repeated int64 numbers = 1;
+  repeated SimpleProto simples = 2;
+  optional string name = 3;
+}
+
+// -- A more complex message with annotations and nested protos
+
+message OuterMessage {
+  optional int32 month = 1;
+  optional int32 year = 2;
+  optional int64 long_timestamp = 3 [(serialized_name) = "timeStamp"];
+  optional string country_code_5f55 = 4;
+}
+
+message ProtoWithAnnotations {
+  optional string id = 1;
+  optional OuterMessage outer_message = 2 [(serialized_name) = "expiration_date"];
+
+  message InnerMessage {
+    optional int32 n__id_ct = 1;
+
+    enum Type {
+      UNKNOWN = 0;
+      TEXT = 1 [(serialized_value) = "text/plain"];
+      IMAGE = 2 [(serialized_value) = "image/png"];
+    }
+    optional Type content = 2;
+
+    message Data {
+      optional string data = 1;
+      optional int32 width = 2;
+      optional int32 height = 3;
+    }
+    repeated Data data = 3 [(serialized_name) = "$binary_data$"];
+  }
+  optional InnerMessage inner_message_1 = 3;
+  optional InnerMessage inner_message_2 = 4;
+}
\ No newline at end of file
diff --git a/version_generator.py b/version_generator.py
new file mode 100755
index 0000000..dbffca8
--- /dev/null
+++ b/version_generator.py
@@ -0,0 +1,34 @@
+#!/usr/bin/python3
+
+# Copyright (C) 2022 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Script that generates the GsonBuildConfig.java file based on the version in
+# pom.xml. It expects paths to pom.xml and the GsonBuildConfig.java template as
+# arguments in any order. It emits the finished file to the standard output.
+
+import sys
+import xml.etree.ElementTree as ET
+
+
+def main():
+  pom_path = next(path for path in sys.argv[1:] if path.endswith(".xml"))
+  java_path = next(path for path in sys.argv[1:] if path.endswith(".java"))
+  pom_file = open(pom_path, "r")
+  pom_xml = ET.parse(pom_file)
+  version = pom_xml.getroot().find("{http://maven.apache.org/POM/4.0.0}version").text
+  java_file = open(java_path, "r")
+  print(java_file.read().replace("${project.version}", version))
+
+main()