Repository: google/gson Branch: main Commit: 1fa9b7a0a994 Files: 305 Total size: 2.1 MB Directory structure: gitextract_4tdusv9e/ ├── .git-blame-ignore-revs ├── .github/ │ ├── ISSUE_TEMPLATE/ │ │ ├── bug_report.md │ │ ├── config.yml │ │ └── feature_request.md │ ├── dependabot.yml │ ├── pull_request_template.md │ └── workflows/ │ ├── build.yml │ ├── check-android-compatibility.yml │ ├── check-api-compatibility.yml │ ├── cifuzz.yml │ ├── codeql-analysis.yml │ └── scorecard.yml ├── .gitignore ├── .mvn/ │ └── jvm.config ├── CHANGELOG.md ├── GsonDesignDocument.md ├── LICENSE ├── README.md ├── ReleaseProcess.md ├── Troubleshooting.md ├── UserGuide.md ├── extras/ │ ├── README.md │ ├── pom.xml │ └── src/ │ ├── main/ │ │ └── java/ │ │ └── com/ │ │ └── google/ │ │ └── gson/ │ │ ├── extras/ │ │ │ └── examples/ │ │ │ └── rawcollections/ │ │ │ └── RawCollectionsExample.java │ │ ├── interceptors/ │ │ │ ├── Intercept.java │ │ │ ├── InterceptorFactory.java │ │ │ └── JsonPostDeserializer.java │ │ └── typeadapters/ │ │ ├── PostConstructAdapterFactory.java │ │ ├── RuntimeTypeAdapterFactory.java │ │ └── UtcDateTypeAdapter.java │ └── test/ │ └── java/ │ └── com/ │ └── google/ │ └── gson/ │ ├── interceptors/ │ │ └── InterceptorTest.java │ └── typeadapters/ │ ├── PostConstructAdapterFactoryTest.java │ ├── RuntimeTypeAdapterFactoryTest.java │ └── UtcDateTypeAdapterTest.java ├── gson/ │ ├── LICENSE │ ├── README.md │ ├── pom.xml │ └── src/ │ ├── main/ │ │ ├── java/ │ │ │ ├── com/ │ │ │ │ └── google/ │ │ │ │ └── gson/ │ │ │ │ ├── ExclusionStrategy.java │ │ │ │ ├── FieldAttributes.java │ │ │ │ ├── FieldNamingPolicy.java │ │ │ │ ├── FieldNamingStrategy.java │ │ │ │ ├── FormattingStyle.java │ │ │ │ ├── Gson.java │ │ │ │ ├── GsonBuilder.java │ │ │ │ ├── InstanceCreator.java │ │ │ │ ├── JsonArray.java │ │ │ │ ├── JsonDeserializationContext.java │ │ │ │ ├── JsonDeserializer.java │ │ │ │ ├── JsonElement.java │ │ │ │ ├── JsonIOException.java │ │ │ │ ├── JsonNull.java │ │ │ │ ├── JsonObject.java │ │ │ │ ├── JsonParseException.java │ │ │ │ ├── JsonParser.java │ │ │ │ ├── JsonPrimitive.java │ │ │ │ ├── JsonSerializationContext.java │ │ │ │ ├── JsonSerializer.java │ │ │ │ ├── JsonStreamParser.java │ │ │ │ ├── JsonSyntaxException.java │ │ │ │ ├── LongSerializationPolicy.java │ │ │ │ ├── ReflectionAccessFilter.java │ │ │ │ ├── Strictness.java │ │ │ │ ├── ToNumberPolicy.java │ │ │ │ ├── ToNumberStrategy.java │ │ │ │ ├── TypeAdapter.java │ │ │ │ ├── TypeAdapterFactory.java │ │ │ │ ├── annotations/ │ │ │ │ │ ├── Expose.java │ │ │ │ │ ├── JsonAdapter.java │ │ │ │ │ ├── SerializedName.java │ │ │ │ │ ├── Since.java │ │ │ │ │ ├── Until.java │ │ │ │ │ └── package-info.java │ │ │ │ ├── internal/ │ │ │ │ │ ├── ConstructorConstructor.java │ │ │ │ │ ├── Excluder.java │ │ │ │ │ ├── GsonTypes.java │ │ │ │ │ ├── JavaVersion.java │ │ │ │ │ ├── JsonReaderInternalAccess.java │ │ │ │ │ ├── LazilyParsedNumber.java │ │ │ │ │ ├── LinkedTreeMap.java │ │ │ │ │ ├── NonNullElementWrapperList.java │ │ │ │ │ ├── NumberLimits.java │ │ │ │ │ ├── ObjectConstructor.java │ │ │ │ │ ├── PreJava9DateFormatProvider.java │ │ │ │ │ ├── Primitives.java │ │ │ │ │ ├── ReflectionAccessFilterHelper.java │ │ │ │ │ ├── Streams.java │ │ │ │ │ ├── TroubleshootingGuide.java │ │ │ │ │ ├── UnsafeAllocator.java │ │ │ │ │ ├── bind/ │ │ │ │ │ │ ├── ArrayTypeAdapter.java │ │ │ │ │ │ ├── CollectionTypeAdapterFactory.java │ │ │ │ │ │ ├── DefaultDateTypeAdapter.java │ │ │ │ │ │ ├── EnumTypeAdapter.java │ │ │ │ │ │ ├── IgnoreJRERequirement.java │ │ │ │ │ │ ├── JavaTimeTypeAdapters.java │ │ │ │ │ │ ├── JsonAdapterAnnotationTypeAdapterFactory.java │ │ │ │ │ │ ├── JsonElementTypeAdapter.java │ │ │ │ │ │ ├── JsonTreeReader.java │ │ │ │ │ │ ├── JsonTreeWriter.java │ │ │ │ │ │ ├── MapTypeAdapterFactory.java │ │ │ │ │ │ ├── NumberTypeAdapter.java │ │ │ │ │ │ ├── ObjectTypeAdapter.java │ │ │ │ │ │ ├── ReflectiveTypeAdapterFactory.java │ │ │ │ │ │ ├── SerializationDelegatingTypeAdapter.java │ │ │ │ │ │ ├── TreeTypeAdapter.java │ │ │ │ │ │ ├── TypeAdapterRuntimeTypeWrapper.java │ │ │ │ │ │ ├── TypeAdapters.java │ │ │ │ │ │ └── util/ │ │ │ │ │ │ └── ISO8601Utils.java │ │ │ │ │ ├── package-info.java │ │ │ │ │ ├── reflect/ │ │ │ │ │ │ └── ReflectionHelper.java │ │ │ │ │ └── sql/ │ │ │ │ │ ├── SqlDateTypeAdapter.java │ │ │ │ │ ├── SqlTimeTypeAdapter.java │ │ │ │ │ ├── SqlTimestampTypeAdapter.java │ │ │ │ │ └── SqlTypesSupport.java │ │ │ │ ├── package-info.java │ │ │ │ ├── reflect/ │ │ │ │ │ ├── TypeToken.java │ │ │ │ │ └── package-info.java │ │ │ │ └── stream/ │ │ │ │ ├── JsonReader.java │ │ │ │ ├── JsonScope.java │ │ │ │ ├── JsonToken.java │ │ │ │ ├── JsonWriter.java │ │ │ │ ├── MalformedJsonException.java │ │ │ │ └── package-info.java │ │ │ └── module-info.java │ │ ├── java-templates/ │ │ │ └── com/ │ │ │ └── google/ │ │ │ └── gson/ │ │ │ └── internal/ │ │ │ └── GsonBuildConfig.java │ │ └── resources/ │ │ └── META-INF/ │ │ └── proguard/ │ │ └── gson.pro │ └── test/ │ ├── java/ │ │ └── com/ │ │ └── google/ │ │ └── gson/ │ │ ├── CommentsTest.java │ │ ├── DefaultInetAddressTypeAdapterTest.java │ │ ├── DefaultMapJsonSerializerTest.java │ │ ├── ExposeAnnotationExclusionStrategyTest.java │ │ ├── FieldAttributesTest.java │ │ ├── FieldNamingPolicyTest.java │ │ ├── GenericArrayTypeTest.java │ │ ├── GsonBuilderTest.java │ │ ├── GsonTest.java │ │ ├── GsonTypeAdapterTest.java │ │ ├── InnerClassExclusionStrategyTest.java │ │ ├── JavaSerializationTest.java │ │ ├── JsonArrayAsListSuiteTest.java │ │ ├── JsonArrayAsListTest.java │ │ ├── JsonArrayTest.java │ │ ├── JsonNullTest.java │ │ ├── JsonObjectAsMapSuiteTest.java │ │ ├── JsonObjectAsMapTest.java │ │ ├── JsonObjectTest.java │ │ ├── JsonParserParameterizedTest.java │ │ ├── JsonParserTest.java │ │ ├── JsonPrimitiveTest.java │ │ ├── JsonStreamParserTest.java │ │ ├── LongSerializationPolicyTest.java │ │ ├── MixedStreamTest.java │ │ ├── ObjectTypeAdapterParameterizedTest.java │ │ ├── ObjectTypeAdapterTest.java │ │ ├── OverrideCoreTypeAdaptersTest.java │ │ ├── ParameterizedTypeFixtures.java │ │ ├── ParameterizedTypeTest.java │ │ ├── PrimitiveTypeAdapter.java │ │ ├── SubsetTest.java │ │ ├── ToNumberPolicyTest.java │ │ ├── TypeAdapterTest.java │ │ ├── VersionExclusionStrategyTest.java │ │ ├── common/ │ │ │ ├── MoreAsserts.java │ │ │ └── TestTypes.java │ │ ├── functional/ │ │ │ ├── ArrayTest.java │ │ │ ├── CircularReferenceTest.java │ │ │ ├── CollectionTest.java │ │ │ ├── ConcurrencyTest.java │ │ │ ├── CustomDeserializerTest.java │ │ │ ├── CustomSerializerTest.java │ │ │ ├── CustomTypeAdaptersTest.java │ │ │ ├── DefaultTypeAdaptersTest.java │ │ │ ├── DelegateTypeAdapterTest.java │ │ │ ├── EnumTest.java │ │ │ ├── EnumWithObfuscatedTest.java │ │ │ ├── EscapingTest.java │ │ │ ├── ExclusionStrategyFunctionalTest.java │ │ │ ├── ExposeFieldsTest.java │ │ │ ├── FieldExclusionTest.java │ │ │ ├── FieldNamingTest.java │ │ │ ├── FormattingStyleTest.java │ │ │ ├── GsonVersionDiagnosticsTest.java │ │ │ ├── InheritanceTest.java │ │ │ ├── InstanceCreatorTest.java │ │ │ ├── InterfaceTest.java │ │ │ ├── InternationalizationTest.java │ │ │ ├── Java17RecordTest.java │ │ │ ├── JavaUtilConcurrentAtomicTest.java │ │ │ ├── JavaUtilTest.java │ │ │ ├── JsonAdapterAnnotationOnClassesTest.java │ │ │ ├── JsonAdapterAnnotationOnFieldsTest.java │ │ │ ├── JsonAdapterSerializerDeserializerTest.java │ │ │ ├── JsonParserTest.java │ │ │ ├── JsonTreeTest.java │ │ │ ├── LeniencyTest.java │ │ │ ├── MapAsArrayTypeAdapterTest.java │ │ │ ├── MapTest.java │ │ │ ├── MoreSpecificTypeSerializationTest.java │ │ │ ├── NamingPolicyTest.java │ │ │ ├── NullObjectAndFieldTest.java │ │ │ ├── NumberLimitsTest.java │ │ │ ├── ObjectTest.java │ │ │ ├── ParameterizedTypesTest.java │ │ │ ├── PrettyPrintingTest.java │ │ │ ├── PrimitiveCharacterTest.java │ │ │ ├── PrimitiveTest.java │ │ │ ├── PrintFormattingTest.java │ │ │ ├── RawSerializationTest.java │ │ │ ├── ReadersWritersTest.java │ │ │ ├── ReflectionAccessFilterTest.java │ │ │ ├── ReflectionAccessTest.java │ │ │ ├── ReusedTypeVariablesFullyResolveTest.java │ │ │ ├── RuntimeTypeAdapterFactoryFunctionalTest.java │ │ │ ├── SecurityTest.java │ │ │ ├── SerializedNameTest.java │ │ │ ├── StreamingTypeAdaptersTest.java │ │ │ ├── StringTest.java │ │ │ ├── ToNumberPolicyFunctionalTest.java │ │ │ ├── TreeTypeAdaptersTest.java │ │ │ ├── TypeAdapterPrecedenceTest.java │ │ │ ├── TypeAdapterRuntimeTypeWrapperTest.java │ │ │ ├── TypeHierarchyAdapterTest.java │ │ │ ├── TypeVariableTest.java │ │ │ ├── UncategorizedTest.java │ │ │ └── VersioningTest.java │ │ ├── integration/ │ │ │ └── OSGiManifestIT.java │ │ ├── internal/ │ │ │ ├── ConstructorConstructorTest.java │ │ │ ├── GsonBuildConfigTest.java │ │ │ ├── GsonTypesTest.java │ │ │ ├── JavaVersionTest.java │ │ │ ├── LazilyParsedNumberTest.java │ │ │ ├── LinkedTreeMapSuiteTest.java │ │ │ ├── LinkedTreeMapTest.java │ │ │ ├── StreamsTest.java │ │ │ ├── UnsafeAllocatorInstantiationTest.java │ │ │ ├── bind/ │ │ │ │ ├── DefaultDateTypeAdapterTest.java │ │ │ │ ├── Java17ReflectiveTypeAdapterFactoryTest.java │ │ │ │ ├── JsonElementReaderTest.java │ │ │ │ ├── JsonTreeReaderTest.java │ │ │ │ ├── JsonTreeWriterTest.java │ │ │ │ ├── RecursiveTypesResolveTest.java │ │ │ │ └── util/ │ │ │ │ └── ISO8601UtilsTest.java │ │ │ ├── reflect/ │ │ │ │ └── Java17ReflectionHelperTest.java │ │ │ └── sql/ │ │ │ ├── SqlTypesGsonTest.java │ │ │ └── SqlTypesSupportTest.java │ │ ├── metrics/ │ │ │ └── PerformanceTest.java │ │ ├── reflect/ │ │ │ └── TypeTokenTest.java │ │ └── stream/ │ │ ├── JsonReaderPathTest.java │ │ ├── JsonReaderTest.java │ │ └── JsonWriterTest.java │ └── resources/ │ └── testcases-proguard.conf ├── metrics/ │ ├── README.md │ ├── pom.xml │ └── src/ │ └── main/ │ └── java/ │ └── com/ │ └── google/ │ └── gson/ │ └── metrics/ │ ├── BagOfPrimitives.java │ ├── BagOfPrimitivesDeserializationBenchmark.java │ ├── CollectionsDeserializationBenchmark.java │ ├── NonUploadingCaliperRunner.java │ ├── ParseBenchmark.java │ └── SerializationBenchmark.java ├── pom.xml ├── proto/ │ ├── .gitignore │ ├── README.md │ ├── pom.xml │ └── src/ │ ├── main/ │ │ └── java/ │ │ └── com/ │ │ └── google/ │ │ └── gson/ │ │ └── protobuf/ │ │ └── ProtoTypeAdapter.java │ └── test/ │ ├── java/ │ │ └── com/ │ │ └── google/ │ │ └── gson/ │ │ └── protobuf/ │ │ └── functional/ │ │ ├── ProtosWithAnnotationsAndJsonNamesTest.java │ │ ├── ProtosWithAnnotationsTest.java │ │ ├── ProtosWithComplexAndRepeatedFieldsTest.java │ │ └── ProtosWithPrimitiveTypesTest.java │ └── protobuf/ │ ├── annotations.proto │ └── bag.proto ├── test-graal-native-image/ │ ├── README.md │ ├── pom.xml │ └── src/ │ └── test/ │ ├── java/ │ │ └── com/ │ │ └── google/ │ │ └── gson/ │ │ └── native_test/ │ │ ├── Java17RecordReflectionTest.java │ │ └── ReflectionTest.java │ └── resources/ │ └── META-INF/ │ └── native-image/ │ └── reflect-config.json ├── test-jpms/ │ ├── README.md │ ├── pom.xml │ └── src/ │ ├── main/ │ │ └── java/ │ │ └── module-info.java │ └── test/ │ └── java/ │ ├── com/ │ │ └── google/ │ │ └── gson/ │ │ └── jpms_test/ │ │ ├── ExportedPackagesTest.java │ │ ├── ModuleTest.java │ │ ├── ReflectionInaccessibleTest.java │ │ └── opened/ │ │ └── ReflectionTest.java │ └── module-info.java └── test-shrinker/ ├── README.md ├── common.pro ├── pom.xml ├── proguard.pro ├── r8.pro └── src/ ├── main/ │ └── java/ │ └── com/ │ └── example/ │ ├── ClassWithAdapter.java │ ├── ClassWithExposeAnnotation.java │ ├── ClassWithHasArgsConstructor.java │ ├── ClassWithJsonAdapterAnnotation.java │ ├── ClassWithNamedFields.java │ ├── ClassWithNoArgsConstructor.java │ ├── ClassWithSerializedName.java │ ├── ClassWithUnreferencedHasArgsConstructor.java │ ├── ClassWithUnreferencedNoArgsConstructor.java │ ├── ClassWithVersionAnnotations.java │ ├── EnumClass.java │ ├── EnumClassWithSerializedName.java │ ├── GenericClasses.java │ ├── InterfaceWithImplementation.java │ ├── Main.java │ ├── NoSerializedNameMain.java │ ├── TestExecutor.java │ └── UnusedClass.java └── test/ └── java/ └── com/ └── google/ └── gson/ └── it/ └── ShrinkingIT.java ================================================ FILE CONTENTS ================================================ ================================================ FILE: .git-blame-ignore-revs ================================================ # Ignore commit which reformatted code 2c94c757a6a9426cc2fe47bc1c63f69e7c73b7b4 # Ignore commit which changed line endings consistently to LF c2a0e4634a2100494159add78db2ee06f5eb9be6 ================================================ FILE: .github/ISSUE_TEMPLATE/bug_report.md ================================================ --- name: Bug report about: Report a Gson bug. Please have a look at the troubleshooting guide (Troubleshooting.md) first. title: '' labels: bug assignees: '' --- # Gson version # Java / Android version # Used tools - [ ] Maven; version: - [ ] Gradle; version: - [ ] ProGuard (attach the configuration file please); version: - [ ] ... # Description ## Expected behavior ## Actual behavior # Reproduction steps 1. ... 2. ... # Exception stack trace ``` ``` ================================================ FILE: .github/ISSUE_TEMPLATE/config.yml ================================================ contact_links: - name: Usage question url: https://stackoverflow.com/questions/tagged/gson about: Ask usage questions on StackOverflow. - name: Questions, ideas, tips & tricks, ... url: https://github.com/google/gson/discussions about: Share information in GitHub Discussions. ================================================ FILE: .github/ISSUE_TEMPLATE/feature_request.md ================================================ --- 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 # Feature description # Alternatives / workarounds ================================================ FILE: .github/dependabot.yml ================================================ version: 2 updates: - package-ecosystem: "maven" directory: "/" schedule: interval: "monthly" cooldown: default-days: 14 groups: # Name is used for branch name and pull request title maven: patterns: # Create a single pull request for all dependencies and plugins - "*" - package-ecosystem: "github-actions" directory: "/" schedule: interval: "monthly" cooldown: default-days: 14 groups: # Name is used for branch name and pull request title github-actions: patterns: # Create a single pull request for all actions - "*" ================================================ FILE: .github/pull_request_template.md ================================================ ### Purpose ### Description ### Checklist - [ ] New code follows the [Google Java Style Guide](https://google.github.io/styleguide/javaguide.html)\ This is automatically checked by `mvn verify`, but can also be checked on its own using `mvn spotless:check`.\ Style violations can be fixed using `mvn spotless:apply`; this can be done in a separate commit to verify that it did not cause undesired changes. - [ ] If necessary, new public API validates arguments, for example rejects `null` - [ ] New public API has Javadoc - [ ] Javadoc uses `@since $next-version$` (`$next-version$` is a special placeholder which is automatically replaced during release) - [ ] If necessary, new unit tests have been added - [ ] Assertions in unit tests use [Truth](https://truth.dev/), see existing tests - [ ] No JUnit 3 features are used (such as extending class `TestCase`) - [ ] If this pull request fixes a bug, a new test was added for a situation which failed previously and is now fixed - [ ] `mvn clean verify javadoc:jar` passes without errors ================================================ FILE: .github/workflows/build.yml ================================================ name: Build on: push: branches-ignore: # Ignore Dependabot branches because it will also open a pull request, which would cause the # workflow to redundantly run twice - dependabot/** pull_request: permissions: contents: read # to fetch code (actions/checkout) env: # Common Maven arguments MAVEN_ARGS: --show-version --batch-mode --no-transfer-progress jobs: build: name: "Build on JDK ${{ matrix.java }}" strategy: matrix: java: [ 17, 21 ] include: # Custom JDK 11 configuration because some of the plugins and test dependencies don't support it anymore, # but it is important to still test with a JDK version without Record classes - java: 11 # Disable Enforcer check which (intentionally) prevents using JDK 11 for building # Exclude 'test-graal-native-image' module because JUnit 6 requires >= Java 17 # Exclude 'proto' module because protobuf-maven-plugin requires >= Java 17 extra-mvn-args: -Denforcer.fail=false --projects '!test-graal-native-image,!proto' - java: 25 # Disable Enforcer check which (intentionally) prevents using JDK 25 for building # Exclude 'test-shrinker' because ProGuard does not support JDK 25 yet, see # https://github.com/Guardsquare/proguard/issues/481 and https://github.com/Guardsquare/proguard/issues/473 # TODO: Once ProGuard supports JDK 25, also remove the corresponding 'JDK25' profile in `gson/pom.xml` extra-mvn-args: -Denforcer.fail=false --projects '!test-shrinker' runs-on: ubuntu-latest steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: "Set up JDK ${{ matrix.java }}" uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0 with: distribution: 'temurin' java-version: ${{ matrix.java }} cache: 'maven' - name: Build with Maven # This also runs javadoc:jar to detect any issues with the Javadoc generated during release run: mvn verify javadoc:jar ${{ matrix.extra-mvn-args || '' }} # Build a subset of the Gson API, see also https://github.com/google/gson/pull/2946 build-gson-subset: name: Build Gson subset runs-on: ubuntu-latest steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: Set up JDK uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0 with: distribution: 'temurin' java-version: 21 cache: 'maven' - name: Build with Maven run: mvn clean test --projects gson --activate-profiles gson-subset native-image-test: name: "GraalVM Native Image test (JDK ${{ matrix.java }})" strategy: matrix: java: [ 21 ] include: - java: 25 # Disable Enforcer check which (intentionally) prevents using JDK 25 for building # TODO: Remove this once JDK 25 is fully supported for building Gson extra-mvn-args: -Denforcer.fail=false runs-on: ubuntu-latest steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: "Set up GraalVM" uses: graalvm/setup-graalvm@54b4f5a65c1a84b2fdfdc2078fe43df32819e4b1 # v1.4.5 with: java-version: ${{ matrix.java }} distribution: 'graalvm' # According to documentation in graalvm/setup-graalvm this is used to avoid rate-limiting issues github-token: ${{ secrets.GITHUB_TOKEN }} cache: 'maven' - name: Build and run tests # Only run tests in `test-graal-native-image` (and implicitly build and run tests in `gson`), # everything else is covered already by regular build job above run: mvn test --activate-profiles native-image-test --projects test-graal-native-image --also-make ${{ matrix.extra-mvn-args || '' }} verify-reproducible-build: name: "Verify reproducible build" runs-on: ubuntu-latest steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: Set up JDK uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0 with: distribution: 'temurin' java-version: 17 cache: 'maven' - name: "Verify no plugin issues" run: mvn artifact:check-buildplan --projects '!metrics,!test-graal-native-image,!test-jpms,!test-shrinker' - name: "Verify reproducible build" # See https://maven.apache.org/guides/mini/guide-reproducible-builds.html#how-to-test-my-maven-build-reproducibility run: | mvn clean install -Dmaven.test.skip --projects '!metrics,!test-graal-native-image,!test-jpms,!test-shrinker' # Run with `-Dbuildinfo.attach=false`; otherwise `artifact:compare` fails because it creates a `.buildinfo` file which # erroneously references the existing `.buildinfo` file (respectively because it is overwriting it, a file with size 0) # See https://issues.apache.org/jira/browse/MARTIFACT-57 mvn clean verify artifact:compare -Dmaven.test.skip --projects '!metrics,!test-graal-native-image,!test-jpms,!test-shrinker' -Dbuildinfo.attach=false ================================================ FILE: .github/workflows/check-android-compatibility.yml ================================================ # For security reasons this is a separate GitHub workflow, see https://github.com/google/gson/issues/2429#issuecomment-1622522842 # Once https://github.com/mojohaus/animal-sniffer/issues/252 or https://github.com/mojohaus/animal-sniffer/pull/253 # are resolved, can consider adjusting pom.xml to include this as part of normal Maven build name: Check Android compatibility on: push: branches-ignore: # Ignore Dependabot branches because it will also open a pull request, which would cause the # workflow to redundantly run twice - dependabot/** pull_request: permissions: contents: read # to fetch code (actions/checkout) env: # Common Maven arguments MAVEN_ARGS: --show-version --batch-mode --no-transfer-progress jobs: check-android-compatibility: runs-on: ubuntu-latest steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: Set up JDK uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0 with: distribution: 'temurin' java-version: '17' cache: 'maven' - name: Check Android compatibility run: | mvn compile animal-sniffer:check@check-android-compatibility -Dmaven.test.skip --projects '!metrics,!test-graal-native-image,!test-jpms,!test-shrinker' ================================================ FILE: .github/workflows/check-api-compatibility.yml ================================================ # This workflow makes sure that a pull request does not make any incompatible changes # to the public API of Gson name: Check API compatibility on: pull_request permissions: contents: read # to fetch code (actions/checkout) env: # Common Maven arguments MAVEN_ARGS: --show-version --batch-mode --no-transfer-progress jobs: check-api-compatibility: runs-on: ubuntu-latest # This setup tries to determine API incompatibility only for the changes introduced by the # pull request. It does this by first checking out the 'old' version and installing it into # the local Maven repository before then using japicmp to compare it to the current changes. # # Alternatively it would also be possible to compare against the last release version instead. # # Both approaches have their advantages and disadvantages, see description of # https://github.com/google/gson/pull/2692 for details. steps: - name: Check out old version uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: ref: ${{ github.event.pull_request.base.sha }} path: 'gson-old-japicmp' - name: Set up JDK uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0 with: distribution: 'temurin' java-version: '17' cache: 'maven' - name: Build old version run: | cd gson-old-japicmp # Set dummy version mvn org.codehaus.mojo:versions-maven-plugin:2.16.2:set "-DnewVersion=0.0.0-JAPICMP-OLD" # Install artifacts with dummy version in local repository; used later by Maven plugin for comparison mvn install -Dmaven.test.skip --projects '!metrics,!test-graal-native-image,!test-jpms,!test-shrinker' - name: Check out new version uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: Check API compatibility id: check-compatibility run: | mvn package japicmp:cmp --fail-at-end -Dmaven.test.skip --projects '!extras,!metrics,!test-graal-native-image,!test-jpms,!test-shrinker' - name: Upload API differences artifacts uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0 # Run on workflow success (in that case differences report might include added methods and classes) # or when API compatibility check failed if: success() || ( failure() && steps.check-compatibility.outcome == 'failure' ) with: name: api-differences path: | **/japicmp/default-cli.html **/japicmp/default-cli.diff # Plugin should always have created report files (though they might be empty) if-no-files-found: error ================================================ FILE: .github/workflows/cifuzz.yml ================================================ name: CIFuzz on: [pull_request] permissions: {} jobs: Fuzzing: runs-on: ubuntu-latest permissions: security-events: write steps: - name: Build Fuzzers id: build # Cannot be pinned to commit because there are no releases, see https://github.com/google/oss-fuzz/issues/6836 uses: google/oss-fuzz/infra/cifuzz/actions/build_fuzzers@master with: oss-fuzz-project-name: 'gson' dry-run: false language: jvm - name: Run Fuzzers # Cannot be pinned to commit because there are no releases, see https://github.com/google/oss-fuzz/issues/6836 uses: google/oss-fuzz/infra/cifuzz/actions/run_fuzzers@master with: oss-fuzz-project-name: 'gson' fuzz-seconds: 600 dry-run: false output-sarif: true - name: Upload Crash uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0 if: failure() && steps.build.outcome == 'success' with: name: artifacts path: ./out/artifacts - name: Upload Sarif if: always() && steps.build.outcome == 'success' uses: github/codeql-action/upload-sarif@5d4e8d1aca955e8d8589aabd499c5cae939e33c7 # v4.31.9 with: # Path to SARIF file relative to the root of the repository sarif_file: cifuzz-sarif/results.sarif checkout_path: cifuzz-sarif ================================================ FILE: .github/workflows/codeql-analysis.yml ================================================ # Based on default config generated by GitHub, see also https://github.com/github/codeql-action name: "CodeQL" on: push: branches: [ main ] pull_request: branches: [ main ] schedule: # Run every Monday at 16:10 - cron: '10 16 * * 1' permissions: contents: read # to fetch code (actions/checkout) env: # Common Maven arguments MAVEN_ARGS: --show-version --batch-mode --no-transfer-progress jobs: analyze: name: Analyze (${{ matrix.language }}) runs-on: ubuntu-latest permissions: security-events: write strategy: fail-fast: false matrix: include: - language: java build-mode: manual # GitHub Actions - language: actions build-mode: none steps: - name: Checkout repository uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: Set up JDK if: ${{ matrix.language == 'java' }} uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0 with: distribution: 'temurin' java-version: '17' cache: 'maven' # Initializes the CodeQL tools for scanning - name: Initialize CodeQL uses: github/codeql-action/init@5d4e8d1aca955e8d8589aabd499c5cae939e33c7 # v4.31.9 with: languages: ${{ matrix.language }} build-mode: ${{ matrix.build-mode }} # Run all security queries and maintainability and reliability queries queries: +security-and-quality # 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 (Java) if: ${{ matrix.language == 'java' }} run: | mvn compile - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@5d4e8d1aca955e8d8589aabd499c5cae939e33c7 # v4.31.9 with: category: "/language:${{ matrix.language }}" ================================================ FILE: .github/workflows/scorecard.yml ================================================ # This workflow uses actions that are not certified by GitHub. They are provided # by a third-party and are governed by separate terms of service, privacy # policy, and support documentation. name: Scorecard supply-chain security on: # For Branch-Protection check. Only the default branch is supported. See # https://github.com/ossf/scorecard/blob/main/docs/checks.md#branch-protection branch_protection_rule: # To guarantee Maintained check is occasionally updated. See # https://github.com/ossf/scorecard/blob/main/docs/checks.md#maintained schedule: - cron: '18 22 * * 3' push: branches: [ "main" ] # Declare default permissions as read only. permissions: read-all jobs: analysis: name: Scorecard analysis runs-on: ubuntu-latest # `publish_results: true` only works when run from the default branch. conditional can be removed if disabled. if: github.event.repository.default_branch == github.ref_name || github.event_name == 'pull_request' permissions: # Needed to upload the results to code-scanning dashboard. security-events: write # Needed to publish results and get a badge (see publish_results below). id-token: write # Uncomment the permissions below if installing in a private repository. # contents: read # actions: read steps: - name: "Checkout code" uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: persist-credentials: false - name: "Run analysis" uses: ossf/scorecard-action@4eaacf0543bb3f2c246792bd56e8cdeffafb205a # v2.4.3 with: results_file: results.sarif results_format: sarif # (Optional) "write" PAT token. Uncomment the `repo_token` line below if: # - you want to enable the Branch-Protection check on a *public* repository, or # - you are installing Scorecard on a *private* repository # To create the PAT, follow the steps in https://github.com/ossf/scorecard-action?tab=readme-ov-file#authentication-with-fine-grained-pat-optional. # repo_token: ${{ secrets.SCORECARD_TOKEN }} # Public repositories: # - Publish results to OpenSSF REST API for easy access by consumers # - Allows the repository to include the Scorecard badge. # - See https://github.com/ossf/scorecard-action#publishing-results. # For private repositories: # - `publish_results` will always be set to `false`, regardless # of the value entered here. publish_results: true # (Optional) Uncomment file_mode if you have a .gitattributes with files marked export-ignore # file_mode: git # Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF # format to the repository Actions tab. - name: "Upload artifact" uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0 with: name: SARIF file path: results.sarif retention-days: 5 # Upload the results to GitHub's code scanning dashboard (optional). # Commenting out will disable upload of results to your repo's Code Scanning dashboard - name: "Upload to code-scanning" uses: github/codeql-action/upload-sarif@5d4e8d1aca955e8d8589aabd499c5cae939e33c7 # v4.31.9 with: sarif_file: results.sarif ================================================ FILE: .gitignore ================================================ .classpath .project .settings eclipsebin target */target pom.xml.* release.properties .idea *.iml *.ipr *.iws classes .gradle local.properties build .DS_Store ================================================ FILE: .mvn/jvm.config ================================================ --add-exports jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED --add-exports jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED --add-exports jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED --add-exports jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED --add-exports jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED --add-exports jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED --add-exports jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED --add-exports jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED --add-opens jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED --add-opens jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED ================================================ FILE: CHANGELOG.md ================================================ Change Log ========== The change log for versions newer than 2.10 is available only on the [GitHub Releases page](https://github.com/google/gson/releases). ## Version 2.10 * Support for serializing and deserializing Java records, on Java ≥ 16. (https://github.com/google/gson/pull/2201) * Add `JsonArray.asList` and `JsonObject.asMap` view methods (https://github.com/google/gson/pull/2225) * Fix `TypeAdapterRuntimeTypeWrapper` not detecting reflective `TreeTypeAdapter` and `FutureTypeAdapter` (https://github.com/google/gson/pull/1787) * Improve `JsonReader.skipValue()` (https://github.com/google/gson/pull/2062) * Perform numeric conversion for primitive numeric type adapters (https://github.com/google/gson/pull/2158) * Add `Gson.fromJson(..., TypeToken)` overloads (https://github.com/google/gson/pull/1700) * Fix changes to `GsonBuilder` affecting existing `Gson` instances (https://github.com/google/gson/pull/1815) * Make `JsonElement` conversion methods more consistent and fix javadoc (https://github.com/google/gson/pull/2178) * Throw `UnsupportedOperationException` when `JsonWriter.jsonValue` is not supported (https://github.com/google/gson/pull/1651) * Disallow `JsonObject` `Entry.setValue(null)` (https://github.com/google/gson/pull/2167) * Fix `TypeAdapter.toJson` throwing AssertionError for custom IOException (https://github.com/google/gson/pull/2172) * Convert null to JsonNull for `JsonArray.set` (https://github.com/google/gson/pull/2170) * Fixed nullSafe usage. (https://github.com/google/gson/pull/1555) * Validate `TypeToken.getParameterized` arguments (https://github.com/google/gson/pull/2166) * Fix #1702: Gson.toJson creates CharSequence which does not implement toString (https://github.com/google/gson/pull/1703) * Prefer existing adapter for concurrent `Gson.getAdapter` calls (https://github.com/google/gson/pull/2153) * Improve `ArrayTypeAdapter` for `Object[]` (https://github.com/google/gson/pull/1716) * Improve `AppendableWriter` performance (https://github.com/google/gson/pull/1706) ## Version 2.9.1 * Make `Object` and `JsonElement` deserialization iterative rather than recursive (https://github.com/google/gson/pull/1912) * Added parsing support for enum that has overridden toString() method (https://github.com/google/gson/pull/1950) * Removed support for building Gson with Gradle (https://github.com/google/gson/pull/2081) * Removed obsolete `codegen` hierarchy (https://github.com/google/gson/pull/2099) * Add support for reflection access filter (https://github.com/google/gson/pull/1905) * Improve `TypeToken` creation validation (https://github.com/google/gson/pull/2072) * Add explicit support for `float` in `JsonWriter` (https://github.com/google/gson/pull/2130, https://github.com/google/gson/pull/2132) * Fail when parsing invalid local date (https://github.com/google/gson/pull/2134) Also many small improvements to javadoc. ## Version 2.9.0 **The minimum supported Java version changes from 6 to 7.** * Change target Java version to 7 (https://github.com/google/gson/pull/2043) * Put `module-info.class` into Multi-Release JAR folder (https://github.com/google/gson/pull/2013) * Improve error message when abstract class cannot be constructed (https://github.com/google/gson/pull/1814) * Support EnumMap deserialization (https://github.com/google/gson/pull/2071) * Add LazilyParsedNumber default adapter (https://github.com/google/gson/pull/2060) * Fix JsonReader.hasNext() returning true at end of document (https://github.com/google/gson/pull/2061) * Remove Gradle build support. Build script was outdated and not actively maintained anymore (https://github.com/google/gson/pull/2063) * Add `GsonBuilder.disableJdkUnsafe()` (https://github.com/google/gson/pull/1904) * Add `UPPER_CASE_WITH_UNDERSCORES` in FieldNamingPolicy (https://github.com/google/gson/pull/2024) * Fix failing to serialize Collection or Map with inaccessible constructor (https://github.com/google/gson/pull/1902) * Improve TreeTypeAdapter thread-safety (https://github.com/google/gson/pull/1976) * Fix `Gson.newJsonWriter` ignoring lenient and HTML-safe setting (https://github.com/google/gson/pull/1989) * Delete unused LinkedHashTreeMap (https://github.com/google/gson/pull/1992) * Make default adapters stricter; improve exception messages (https://github.com/google/gson/pull/2000) * Fix `FieldNamingPolicy.upperCaseFirstLetter` uppercasing non-letter (https://github.com/google/gson/pull/2004) ## Version 2.8.9 * Make OSGi bundle's dependency on `sun.misc` optional (https://github.com/google/gson/pull/1993). * Deprecate `Gson.excluder()` exposing internal `Excluder` class (https://github.com/google/gson/pull/1986). * Prevent Java deserialization of internal classes (https://github.com/google/gson/pull/1991). * Improve number strategy implementation (https://github.com/google/gson/pull/1987). * Fix LongSerializationPolicy null handling being inconsistent with Gson (https://github.com/google/gson/pull/1990). * Support arbitrary Number implementation for Object and Number deserialization (https://github.com/google/gson/pull/1290). * Bump proguard-maven-plugin from 2.4.0 to 2.5.1 (https://github.com/google/gson/pull/1980). * Don't exclude static local classes (https://github.com/google/gson/pull/1969). * Fix `RuntimeTypeAdapterFactory` depending on internal `Streams` class (https://github.com/google/gson/pull/1959). * Improve Maven build (https://github.com/google/gson/pull/1964). * Make dependency on `java.sql` optional (https://github.com/google/gson/pull/1707). ## Version 2.8.8 * Fixed issue with recursive types (https://github.com/google/gson/issues/1390). * Better behaviour with Java 9+ and `Unsafe` if there is a security manager (https://github.com/google/gson/pull/1712). * `EnumTypeAdapter` now works better when ProGuard has obfuscated enum fields (https://github.com/google/gson/pull/1495). ## Version 2.8.7 * Fixed `ISO8601UtilsTest` failing on systems with UTC+X. * Improved javadoc for `JsonStreamParser`. * Updated proguard.cfg (https://github.com/google/gson/pull/1693). * Fixed `IllegalStateException` in `JsonTreeWriter` (https://github.com/google/gson/issues/1592). * Added `JsonArray.isEmpty()` (https://github.com/google/gson/pull/1640). * Added new test cases (https://github.com/google/gson/pull/1638). * Fixed OSGi metadata generation to work on JavaSE < 9 (https://github.com/google/gson/pull/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/main/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 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 points = new ArrayList(); points.add(new Point3d(1, 2, 3)); String json = gson.toJson(points, new TypeToken>() {}.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 `` 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` 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 ================================================ FILE: GsonDesignDocument.md ================================================ # 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. Some information in this document is outdated and does not reflect the current state of Gson. This information can however still be relevant for understanding the history of Gson. ## 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 thereby 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 type 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 later 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 (maybe 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. ================================================ FILE: LICENSE ================================================ 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. ================================================ FILE: README.md ================================================ # 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. > [!NOTE]\ > Gson is currently in maintenance mode; existing bugs will be fixed, but large new features will likely not be added. If you want to add a new feature, please first search for existing GitHub issues, or create a new one to discuss the feature and get feedback. > [!IMPORTANT]\ > Gson's main focus is on Java. Using it with other JVM languages such as Kotlin or Scala might work fine in many cases, but language-specific features such as Kotlin's non-`null` types or constructors with default arguments are not supported. This can lead to confusing and incorrect behavior.\ > When using languages other than Java, prefer a JSON library with explicit support for that language. > [!IMPORTANT]\ > Gson is not a recommended library for interacting with JSON on Android. The open-ended reflection in the Gson runtime doesn't play nicely with shrinking/optimization/obfuscation passes that Android release apps should perform.\ > If your app or library may be running on Android, consider using [Kotlin Serialization](https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/basic-serialization.md#basics) or [Moshi's Codegen](https://github.com/square/moshi?tab=readme-ov-file#codegen), > which use code generation instead of reflection. This avoids Gson's runtime crashes when optimizations are applied (usually due to the fields missing or being obfuscated), and results in faster performance on Android devices. > The Moshi APIs may be more familiar to users who already know Gson. > If you still want to use Gson and attempt to avoid these crashes, you can see how to do so [here](Troubleshooting.md#proguard-r8). ### 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.13.2' } ``` Maven: ```xml com.google.code.gson gson 2.13.2 ``` [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.12.0 and newer: Java 8 - Gson 2.9.0 to 2.11.0: 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()). #### Minimum Android API level - Gson 2.11.0 and newer: API level 21 - Gson 2.10.1 and older: API level 19 Older Gson versions may also support lower API levels, however this has not been verified. ### Documentation * [API Javadoc](https://www.javadoc.io/doc/com.google.code.gson/gson): Documentation for the current release * [User guide](UserGuide.md): This guide contains examples on how to use Gson in your code * [Troubleshooting guide](Troubleshooting.md): Describes how to solve common issues when using Gson * [Releases and change log](https://github.com/google/gson/releases): Latest releases and changes in these versions; for older releases see [`CHANGELOG.md`](CHANGELOG.md) * [Design document](GsonDesignDocument.md): This document discusses issues we faced while designing Gson. It also includes a comparison of Gson with other Java libraries that can be used for Json conversion Please use the ['gson' tag on StackOverflow](https://stackoverflow.com/questions/tagged/gson), [GitHub Discussions](https://github.com/google/gson/discussions) or the [google-gson Google group](https://groups.google.com/group/google-gson) to discuss Gson or to post questions. ### ProGuard / R8 See the details in the related section in the [Troubleshooting guide](Troubleshooting.md#proguard-r8). ### 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/) ### Building Gson uses Maven to build the project: ``` mvn clean verify ``` JDK 17 or newer is required for building, JDK 21 is recommended. Newer JDKs are currently not supported for building (but are supported when _using_ Gson). ### Contributing See the [contributing guide](https://github.com/google/.github/blob/master/CONTRIBUTING.md).\ Please perform a quick search to check if there are already existing issues or pull requests related to your contribution. Keep in mind that Gson is in maintenance mode. 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. ### 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. ================================================ FILE: ReleaseProcess.md ================================================ # 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. Make sure your `${user.home}/.m2/settings.xml` contains the [Maven Central credentials](https://central.sonatype.org/publish/publish-portal-maven/#credentials) 1. `cd gson` to the parent directory; ensure there are no open files and all changes are committed. 1. Run `mvn release:clean` 1. Start the release: `mvn release:prepare` - Answer questions: usually the defaults are fine. Try to follow [Semantic Versioning](https://semver.org/) when choosing the release version number. - 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 the Central Portal](https://central.sonatype.com/) 1. Download and sanity check all files.\ 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. Publish the new Gson version in the Central Portal.\ Gson will now get synced to Maven Central within the next hour. 1. Create a [GitHub release](https://github.com/google/gson/releases) for the new version.\ You can let GitHub [automatically generate the description for the release](https://docs.github.com/en/repositories/releasing-projects-on-github/automatically-generated-release-notes), but you should edit it manually to point out the most important changes and potentially incompatible changes. 1. Update version references in (version might be referenced multiple times): - [`README.md`](README.md) - [`UserGuide.md`](UserGuide.md) Note: When using the Maven Release Plugin as described above, these version references should have been replaced automatically, but verify this manually nonetheless to be on the safe side. 1. Optional: Create a post on the [Gson Discussion Forum](https://groups.google.com/group/google-gson). 1. Optional: Update the release version in [Wikipedia](https://en.wikipedia.org/wiki/Gson) and update the current "stable" release. Important: When aborting a release / rolling back release preparations, make sure to also revert all changes to files which were done during the release (e.g. automatic replacement of version references). ## Testing Maven release workflow locally The following describes how to perform the steps of the release locally to verify that they work as desired. > [!CAUTION]\ > Be careful with this, these steps might be outdated or incomplete. Double-check that you are working on a copy of your local Gson Git repository and make sure you have followed all steps. To be safe you can also temporarily turn off your internet connection to avoid accidentally pushing changes to the real remote Git or Maven repository.\ > As an alternative to the steps described below you can instead [perform a dry run](https://maven.apache.org/maven-release/maven-release-plugin/usage.html#do-a-dry-run), though this might not behave identical to a real release. 1. Make a copy of your local Gson Git repository and only work with that copy 1. Make sure you are on the `main` branch 1. Create a temp directory outside the Gson directory\ In the following steps this will be called `#gson-remote-temp#`; replace this with the actual absolute file path of the directory, using only forward slashes. For example under Windows `C:\my-dir` becomes `C:/my-dir`. 1. Create the directory `#gson-remote-temp#/git-repo` 1. In that directory run ```sh git init --bare --initial-branch=main . ``` 1. Edit the root `pom.xml` of Gson 1. Change the `` to ```txt scm:git:file:///#gson-remote-temp#/git-repo ``` 1. For the `central-publishing-maven-plugin` **inside the ``**, add the following to its `` ```xml true ``` 1. If you don't want to use GPG, remove the `maven-gpg-plugin` entry from the 'release' profile.\ There is also an entry under ``; you can remove that as well. 1. Commit the changes using Git 1. Change the remote repository of the Git project ```txt git remote set-url origin file:///#gson-remote-temp#/git-repo ``` 1. Push the changes ```sh git push origin main ``` Now you can perform the steps of the release: 1. ```sh mvn release:clean ``` 1. ```sh mvn release:prepare ``` 1. ```sh mvn release:perform ``` 1. Verify that `#gson-remote-temp#/git-repo` contains the desired changes 1. Verify that in the Gson project directory where you performed the release, the `target/checkout/target/central-publishing/central-bundle.zip` file contains the desired artifacts\ Currently that is the artifacts for `gson-parent` and `gson`. 1. Afterwards delete all Gson files under `${user.home}/.m2/repository/com/google/code/gson` which have been installed in your local Maven repository during the release.\ Otherwise Maven might not download the real Gson artifacts with these version numbers, once they are released. ## 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" ``` ================================================ FILE: Troubleshooting.md ================================================ # Troubleshooting Guide This guide describes how to troubleshoot common issues when using Gson. ## `ClassCastException` when using deserialized object **Symptom:** `ClassCastException` is thrown when accessing an object deserialized by Gson **Reason:** - Your code is most likely not type-safe - Or, you have not configured code shrinking tools such as ProGuard or R8 correctly **Solution:** Make sure your code adheres to the following: - Avoid raw types: Instead of calling `fromJson(..., List.class)`, create for example a `TypeToken>`. See the [user guide](UserGuide.md#collections-examples) for more information. - When using `TypeToken` prefer the `Gson.fromJson` overloads with `TypeToken` parameter such as [`fromJson(Reader, TypeToken)`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/Gson.html#fromJson(java.io.Reader,com.google.gson.reflect.TypeToken)). The overloads with `Type` parameter do not provide any type-safety guarantees. - When using `TypeToken` make sure you don't capture a type variable. For example avoid something like `new TypeToken>()` (where `T` is a type variable). Due to Java [type erasure](https://dev.java/learn/generics/type-erasure/) the actual type of `T` is not available at runtime. Refactor your code to pass around `TypeToken` instances or use [`TypeToken.getParameterized(...)`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/reflect/TypeToken.html#getParameterized(java.lang.reflect.Type,java.lang.reflect.Type...)), for example `TypeToken.getParameterized(List.class, elementType)` where `elementType` is a type you have to provide separately. If you are using a code shrinking tool such as ProGuard / R8 (for example when building an Android app), make sure it is correctly configured to keep generic signatures and to keep Gson's `TypeToken` class. See the [ProGuard / R8](#proguard-r8) section for more information. ## `InaccessibleObjectException`: 'module ... does not "opens ..." to unnamed module' **Symptom:** An exception with a message in the form 'module ... does not "opens ..." to unnamed module' is thrown **Reason:** You use Gson by accident to access internal fields of third-party classes **Solution:** Write custom Gson [`TypeAdapter`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/TypeAdapter.html) implementations for the affected classes or change the type of your data. If you already wrote a custom adapter, but it is not used, see [this troubleshooting point](#custom-adapter-not-used).\ If this occurs for a field in one of your classes which you did not actually want to serialize or deserialize in the first place, you can exclude that field, see the [user guide](UserGuide.md#excluding-fields-from-serialization-and-deserialization). **Explanation:** When no built-in adapter for a type exists and no custom adapter has been registered, Gson falls back to using reflection to access the fields of a class (including `private` ones). Most likely you are seeing this error because you (by accident) rely on the reflection-based adapter for third-party classes. That should be avoided because you make yourself dependent on the implementation details of these classes which could change at any point. For the JDK it is also not possible anymore to access internal fields using reflection starting with JDK 17, see [JEP 403](https://openjdk.org/jeps/403). If you want to prevent using reflection on third-party classes in the future you can write your own [`ReflectionAccessFilter`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/ReflectionAccessFilter.html) or use one of the predefined ones, such as `ReflectionAccessFilter.BLOCK_ALL_PLATFORM`. ## `InaccessibleObjectException`: 'module ... does not "opens ..." to module com.google.gson' **Symptom:** An exception with a message in the form 'module ... does not "opens ..." to module com.google.gson' is thrown **Reason:** - If the reported package is your own package then you have not configured the module declaration of your project to allow Gson to use reflection on your classes. - If the reported package is from a third party library or the JDK see [this troubleshooting point](#inaccessibleobjectexception-module--does-not-opens--to-unnamed-module). **Solution:** Make sure the `module-info.java` file of your project allows Gson to use reflection on your classes, for example: ```java module mymodule { requires com.google.gson; opens mypackage to com.google.gson; } ``` Or in case this occurs for a field in one of your classes which you did not actually want to serialize or deserialize in the first place, you can exclude that field, see the [user guide](UserGuide.md#excluding-fields-from-serialization-and-deserialization). ## Android app not working in Release mode; random property names **Symptom:** Your Android app is working fine in Debug mode but fails in Release mode and the JSON properties have seemingly random names such as `a`, `b`, ... **Reason:** You probably have not configured ProGuard / R8 correctly **Solution:** Make sure you have configured ProGuard / R8 correctly to preserve the names of your fields. See the section below, it's related to this issue. ## Android app unable to parse JSON after app update **Symptom:** You released a new version of your Android app and it fails to parse JSON data created by the previous version of your app **Reason:** You probably have not configured ProGuard / R8 correctly; probably the field names are being obfuscated and their naming changed between the versions of your app **Solution:** Make sure you have configured ProGuard / R8 correctly to preserve the names of your fields. See the [ProGuard / R8](#proguard-r8) section for more information. If you want to preserve backward compatibility for you app you can use [`@SerializedName`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/annotations/SerializedName.html) on the fields to specify the obfuscated name as alternate, for example: `@SerializedName(value = "myprop", alternate = "a")` Normally ProGuard and R8 produce a mapping file, this makes it easier to find out the obfuscated field names instead of having to find them out through trial and error or other means. See the [Android Studio user guide](https://developer.android.com/studio/build/shrink-code.html#retracing) for more information. ## Default field values not present after deserialization **Symptom:** You have assign default values to fields but after deserialization the fields have their standard value (such as `null` or `0`) **Reason:** Gson cannot invoke the constructor of your class and falls back to JDK `Unsafe` (or similar means) **Solution:** Make sure that the class: - is `static` (explicitly or implicitly when it is a top-level class) - has a no-args constructor Otherwise Gson will by default try to use JDK `Unsafe` or similar means to create an instance of your class without invoking the constructor and without running any initializers. You can also disable that behavior through [`GsonBuilder.disableJdkUnsafe()`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/GsonBuilder.html#disableJdkUnsafe()) to notice such issues early on. ## `null` values for anonymous and local classes **Symptom:** Objects of a class are always serialized as JSON `null` / always deserialized as Java `null` **Reason:** The class you are serializing or deserializing is an anonymous or a local class (or you have specified a custom `ExclusionStrategy`) **Solution:** Convert the class to a `static` nested class. If the class is already `static` make sure you have not specified a Gson `ExclusionStrategy` which might exclude the class. Notes: - "double brace-initialization" also creates anonymous classes - Local record classes (feature added in Java 16) are supported by Gson and are not affected by this ## Map keys having unexpected format in JSON **Symptom:** JSON output for `Map` keys is unexpected / cannot be deserialized again **Reason:** The `Map` key type is 'complex' and you have not configured the `GsonBuilder` properly **Solution:** Use [`GsonBuilder.enableComplexMapKeySerialization()`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/GsonBuilder.html#enableComplexMapKeySerialization()). See also the [user guide](UserGuide.md#maps-examples) for more information. ## Parsing JSON fails with `MalformedJsonException` **Symptom:** JSON parsing fails with `MalformedJsonException` **Reason:** The JSON data is actually malformed **Solution:** During debugging, log the JSON data right before calling Gson methods or set a breakpoint to inspect the data and make sure it has the expected format. Sometimes APIs might return HTML error pages (instead of JSON data) when reaching rate limits or when other errors occur. Also read the location information of the `MalformedJsonException` exception message, it indicates where exactly in the document the malformed data was detected, including the [JSONPath](https://goessner.net/articles/JsonPath/). For example, let's assume you want to deserialize the following JSON data: ```json { "languages": [ "English", "French", ] } ``` This will fail with an exception similar to this one: `MalformedJsonException: Use JsonReader.setStrictness(Strictness.LENIENT) to accept malformed JSON at line 5 column 4 path $.languages[2]`\ The problem here is the trailing comma (`,`) after `"French"`, trailing commas are not allowed by the JSON specification. The location information "line 5 column 4" points to the `]` in the JSON data (with some slight inaccuracies) because Gson expected another value after `,` instead of the closing `]`. The JSONPath `$.languages[2]` in the exception message also points there: `$.` refers to the root object, `languages` refers to its member of that name and `[2]` refers to the (missing) third value in the JSON array value of that member (numbering starts at 0, so it is `[2]` instead of `[3]`).\ The proper solution here is to fix the malformed JSON data. To spot syntax errors in the JSON data easily you can open it in an editor with support for JSON, for example Visual Studio Code. It will highlight within the JSON data the error location and show why the JSON data is considered invalid. ## Integral JSON number is parsed as `double` **Symptom:** JSON data contains an integral number such as `45` but Gson returns it as `double` **Reason:** When parsing a JSON number as `Object`, Gson will by default always return a `double` **Solution:** Use [`GsonBuilder.setObjectToNumberStrategy`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/GsonBuilder.html#setObjectToNumberStrategy(com.google.gson.ToNumberStrategy)) to specify what type of number should be returned ## Malformed JSON not rejected **Symptom:** Gson parses malformed JSON without throwing any exceptions **Reason:** Due to legacy reasons Gson performs parsing by default in lenient mode **Solution:** If you are using Gson 2.11.0 or newer, call [`GsonBuilder.setStrictness`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/GsonBuilder.html#setStrictness(com.google.gson.Strictness)), [`JsonReader.setStrictness`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/stream/JsonReader.html#setStrictness(com.google.gson.Strictness)) and [`JsonWriter.setStrictness`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/stream/JsonWriter.html#setStrictness(com.google.gson.Strictness)) with `Strictness.STRICT` to overwrite the default lenient behavior of `Gson` and make these classes strictly adhere to the JSON specification. Otherwise if you are using an older Gson version, see the [`Gson` class documentation](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/Gson.html#default-lenient) section "JSON Strictness handling" for alternative solutions. ## `IllegalStateException`: "Expected ... but was ..." **Symptom:** An `IllegalStateException` with a message in the form "Expected ... but was ..." is thrown **Reason:** - The JSON data does not have the correct format - Or, Gson has no built-in adapter for a type and tries to deserialize it as JSON object **Solution:** Make sure that your classes correctly model the JSON data. Also during debugging log the JSON data right before calling Gson methods or set a breakpoint to inspect the data and make sure it has the expected format. Read the location information of the exception message, it indicates where exactly in the document the error occurred, including the [JSONPath](https://goessner.net/articles/JsonPath/). For example, let's assume you have the following Java class: ```java class WebPage { String languages; } ``` And you want to deserialize the following JSON data: ```json { "languages": ["English", "French"] } ``` This will fail with an exception similar to this one: `IllegalStateException: Expected a string but was BEGIN_ARRAY at line 2 column 17 path $.languages`\ This means Gson expected a JSON string value but found the beginning of a JSON array (`[`). The location information "line 2 column 17" points to the `[` in the JSON data (with some slight inaccuracies), so does the JSONPath `$.languages` in the exception message. It refers to the `languages` member of the root object (`$.`).\ The solution here is to change in the `WebPage` class the field `String languages` to `List languages`. If you are sure that the JSON data is correct and the exception message is "Expected BEGIN_OBJECT but was ...", then this might indicate that Gson has no built-in adapter for the type. Gson then tries to use reflection and expects that the data is a JSON object (hence the error message "Expected BEGIN_OBJECT ..."). In that case you have to write a custom [`TypeAdapter`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/TypeAdapter.html) for that type. If you already wrote a custom adapter, but it is not used, see [this troubleshooting point](#custom-adapter-not-used). ## `IllegalStateException`: "Expected ... but was NULL" **Symptom:** An `IllegalStateException` with a message in the form "Expected ... but was NULL" is thrown **Reason:** - A built-in adapter does not support JSON null values - Or, you have written a custom `TypeAdapter` which does not properly handle JSON null values **Solution:** If this occurs for a custom adapter you wrote, add code similar to the following at the beginning of its `read` method: ```java @Override public MyClass read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } ... } ``` Alternatively you can call [`nullSafe()`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/TypeAdapter.html#nullSafe()) on the adapter instance you created. ## Properties missing in JSON **Symptom:** Properties are missing in the JSON output **Reason:** Gson by default omits JSON null from the output\ (or: ProGuard / R8 is not configured correctly and removed unused fields, see the [ProGuard / R8](#proguard-r8) section) **Solution:** Use [`GsonBuilder.serializeNulls()`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/GsonBuilder.html#serializeNulls()) Note: Gson does not support anonymous and local classes and will serialize them as JSON null, see the [related troubleshooting point](#null-values-for-anonymous-and-local-classes). ## JSON output changes for newer Android versions **Symptom:** The JSON output differs when running on newer Android versions **Reason:** You use Gson by accident to access internal fields of Android classes **Solution:** Write custom Gson [`TypeAdapter`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/TypeAdapter.html) implementations for the affected classes or change the type of your data **Explanation:** When no built-in adapter for a type exists and no custom adapter has been registered, Gson falls back to using reflection to access the fields of a class (including `private` ones). Most likely you are experiencing this issue because you (by accident) rely on the reflection-based adapter for Android classes. That should be avoided because you make yourself dependent on the implementation details of these classes which could change at any point. If you want to prevent using reflection on third-party classes in the future you can write your own [`ReflectionAccessFilter`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/ReflectionAccessFilter.html) or use one of the predefined ones, such as `ReflectionAccessFilter.BLOCK_ALL_PLATFORM`. ## JSON output contains values of `static` fields **Symptom:** The JSON output contains values of `static` fields **Reason:** You used `GsonBuilder.excludeFieldsWithModifiers` to overwrite the default excluded modifiers **Solution:** When calling `GsonBuilder.excludeFieldsWithModifiers` you overwrite the default excluded modifiers. Therefore, you have to explicitly exclude `static` fields if desired. This can be done by adding `Modifier.STATIC` as additional argument to the `excludeFieldsWithModifiers` call. ## `NoSuchMethodError` when calling Gson methods **Symptom:** A `java.lang.NoSuchMethodError` is thrown when trying to call certain Gson methods **Reason:** - You have multiple versions of Gson on your classpath - Or, the Gson version you compiled against is different from the one on your classpath - Or, you are using a code shrinking tool such as ProGuard or R8 which removed methods from Gson **Solution:** First disable any code shrinking tools such as ProGuard or R8 and check if the issue persists. If not, you have to tweak the configuration of that tool to not modify Gson classes. Otherwise verify that the Gson JAR on your classpath is the same you are compiling against, and that there is only one Gson JAR on your classpath. See [this Stack Overflow question](https://stackoverflow.com/q/227486) to find out where a class is loaded from. For example, for debugging you could include the following code: ```java System.out.println(Gson.class.getProtectionDomain().getCodeSource().getLocation()); ``` If that fails with a `NullPointerException` you have to try one of the other ways to find out where a class is loaded from. ## `IllegalArgumentException`: 'Class ... declares multiple JSON fields named '...'' **Symptom:** An exception with the message 'Class ... declares multiple JSON fields named '...'' is thrown **Reason:** - The name you have specified with a [`@SerializedName`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/annotations/SerializedName.html) annotation for a field collides with the name of another field - Or, the [`FieldNamingStrategy`](https://javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/FieldNamingStrategy.html) you have specified produces conflicting field names - Or, a field of your class has the same name as the field of a superclass - Or, you are using an obfuscation tool such as ProGuard or R8, and it has renamed the fields; in that case see the [ProGuard / R8](#proguard-r8) section Gson prevents multiple fields with the same name because during deserialization it would be ambiguous for which field the JSON data should be deserialized. For serialization it would cause the same field to appear multiple times in JSON. While the JSON specification permits this, it is likely that the application parsing the JSON data will not handle it correctly. **Solution:** First identify the fields with conflicting names based on the exception message. Then decide if you want to rename one of them using the [`@SerializedName`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/annotations/SerializedName.html) annotation or a [`FieldNamingStrategy`](https://javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/FieldNamingStrategy.html), or if you want to [exclude](UserGuide.md#excluding-fields-from-serialization-and-deserialization) one of them. When excluding one of the fields you have to apply the exclusion for both serialization and deserialization (even if your application only performs one of these actions) because the duplicate field check cannot differentiate between these actions. ## `UnsupportedOperationException` when serializing or deserializing `java.lang.Class` **Symptom:** An `UnsupportedOperationException` is thrown when trying to serialize or deserialize `java.lang.Class` **Reason:** Gson intentionally does not permit serializing and deserializing `java.lang.Class` for security reasons. Otherwise a malicious user could make your application load an arbitrary class from the classpath and, depending on what your application does with the `Class`, in the worst case perform a remote code execution attack. **Solution:** First check if you really need to serialize or deserialize a `Class`. Often it is possible to use string aliases and then map them to the known `Class`; you could write a custom [`TypeAdapter`](https://javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/TypeAdapter.html) to do this. If the `Class` values are not known in advance, try to introduce a common base class or interface for all these classes and then verify that the deserialized class is a subclass. For example assuming the base class is called `MyBaseClass`, your custom `TypeAdapter` should load the class like this: ```java Class.forName(jsonString, false, getClass().getClassLoader()).asSubclass(MyBaseClass.class) ``` This will not initialize arbitrary classes, and it will throw a `ClassCastException` if the loaded class is not the same as or a subclass of `MyBaseClass`. ## Custom type adapter is not used **Symptom:** You have registered a custom `TypeAdapter` (or `JsonSerializer` or `JsonDeserializer`) on a `GsonBuilder`, but Gson is not using your adapter **Reason:** - You registered the adapter for the wrong type - Or, you are serializing or deserializing a subclass - Or, your custom `Gson` instance is not actually used **Solution:** - Debug your code and verify that the custom `Gson` instance on which you have registered the adapter is actually used. Possibly parts of your application are using a different `Gson` instance, or you are using a framework such as Spring which is using a different `Gson` instance with default configuration (in that case have a look at the framework-specific configuration options). - Verify that you are registering the adapter for the correct type. `GsonBuilder.registerTypeAdapter(...)` takes the adapter as `Object` argument, so you will not see a compilation error when you provide the wrong type. For example when you want to register an adapter for `MyClass`, you should call `registerTypeAdapter(MyClass.class, new MyClassAdapter())`.\ Also pay close attention to the package name, there are classes with the same name in different packages, such as `java.util.Date` and `java.sql.Date`. - `registerTypeAdapter` only registers an adapter for the specified class, _but not for subclasses_. Use [`registerTypeHierarchyAdapter`](https://javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/GsonBuilder.html#registerTypeHierarchyAdapter(java.lang.Class,java.lang.Object)) to also handle subclasses. - Be careful with parameterized types for `registerTypeAdapter` because Gson only uses the adapter if there is an exact match for the types. For example if you register an adapter for `List` it won't be used for `List` (raw type), `List` or `ArrayList`. You can solve this by writing a [`TypeAdapterFactory`](https://javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/TypeAdapterFactory.html) instead, which manually checks if the type matches. - If you want to register an adapter for a primitive type such as `boolean`, you might also want to register it for the wrapper type `java.lang.Boolean`, and the other way around. - The built-in adapters for `JsonElement` (and subclasses) and for `Object` cannot be overwritten. However, as workaround for a field of those types you can use the [`@JsonAdapter` annotation](https://javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/annotations/JsonAdapter.html) to specify a custom adapter. ## `IllegalStateException`: 'TypeToken must be created with a type argument'
`RuntimeException`: 'Missing type parameter' **Symptom:** An `IllegalStateException` with the message 'TypeToken must be created with a type argument' is thrown.\ For older Gson versions a `RuntimeException` with message 'Missing type parameter' is thrown. **Reason:** - You created a `TypeToken` without type argument, for example `new TypeToken() {}` (note the missing `<...>`). You always have to provide the type argument, for example like this: `new TypeToken>() {}`. Normally the compiler will also emit a 'raw types' warning when you forget the `<...>`. - Or, you are using a code shrinking tool such as ProGuard or R8 (Android app builds normally have this enabled by default) but have not configured it correctly for usage with Gson. **Solution:** When you are using a code shrinking tool such as ProGuard or R8 you have to adjust your configuration to include the following rules: ``` # Keep generic signatures; needed for correct type resolution -keepattributes Signature # Keep class TypeToken (respectively its generic signature) -keep class com.google.gson.reflect.TypeToken { *; } # Keep any (anonymous) classes extending TypeToken -keep class * extends com.google.gson.reflect.TypeToken ``` See the [ProGuard / R8](#proguard-r8) section for more information. Note: For newer Gson versions these rules might be applied automatically; make sure you are using the latest Gson version and the latest version of the code shrinking tool. ## `JsonIOException`: 'Abstract classes can't be instantiated!' (R8) **Symptom:** A `JsonIOException` with the message 'Abstract classes can't be instantiated!' is thrown; the class mentioned in the exception message is not actually `abstract` in your source code, and you are using the code shrinking tool R8 (Android app builds normally have this configured by default). Note: If the class which you are trying to deserialize is actually abstract, then this exception is probably unrelated to R8 and you will have to implement a custom [`InstanceCreator`](https://javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/InstanceCreator.html) or [`TypeAdapter`](https://javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/TypeAdapter.html) which creates an instance of a non-abstract subclass of the class. If you already wrote a custom adapter, but it is not used, see [this troubleshooting point](#custom-adapter-not-used). **Reason:** The code shrinking tool R8 performs optimizations where it removes the no-args constructor from a class and makes the class `abstract`. Due to this Gson cannot create an instance of the class. **Solution:** Make sure the class has a no-args constructor, then adjust your R8 configuration file to keep the constructor of the class. For example: ``` # Keep the no-args constructor of the deserialized class -keepclassmembers class com.example.MyClass { (); } ``` You can also use `(...);` to keep all constructors of that class, but then you might actually rely on `sun.misc.Unsafe` on both JDK and Android to create classes without no-args constructor, see [`GsonBuilder.disableJdkUnsafe()`](https://javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/GsonBuilder.html#disableJdkUnsafe()) for more information. For Android you can add this rule to the `proguard-rules.pro` file, see also the [Android documentation](https://developer.android.com/build/shrink-code#keep-code). In case the class name in the exception message is obfuscated, see the Android documentation about [retracing](https://developer.android.com/build/shrink-code#retracing). For Android you can alternatively use the [`@Keep` annotation](https://developer.android.com/studio/write/annotations#keep) on the class or constructor you want to keep. That might be easier than having to maintain a custom R8 configuration. Note that the latest Gson versions (2.11.0 or newer) specify a default R8 configuration. See the [ProGuard / R8](#proguard-r8) section for more information. ## `IllegalArgumentException`: 'TypeToken type argument must not contain a type variable' **Symptom:** An exception with the message 'TypeToken type argument must not contain a type variable' is thrown **Reason:** This exception is thrown when you create an anonymous `TypeToken` subclass which captures a type variable, for example `new TypeToken>() {}` (where `T` is a type variable). At compile time such code looks safe and you can use the type `List` without any warnings. However, this code is not actually type-safe because at runtime due to [type erasure](https://dev.java/learn/generics/type-erasure/) only the upper bound of the type variable is available. For the previous example that would be `List`. When using such a `TypeToken` with any Gson methods performing deserialization this would lead to confusing and difficult to debug `ClassCastException`s. For serialization it can in some cases also lead to undesired results. Note: Earlier version of Gson unfortunately did not prevent capturing type variables, which caused many users to unwittingly write type-unsafe code. **Solution:** - Use [`TypeToken.getParameterized(...)`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/reflect/TypeToken.html#getParameterized(java.lang.reflect.Type,java.lang.reflect.Type...)), for example `TypeToken.getParameterized(List.class, elementType)` where `elementType` is a type you have to provide separately. - For Kotlin users: Use [`reified` type parameters](https://kotlinlang.org/docs/inline-functions.html#reified-type-parameters), that means change `` to ``, if possible. If you have a chain of functions with type parameters you will probably have to make all of them `reified`. - If you don't actually use Gson's `TypeToken` for any Gson method, use a general purpose 'type token' implementation provided by a different library instead, for example Guava's [`com.google.common.reflect.TypeToken`](https://javadoc.io/doc/com.google.guava/guava/latest/com/google/common/reflect/TypeToken.html). For backward compatibility it is possible to restore Gson's old behavior of allowing `TypeToken` to capture type variables by setting the [system property](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/System.html#setProperty(java.lang.String,java.lang.String)) `gson.allowCapturingTypeVariables` to `"true"`, **however**: - This does not solve any of the type-safety problems mentioned above; in the long term you should prefer one of the other solutions listed above. This system property might be removed in future Gson versions. - You should only ever set the property to `"true"`, but never to any other value or manually clear it. Otherwise this might counteract any libraries you are using which might have deliberately set the system property because they rely on its behavior. ## Android - R8 / ProGuard Gson is not recommended on Android due to the expectation of R8 optimization, or other environments where you intend to minify (shrink/optimize/obfuscate) your build, such as with ProGuard. While it is possible to make it work with minification, many features of the library will not work in this environment due to the open ended reflection performed in Gson. This is true even with the most up to date ProGuard file, included since Gson 2.11.0. If you do want to make Gson work with minification, you must test your code after minification has been applied, and can choose to either: ### Constrain reflected classes - Ensure all of your objects have a no-arg constructor (and be a top-level or static class to avoid implicit constructor arguments) - Annotate all fields with `@SerializedName()` If you still use a Gson version older than 2.11.0 or if you are using ProGuard for a non-Android project ([related ProGuard issue](https://github.com/Guardsquare/proguard/issues/337)), you may need to copy the rules from Gson's [`gson.pro`](gson/src/main/resources/META-INF/proguard/gson.pro) file into your own ProGuard configuration file. ### Avoid Reflection It is possible to avoid reflection when using Gson. This will mean you will need to have a `TypeAdapter` or `TypeAdapterFactory` for every type you might want to serialize or deserialize, or that you are only using Gson through its explicit JSON API via classes like `JsonObject` and `JsonArray`, or are manually reading or writing JSON data using `JsonReader` and `JsonWriter`. You can ensure reflection isn't being used by calling [`GsonBuilder.addReflectionAccessFilter()`](https://javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/GsonBuilder.html#addReflectionAccessFilter(com.google.gson.ReflectionAccessFilter)) to add a filter which always returns `BLOCK_ALL`. ================================================ FILE: UserGuide.md ================================================ # Gson User Guide 1. [Overview](#overview) 2. [Goals for Gson](#goals-for-gson) 3. [Gson Performance and Scalability](#gson-performance-and-scalability) 4. [Gson Users](#gson-users) 5. [Using Gson](#using-gson) * [Using Gson with Gradle/Android](#using-gson-with-gradleandroid) * [Using Gson with Maven](#using-gson-with-maven) * [Primitives Examples](#primitives-examples) * [Object Examples](#object-examples) * [Finer Points with Objects](#finer-points-with-objects) * [Nested Classes (including Inner Classes)](#nested-classes-including-inner-classes) * [Array Examples](#array-examples) * [Collections Examples](#collections-examples) * [Collections Limitations](#collections-limitations) * [Maps Examples](#maps-examples) * [Serializing and Deserializing Generic Types](#serializing-and-deserializing-generic-types) * [Serializing and Deserializing Collection with Objects of Arbitrary Types](#serializing-and-deserializing-collection-with-objects-of-arbitrary-types) * [Built-in Serializers and Deserializers](#built-in-serializers-and-deserializers) * [Custom Serialization and Deserialization](#custom-serialization-and-deserialization) * [Writing a Serializer](#writing-a-serializer) * [Writing a Deserializer](#writing-a-deserializer) * [Writing an Instance Creator](#writing-an-instance-creator) * [InstanceCreator for a Parameterized Type](#instancecreator-for-a-parameterized-type) * [Compact Vs. Pretty Printing for JSON Output Format](#compact-vs-pretty-printing-for-json-output-format) * [Null Object Support](#null-object-support) * [Versioning Support](#versioning-support) * [Excluding Fields From Serialization and Deserialization](#excluding-fields-from-serialization-and-deserialization) * [Java Modifier Exclusion](#java-modifier-exclusion) * [Gson's `@Expose`](#gsons-expose) * [User Defined Exclusion Strategies](#user-defined-exclusion-strategies) * [JSON Field Naming Support](#json-field-naming-support) * [Sharing State Across Custom Serializers and Deserializers](#sharing-state-across-custom-serializers-and-deserializers) * [Streaming](#streaming) 6. [Issues in Designing Gson](#issues-in-designing-gson) 7. [Future Enhancements to Gson](#future-enhancements-to-gson) ## 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. ## 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 ## 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. ## 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. ## 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. ## Using Gson with Gradle/Android ```gradle dependencies { implementation 'com.google.code.gson:gson:2.13.2' } ``` ## 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 com.google.code.gson gson 2.13.2 compile ``` That is it, now your Maven project is Gson enabled. ### 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 i = gson.fromJson("1", int.class); Integer intObj = gson.fromJson("1", Integer.class); Long longObj = gson.fromJson("1", Long.class); Boolean boolObj = gson.fromJson("false", Boolean.class); String str = gson.fromJson("\"abc\"", String.class); String[] strArray = gson.fromJson("[\"abc\"]", String[].class); ``` ### 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); // ==> {"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 ``` #### **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 are ignored and not included in serialization or deserialization. * Anonymous and local classes are excluded. They will be serialized as JSON `null` and when deserialized their JSON value is ignored and `null` is returned. Convert the classes to `static` nested classes to enable serialization and deserialization for them. ### 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 { 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. ### 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. ### Collections Examples ```java Gson gson = new Gson(); Collection ints = Arrays.asList(1,2,3,4,5); // Serialization String json = gson.toJson(ints); // ==> [1,2,3,4,5] // Deserialization TypeToken> collectionType = new TypeToken>(){}; // Note: For older Gson versions it is necessary to use `collectionType.getType()` as argument below, // this is however not type-safe and care must be taken to specify the correct type for the local variable Collection 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. #### 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. ### 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 stringMap = new LinkedHashMap<>(); stringMap.put("key", "value"); stringMap.put(null, "null-entry"); // Serialization String json = gson.toJson(stringMap); // ==> {"key":"value","null":"null-entry"} Map intMap = new LinkedHashMap<>(); intMap.put(2, 4); intMap.put(3, 6); // Serialization String json = gson.toJson(intMap); // ==> {"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(); TypeToken> mapType = new TypeToken>(){}; String json = "{\"key\": \"value\"}"; // Deserialization // Note: For older Gson versions it is necessary to use `mapType.getType()` as argument below, // this is however not type-safe and care must be taken to specify the correct type for the local variable Map 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 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); // ==> [[{"firstName":"John","lastName":"Doe"},30],[{"firstName":"Jane","lastName":"Doe"},35]] Map stringMap = new LinkedHashMap<>(); stringMap.put("key", "value"); // Serialization; non-complex map is serialized as a regular JSON object String json = gson.toJson(stringMap); // ==> {"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. ### 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 value; } Gson gson = new Gson(); Foo foo = new Foo(); 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`, 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>() {}.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. ### 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 genericized version of the 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`. 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`. ### 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). ### Custom Serialization and Deserialization Sometimes the 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 1. if the type adapter implements more than one of these interfaces, in that case it registers the adapter for all of them. 2. if the type adapter is for the Object class or JsonElement or any of its subclasses, in that case it throws IllegalArgumentException because overriding the built-in adapters for these types is not supported. #### Writing a Serializer Here is an example of how to write a custom serializer for JodaTime `DateTime` class. ```java private class DateTimeSerializer implements JsonSerializer { 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. #### Writing a Deserializer Here is an example of how to write a custom deserializer for JodaTime DateTime class. ```java private class DateTimeDeserializer implements JsonDeserializer { 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` 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, String)` which returns an instance of `Id` Gson supports registering a single handler for this. You can also register a specific handler for a specific generic type (say `Id` 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. ### 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 { 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 #### 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 extends ArrayList { } class MyListInstanceCreator implements InstanceCreator> { @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 { private final Class classOfId; private final long value; public Id(Class classOfId, long value) { this.classOfId = classOfId; this.value = value; } } class IdInstanceCreator implements InstanceCreator> { 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` where the actual instance should be bound to `Id`. 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. ### 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](#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); ``` ### 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: ```json {"s":null,"i":5} null ``` ### 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: ```json {"newField":"new","field":"old"} {"newerField":"newer","newField":"new","field":"old"} ``` ### 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](#custom-serialization-and-deserialization). #### 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(); ``` #### 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. #### 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; 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} ``` ### 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. ### 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. ### Streaming In addition Gson's object model and data binding, you can use Gson to read from and write to a stream with the classes [`JsonReader`](https://javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/stream/JsonReader.html) and [`JsonWriter`](https://javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/stream/JsonWriter.html). These classes operate on a JSON document as a sequence of tokens that are traversed in depth-first order. Because the streams operate on one token at a time, they impose minimal memory overhead. You can also combine streaming and object model access to get the best of both approaches. For example by starting to manually read a JSON document using a `JsonReader` and then using [`Gson#fromJson(JsonReader, ...)`](https://javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/Gson.html#fromJson(com.google.gson.stream.JsonReader,java.lang.reflect.Type)) to read a nested value, or starting to manually write a JSON document using a `JsonWriter` and then using [`Gson#toJson(..., JsonWriter)`](https://javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/Gson.html#toJson(java.lang.Object,java.lang.reflect.Type,com.google.gson.stream.JsonWriter)) to write a nested value. ## 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 includes a comparison of Gson with other Java libraries that can be used for JSON conversion. ## 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. ================================================ FILE: extras/README.md ================================================ # 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. ================================================ FILE: extras/pom.xml ================================================ 4.0.0 com.google.code.gson gson-parent 2.13.3-SNAPSHOT gson-extras 2.13.3-SNAPSHOT 2008 Gson Extras Google Gson grab bag of utilities, type adapters, etc. 2025-09-10T20:39:14Z Apache-2.0 https://www.apache.org/licenses/LICENSE-2.0.txt Google, Inc. https://www.google.com com.google.code.gson gson 2.13.3-SNAPSHOT javax.annotation jsr250-api 1.0 junit junit test com.google.truth truth test Inderjeet Singh Joel Leitch Google Inc. Jesse Wilson Square Inc. gson-extras-2.12.1 ================================================ FILE: extras/src/main/java/com/google/gson/extras/examples/rawcollections/RawCollectionsExample.java ================================================ /* * 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 com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonParser; import java.util.ArrayList; import java.util.Collection; @SuppressWarnings({"PrivateConstructorForUtilityClass", "SystemOut"}) 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); } } ================================================ FILE: extras/src/main/java/com/google/gson/interceptors/Intercept.java ================================================ /* * 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: * *

Here is an example of how this annotation is used: * *

 * @Intercept(postDeserialize=UserValidator.class)
 * public class User {
 *   String name;
 *   String password;
 *   String emailAddress;
 * }
 *
 * public class UserValidator implements JsonPostDeserializer<User> {
 *   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.
 *     }
 *   }
 * }
 * 
* * @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 postDeserialize(); } ================================================ FILE: extras/src/main/java/com/google/gson/interceptors/InterceptorFactory.java ================================================ /* * 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.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 TypeAdapter create(Gson gson, TypeToken type) { Intercept intercept = type.getRawType().getAnnotation(Intercept.class); if (intercept == null) { return null; } TypeAdapter delegate = gson.getDelegateAdapter(this, type); return new InterceptorAdapter<>(delegate, intercept); } static class InterceptorAdapter extends TypeAdapter { private final TypeAdapter delegate; private final JsonPostDeserializer postDeserializer; @SuppressWarnings("unchecked") // ? public InterceptorAdapter(TypeAdapter delegate, Intercept intercept) { try { this.delegate = delegate; this.postDeserializer = intercept.postDeserialize().getDeclaredConstructor().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; } } } ================================================ FILE: extras/src/main/java/com/google/gson/interceptors/JsonPostDeserializer.java ================================================ /* * 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 { /** This method is called by Gson after the object has been deserialized from Json. */ public void postDeserialize(T object); } ================================================ FILE: extras/src/main/java/com/google/gson/typeadapters/PostConstructAdapterFactory.java ================================================ /* * 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 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.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import javax.annotation.PostConstruct; public class PostConstructAdapterFactory implements TypeAdapterFactory { // copied from https://gist.github.com/swankjesse/20df26adaf639ed7fd160f145a0b661a @Override public TypeAdapter create(Gson gson, TypeToken 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 delegate = gson.getDelegateAdapter(this, type); return new PostConstructAdapter<>(delegate, m); } } } return null; } static final class PostConstructAdapter extends TypeAdapter { private final TypeAdapter delegate; private final Method method; public PostConstructAdapter(TypeAdapter 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(e); } 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); } } } ================================================ FILE: extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java ================================================ /* * 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.errorprone.annotations.CanIgnoreReturnValue; 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: * *
{@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;
 * }
 * }
* *

Without additional type information, the serialized JSON is ambiguous. Is the bottom shape in * this drawing a rectangle or a diamond? * *

{@code
 * {
 *   "bottomShape": {
 *     "width": 10,
 *     "height": 5,
 *     "x": 0,
 *     "y": 0
 *   },
 *   "topShape": {
 *     "radius": 2,
 *     "x": 4,
 *     "y": 1
 *   }
 * }
 * }
* * This class addresses this problem by adding type information to the serialized JSON and honoring * that type information when the JSON is deserialized: * *
{@code
 * {
 *   "bottomShape": {
 *     "type": "Diamond",
 *     "width": 10,
 *     "height": 5,
 *     "x": 0,
 *     "y": 0
 *   },
 *   "topShape": {
 *     "type": "Circle",
 *     "radius": 2,
 *     "x": 4,
 *     "y": 1
 *   }
 * }
 * }
* * Both the type field name ({@code "type"}) and the type labels ({@code "Rectangle"}) are * configurable. * *

Registering Types

* * 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. * *
{@code
 * RuntimeTypeAdapterFactory shapeAdapterFactory
 *     = RuntimeTypeAdapterFactory.of(Shape.class, "type");
 * }
* * 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. * *
{@code
 * shapeAdapterFactory.registerSubtype(Rectangle.class, "Rectangle");
 * shapeAdapterFactory.registerSubtype(Circle.class, "Circle");
 * shapeAdapterFactory.registerSubtype(Diamond.class, "Diamond");
 * }
* * Finally, register the type adapter factory in your application's GSON builder: * *
{@code
 * Gson gson = new GsonBuilder()
 *     .registerTypeAdapterFactory(shapeAdapterFactory)
 *     .create();
 * }
* * Like {@code GsonBuilder}, this API supports chaining: * *
{@code
 * RuntimeTypeAdapterFactory shapeAdapterFactory = RuntimeTypeAdapterFactory.of(Shape.class)
 *     .registerSubtype(Rectangle.class)
 *     .registerSubtype(Circle.class)
 *     .registerSubtype(Diamond.class);
 * }
* *

Serialization and deserialization

* * In order to serialize and deserialize a polymorphic object, you must specify the base type * explicitly. * *
{@code
 * Diamond diamond = new Diamond();
 * String json = gson.toJson(diamond, Shape.class);
 * }
* * And then: * *
{@code
 * Shape shape = gson.fromJson(json, Shape.class);
 * }
*/ public final class RuntimeTypeAdapterFactory implements TypeAdapterFactory { private final Class baseType; private final String typeFieldName; private final Map> labelToSubtype = new LinkedHashMap<>(); private final Map, 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 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 RuntimeTypeAdapterFactory of( Class baseType, String typeFieldName, boolean maintainType) { return new RuntimeTypeAdapterFactory<>(baseType, typeFieldName, maintainType); } /** * Creates a new runtime type adapter for {@code baseType} using {@code typeFieldName} as the type * field name. Type field names are case sensitive. */ public static RuntimeTypeAdapterFactory of(Class 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 RuntimeTypeAdapterFactory of(Class 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. */ @CanIgnoreReturnValue public RuntimeTypeAdapterFactory 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. */ @CanIgnoreReturnValue public RuntimeTypeAdapterFactory registerSubtype(Class 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. */ @CanIgnoreReturnValue public RuntimeTypeAdapterFactory registerSubtype(Class type) { return registerSubtype(type, type.getSimpleName()); } @Override public TypeAdapter create(Gson gson, TypeToken type) { if (type == null) { return null; } Class rawType = type.getRawType(); boolean handle = recognizeSubtypes ? baseType.isAssignableFrom(rawType) : baseType.equals(rawType); if (!handle) { return null; } TypeAdapter jsonElementAdapter = gson.getAdapter(JsonElement.class); Map> labelToDelegate = new LinkedHashMap<>(); Map, TypeAdapter> subtypeToDelegate = new LinkedHashMap<>(); for (Map.Entry> 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() { @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 delegate = (TypeAdapter) 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 delegate = (TypeAdapter) 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 e : jsonObject.entrySet()) { clone.add(e.getKey(), e.getValue()); } jsonElementAdapter.write(out, clone); } }.nullSafe(); } } ================================================ FILE: extras/src/main/java/com/google/gson/typeadapters/UtcDateTypeAdapter.java ================================================ /* * 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.JsonParseException; import com.google.gson.TypeAdapter; 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.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; public final class UtcDateTypeAdapter extends TypeAdapter { private static 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 { if (in.peek().equals(JsonToken.NULL)) { in.nextNull(); return null; } else { 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/2.8/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; // always use 0 otherwise returned date will include millis of current time int milliseconds = 0; 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 | 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; } } ================================================ FILE: extras/src/test/java/com/google/gson/interceptors/InterceptorTest.java ================================================ /* * 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 static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; 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 org.junit.Before; import org.junit.Test; /** * Unit tests for {@link Intercept} and {@link JsonPostDeserializer}. * * @author Inderjeet Singh */ public final class InterceptorTest { private Gson gson; @Before public void setUp() throws Exception { this.gson = new GsonBuilder() .registerTypeAdapterFactory(new InterceptorFactory()) .enableComplexMapKeySerialization() .create(); } @Test public void testExceptionsPropagated() { var e = assertThrows(JsonParseException.class, () -> gson.fromJson("{}", User.class)); assertThat(e).hasMessageThat().isEqualTo("name and password are required fields."); } @Test public void testTopLevelClass() { User user = gson.fromJson("{name:'bob',password:'pwd'}", User.class); assertThat(user.email).isEqualTo(User.DEFAULT_EMAIL); } @Test public void testList() { List list = gson.fromJson("[{name:'bob',password:'pwd'}]", new TypeToken>() {}.getType()); User user = list.get(0); assertThat(user.email).isEqualTo(User.DEFAULT_EMAIL); } @Test public void testCollection() { Collection list = gson.fromJson( "[{name:'bob',password:'pwd'}]", new TypeToken>() {}.getType()); User user = list.iterator().next(); assertThat(user.email).isEqualTo(User.DEFAULT_EMAIL); } @Test public void testMapKeyAndValues() { Type mapType = new TypeToken>() {}.getType(); var e = assertThrows( JsonSyntaxException.class, () -> gson.fromJson("[[{name:'bob',password:'pwd'},{}]]", mapType)); assertThat(e).hasMessageThat().isEqualTo("Address city, state and zip are required fields."); Map map = gson.fromJson( "[[{name:'bob',password:'pwd'},{city:'Mountain View',state:'CA',zip:'94043'}]]", mapType); Entry entry = map.entrySet().iterator().next(); assertThat(entry.getKey().email).isEqualTo(User.DEFAULT_EMAIL); assertThat(entry.getValue().firstLine).isEqualTo(Address.DEFAULT_FIRST_LINE); } @Test public void testField() { UserGroup userGroup = gson.fromJson("{user:{name:'bob',password:'pwd'}}", UserGroup.class); assertThat(userGroup.user.email).isEqualTo(User.DEFAULT_EMAIL); } @Test public void testCustomTypeAdapter() { Gson gson = new GsonBuilder() .registerTypeAdapter( User.class, new TypeAdapter() { @Override public void write(JsonWriter out, User value) throws IOException { throw new UnsupportedOperationException(); } @Override public User read(JsonReader in) throws IOException { in.beginObject(); assertThat(in.nextName()).isEqualTo("name"); String name = in.nextString(); assertThat(in.nextName()).isEqualTo("password"); 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); assertThat(userGroup.user.email).isEqualTo(User.DEFAULT_EMAIL); } @Test public void testDirectInvocationOfTypeAdapter() throws Exception { TypeAdapter adapter = gson.getAdapter(UserGroup.class); UserGroup userGroup = adapter.fromJson("{\"user\":{\"name\":\"bob\",\"password\":\"pwd\"}}"); assertThat(userGroup.user.email).isEqualTo(User.DEFAULT_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; User(String name, String password) { this.name = name; this.password = password; } } public static final class UserValidator implements JsonPostDeserializer { @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
{ @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; } } } } ================================================ FILE: extras/src/test/java/com/google/gson/typeadapters/PostConstructAdapterFactoryTest.java ================================================ /* * 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 static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.Arrays; import java.util.List; import java.util.Objects; import javax.annotation.PostConstruct; import org.junit.Test; public class PostConstructAdapterFactoryTest { @Test public void test() throws Exception { Gson gson = new GsonBuilder().registerTypeAdapterFactory(new PostConstructAdapterFactory()).create(); Sandwich unused = gson.fromJson("{\"bread\": \"white\", \"cheese\": \"cheddar\"}", Sandwich.class); var e = assertThrows( IllegalArgumentException.class, () -> gson.fromJson( "{\"bread\": \"cheesey bread\", \"cheese\": \"swiss\"}", Sandwich.class)); assertThat(e).hasMessageThat().isEqualTo("too cheesey"); } @Test 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); assertThat(json) .isEqualTo( "{\"sandwiches\":[{\"bread\":\"white\",\"cheese\":\"cheddar\"}," + "{\"bread\":\"whole wheat\",\"cheese\":\"swiss\"}]}"); MultipleSandwiches sandwichesFromJson = gson.fromJson(json, MultipleSandwiches.class); assertThat(sandwichesFromJson).isEqualTo(sandwiches); } @SuppressWarnings({"overrides", "EqualsHashCode"}) // for missing hashCode() override 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; } Sandwich other = (Sandwich) o; return Objects.equals(this.bread, other.bread) && Objects.equals(this.cheese, other.cheese); } } @SuppressWarnings({"overrides", "EqualsHashCode"}) // for missing hashCode() override static class MultipleSandwiches { public List sandwiches; public MultipleSandwiches(List sandwiches) { this.sandwiches = sandwiches; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof MultipleSandwiches)) { return false; } MultipleSandwiches other = (MultipleSandwiches) o; return Objects.equals(this.sandwiches, other.sandwiches); } } } ================================================ FILE: extras/src/test/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactoryTest.java ================================================ /* * 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 static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; import com.google.gson.TypeAdapterFactory; import org.junit.Test; public final class RuntimeTypeAdapterFactoryTest { @Test public void testRuntimeTypeAdapter() { RuntimeTypeAdapterFactory rta = RuntimeTypeAdapterFactory.of(BillingInstrument.class).registerSubtype(CreditCard.class); Gson gson = new GsonBuilder().registerTypeAdapterFactory(rta).create(); CreditCard original = new CreditCard("Jesse", 234); assertThat(gson.toJson(original, BillingInstrument.class)) .isEqualTo("{\"type\":\"CreditCard\",\"cvv\":234,\"ownerName\":\"Jesse\"}"); BillingInstrument deserialized = gson.fromJson("{type:'CreditCard',cvv:234,ownerName:'Jesse'}", BillingInstrument.class); assertThat(deserialized.ownerName).isEqualTo("Jesse"); assertThat(deserialized).isInstanceOf(CreditCard.class); } @Test 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 rta = RuntimeTypeAdapterFactory.of(BillingInstrument.class) .recognizeSubtypes() .registerSubtype(CreditCard.class); Gson gson = new GsonBuilder().registerTypeAdapterFactory(rta).create(); CreditCard original = new CreditCard("Jesse", 234); assertThat(gson.toJson(original)) .isEqualTo("{\"type\":\"CreditCard\",\"cvv\":234,\"ownerName\":\"Jesse\"}"); BillingInstrument deserialized = gson.fromJson("{type:'CreditCard',cvv:234,ownerName:'Jesse'}", BillingInstrument.class); assertThat(deserialized.ownerName).isEqualTo("Jesse"); assertThat(deserialized).isInstanceOf(CreditCard.class); } @Test public void testRuntimeTypeIsBaseType() { TypeAdapterFactory rta = RuntimeTypeAdapterFactory.of(BillingInstrument.class) .registerSubtype(BillingInstrument.class); Gson gson = new GsonBuilder().registerTypeAdapterFactory(rta).create(); BillingInstrument original = new BillingInstrument("Jesse"); assertThat(gson.toJson(original, BillingInstrument.class)) .isEqualTo("{\"type\":\"BillingInstrument\",\"ownerName\":\"Jesse\"}"); BillingInstrument deserialized = gson.fromJson("{type:'BillingInstrument',ownerName:'Jesse'}", BillingInstrument.class); assertThat(deserialized.ownerName).isEqualTo("Jesse"); } @Test public void testNullBaseType() { assertThrows(NullPointerException.class, () -> RuntimeTypeAdapterFactory.of(null)); } @Test public void testNullTypeFieldName() { assertThrows( NullPointerException.class, () -> RuntimeTypeAdapterFactory.of(BillingInstrument.class, null)); } @Test public void testNullSubtype() { RuntimeTypeAdapterFactory rta = RuntimeTypeAdapterFactory.of(BillingInstrument.class); assertThrows(NullPointerException.class, () -> rta.registerSubtype(null)); } @Test public void testNullLabel() { RuntimeTypeAdapterFactory rta = RuntimeTypeAdapterFactory.of(BillingInstrument.class); assertThrows(NullPointerException.class, () -> rta.registerSubtype(CreditCard.class, null)); } @Test public void testDuplicateSubtype() { RuntimeTypeAdapterFactory rta = RuntimeTypeAdapterFactory.of(BillingInstrument.class); rta.registerSubtype(CreditCard.class, "CC"); var e = assertThrows( IllegalArgumentException.class, () -> rta.registerSubtype(CreditCard.class, "Visa")); assertThat(e).hasMessageThat().isEqualTo("types and labels must be unique"); } @Test public void testDuplicateLabel() { RuntimeTypeAdapterFactory rta = RuntimeTypeAdapterFactory.of(BillingInstrument.class); rta.registerSubtype(CreditCard.class, "CC"); var e = assertThrows( IllegalArgumentException.class, () -> rta.registerSubtype(BankTransfer.class, "CC")); assertThat(e).hasMessageThat().isEqualTo("types and labels must be unique"); } @Test public void testDeserializeMissingTypeField() { TypeAdapterFactory billingAdapter = RuntimeTypeAdapterFactory.of(BillingInstrument.class).registerSubtype(CreditCard.class); Gson gson = new GsonBuilder().registerTypeAdapterFactory(billingAdapter).create(); var e = assertThrows( JsonParseException.class, () -> gson.fromJson("{ownerName:'Jesse'}", BillingInstrument.class)); assertThat(e) .hasMessageThat() .isEqualTo( "cannot deserialize " + BillingInstrument.class + " because it does not define a field named type"); } @Test public void testDeserializeMissingSubtype() { TypeAdapterFactory billingAdapter = RuntimeTypeAdapterFactory.of(BillingInstrument.class).registerSubtype(BankTransfer.class); Gson gson = new GsonBuilder().registerTypeAdapterFactory(billingAdapter).create(); var e = assertThrows( JsonParseException.class, () -> gson.fromJson("{type:'CreditCard',ownerName:'Jesse'}", BillingInstrument.class)); assertThat(e) .hasMessageThat() .isEqualTo( "cannot deserialize " + BillingInstrument.class + " subtype named CreditCard; did you forget to register a subtype?"); } @Test public void testSerializeMissingSubtype() { TypeAdapterFactory billingAdapter = RuntimeTypeAdapterFactory.of(BillingInstrument.class).registerSubtype(BankTransfer.class); Gson gson = new GsonBuilder().registerTypeAdapterFactory(billingAdapter).create(); var e = assertThrows( JsonParseException.class, () -> gson.toJson(new CreditCard("Jesse", 456), BillingInstrument.class)); assertThat(e) .hasMessageThat() .isEqualTo( "cannot serialize " + CreditCard.class.getName() + "; did you forget to register a subtype?"); } @Test public void testSerializeCollidingTypeFieldName() { TypeAdapterFactory billingAdapter = RuntimeTypeAdapterFactory.of(BillingInstrument.class, "cvv") .registerSubtype(CreditCard.class); Gson gson = new GsonBuilder().registerTypeAdapterFactory(billingAdapter).create(); var e = assertThrows( JsonParseException.class, () -> gson.toJson(new CreditCard("Jesse", 456), BillingInstrument.class)); assertThat(e) .hasMessageThat() .isEqualTo( "cannot serialize " + CreditCard.class.getName() + " because it already defines a field named cvv"); } @Test 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); assertThat(deserialized.instrument).isNull(); } 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; } } } ================================================ FILE: extras/src/test/java/com/google/gson/typeadapters/UtcDateTypeAdapterTest.java ================================================ /* * 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 static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; 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 org.junit.Test; @SuppressWarnings("JavaUtilDate") public final class UtcDateTypeAdapterTest { private final Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new UtcDateTypeAdapter()).create(); @Test public void testLocalTimeZone() { Date expected = new Date(); String json = gson.toJson(expected); Date actual = gson.fromJson(json, Date.class); assertThat(actual.getTime()).isEqualTo(expected.getTime()); } @Test 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); assertThat(actual.getTime()).isEqualTo(expected.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. */ @Test public void testUtcDatesOnJdkBefore1_7() { Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new UtcDateTypeAdapter()).create(); Date date = gson.fromJson("'2014-12-05T04:00:00.000Z'", Date.class); assertThat(date.getTime()).isEqualTo(1417752000000L); } @Test 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); assertThat(actualJson).isEqualTo(expectedJson); Date actual = gson.fromJson(expectedJson, Date.class); assertThat(actual.getTime()).isEqualTo(expected.getTime()); } @Test public void testNullDateSerialization() { String json = gson.toJson(null, Date.class); assertThat(json).isEqualTo("null"); } @Test public void testWellFormedParseException() { var e = assertThrows( JsonParseException.class, () -> gson.fromJson("2017-06-20T14:32:30", Date.class)); assertThat(e) .hasMessageThat() .isEqualTo( "java.text.ParseException: Failed to parse date ['2017-06-20T14']: 2017-06-20T14"); } } ================================================ FILE: gson/LICENSE ================================================ 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. ================================================ FILE: gson/README.md ================================================ # 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`. ================================================ FILE: gson/pom.xml ================================================ 4.0.0 com.google.code.gson gson-parent 2.13.3-SNAPSHOT gson Gson Apache-2.0 https://www.apache.org/licenses/LICENSE-2.0.txt 2025-09-10T20:39:14Z **/Java17* com.google.errorprone error_prone_annotations 2.47.0 junit junit test com.google.truth truth test com.google.guava guava-testlib 33.5.0-jre test com.google.guava guava 33.5.0-jre test org.codehaus.mojo templating-maven-plugin 3.1.0 filtering-java-templates filter-sources ${project.basedir}/src/main/java-templates ${project.build.directory}/generated-sources/java-templates org.apache.maven.plugins maven-compiler-plugin default-compile module-info.java default-testCompile test-compile testCompile ${excludeTestCompilation} biz.aQute.bnd bnd-maven-plugin 6.4.0 bnd-process org.apache.maven.plugins maven-surefire-plugin --illegal-access=deny org.apache.maven.plugins maven-failsafe-plugin integration-test verify com.github.wvengen proguard-maven-plugin 2.7.0 obfuscate-test-class process-test-classes proguard com.guardsquare proguard-base 7.8.2 com.guardsquare proguard-core 9.3.0 ${maven.test.skip} true test-classes-obfuscated-injar test-classes-obfuscated-outjar **/*.class ${project.basedir}/src/test/resources/testcases-proguard.conf ${project.build.directory}/classes ${java.home}/jmods/java.base.jmod org.apache.maven.plugins maven-resources-plugin 3.4.0 pre-obfuscate-class test-compile copy-resources ${maven.test.skip} ${project.build.directory}/test-classes-obfuscated-injar/com/google/gson/functional true ${project.build.directory}/test-classes/com/google/gson/functional EnumWithObfuscatedTest.class EnumWithObfuscatedTest$Gender.class post-obfuscate-class process-test-classes copy-resources ${maven.test.skip} ${project.build.directory}/test-classes/com/google/gson/functional true ${project.build.directory}/test-classes-obfuscated-outjar/com/google/gson/functional EnumWithObfuscatedTest.class EnumWithObfuscatedTest$Gender.class org.apache.maven.plugins maven-jar-plugin ${project.build.outputDirectory}/META-INF/MANIFEST.MF org.moditect moditect-maven-plugin 1.3.0.Final add-module-info package add-module-info 9 ${project.build.sourceDirectory}/module-info.java true org.apache.maven.plugins maven-javadoc-plugin com.google.gson.internal:com.google.gson.internal.bind org.sonatype.central central-publishing-maven-plugin JDK17 [17,) 17 JDK25 [25,) com/google/gson/functional/EnumWithObfuscatedTest.java com.github.wvengen proguard-maven-plugin true gson-subset ${project.build.directory}/gson-subset-src org.apache.maven.plugins maven-resources-plugin prepare-gson-subset-src process-sources copy-resources ${gsonSubsetSrcDir} true ${project.build.sourceDirectory} com/google/gson/FormattingStyle.java com/google/gson/JsonArray.java com/google/gson/JsonElement.java com/google/gson/JsonIOException.java com/google/gson/JsonNull.java com/google/gson/JsonObject.java com/google/gson/JsonParseException.java com/google/gson/JsonParser.java com/google/gson/JsonPrimitive.java com/google/gson/JsonStreamParser.java com/google/gson/JsonSyntaxException.java com/google/gson/Strictness.java com/google/gson/TypeAdapter.java com/google/gson/package-info.java com/google/gson/stream/JsonReader.java com/google/gson/stream/JsonScope.java com/google/gson/stream/JsonToken.java com/google/gson/stream/JsonWriter.java com/google/gson/stream/MalformedJsonException.java com/google/gson/stream/package-info.java com/google/gson/internal/JsonReaderInternalAccess.java com/google/gson/internal/LazilyParsedNumber.java com/google/gson/internal/LinkedTreeMap.java com/google/gson/internal/NonNullElementWrapperList.java com/google/gson/internal/NumberLimits.java com/google/gson/internal/Streams.java com/google/gson/internal/TroubleshootingGuide.java com/google/gson/internal/bind/JsonElementTypeAdapter.java com/google/gson/internal/bind/JsonTreeReader.java com/google/gson/internal/bind/JsonTreeWriter.java org.apache.maven.plugins maven-compiler-plugin default-compile ${gsonSubsetSrcDir} default-testCompile test-compile testCompile com/google/gson/internal/bind/JsonTreeReaderTest.java com/google/gson/internal/bind/JsonTreeWriterTest.java com/google/gson/internal/LazilyParsedNumberTest.java com/google/gson/internal/LinkedTreeMapSuiteTest.java com/google/gson/internal/LinkedTreeMapTest.java com/google/gson/internal/StreamsTest.java com/google/gson/stream/JsonReaderPathTest.java com/google/gson/stream/JsonReaderTest.java com/google/gson/stream/JsonWriterTest.java com/google/gson/JsonArrayAsListSuiteTest.java com/google/gson/JsonArrayAsListTest.java com/google/gson/JsonArrayTest.java com/google/gson/JsonNullTest.java com/google/gson/JsonObjectAsMapSuiteTest.java com/google/gson/JsonObjectAsMapTest.java com/google/gson/JsonObjectTest.java com/google/gson/JsonParserParameterizedTest.java com/google/gson/JsonPrimitiveTest.java com/google/gson/JsonStreamParserTest.java com/google/gson/SubsetTest.java com/google/gson/TypeAdapterTest.java com.github.wvengen proguard-maven-plugin true ================================================ FILE: gson/src/main/java/com/google/gson/ExclusionStrategy.java ================================================ /* * 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 class should * be serialized or deserialized as part of the JSON output/input. * *

The following are a few examples that shows how you can use this exclusion mechanism. * *

Exclude fields and objects based on a particular class type: * *

 * private static class SpecificClassExclusionStrategy implements ExclusionStrategy {
 *   private final Class<?> excludedThisClass;
 *
 *   public SpecificClassExclusionStrategy(Class<?> excludedThisClass) {
 *     this.excludedThisClass = excludedThisClass;
 *   }
 *
 *   public boolean shouldSkipClass(Class<?> clazz) {
 *     return excludedThisClass.equals(clazz);
 *   }
 *
 *   public boolean shouldSkipField(FieldAttributes f) {
 *     return excludedThisClass.equals(f.getDeclaredClass());
 *   }
 * }
 * 
* *

Excludes fields and objects based on a particular annotation: * *

 * public @interface FooAnnotation {
 *   // some implementation here
 * }
 *
 * // Excludes any field (or class) that is tagged with an "@FooAnnotation"
 * private static class FooAnnotationExclusionStrategy implements ExclusionStrategy {
 *   public boolean shouldSkipClass(Class<?> clazz) {
 *     return clazz.getAnnotation(FooAnnotation.class) != null;
 *   }
 *
 *   public boolean shouldSkipField(FieldAttributes f) {
 *     return f.getAnnotation(FooAnnotation.class) != null;
 *   }
 * }
 * 
* *

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 samples: * *

 * ExclusionStrategy excludeStrings = new UserDefinedExclusionStrategy(String.class);
 * Gson gson = new GsonBuilder()
 *     .setExclusionStrategies(excludeStrings)
 *     .create();
 * 
* *

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: * *

 * ExclusionStrategy excludeStrings = new UserDefinedExclusionStrategy(String.class);
 * Gson gson = new GsonBuilder()
 *     .addDeserializationExclusionStrategy(excludeStrings)
 *     .create();
 * 
* * @author Inderjeet Singh * @author Joel Leitch * @see GsonBuilder#setExclusionStrategies(ExclusionStrategy...) * @see GsonBuilder#addDeserializationExclusionStrategy(ExclusionStrategy) * @see GsonBuilder#addSerializationExclusionStrategy(ExclusionStrategy) * @since 1.4 */ public interface ExclusionStrategy { /** * Decides if a field should be skipped during serialization or deserialization. * * @param f the field object that is under test * @return true if the field should be ignored; otherwise false */ boolean shouldSkipField(FieldAttributes f); /** * Decides if a class should be serialized or deserialized * * @param clazz the class object that is under test * @return true if the class should be ignored; otherwise false */ boolean shouldSkipClass(Class clazz); } ================================================ FILE: gson/src/main/java/com/google/gson/FieldAttributes.java ================================================ /* * 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.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Type; import java.util.Arrays; import java.util.Collection; import java.util.Objects; /** * A data object that stores attributes of a field. * *

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) { this.field = Objects.requireNonNull(f); } /** * Gets the declaring Class that contains this field * * @return the declaring class that contains this field */ public Class getDeclaringClass() { return field.getDeclaringClass(); } /** * Gets the name of the field * * @return the name of the field */ public String getName() { return field.getName(); } /** * Returns the declared generic type of the field. * *

For example, assume the following class definition: * *

   * public class Foo {
   *   private String bar;
   *   private List<String> red;
   * }
   *
   * Type listParameterizedType = new TypeToken<List<String>>() {}.getType();
   * 
* *

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. * *

For example, assume the following class definition: * *

   * public class Foo {
   *   private String bar;
   *   private List<String> red;
   * }
   * 
* *

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(); } /** * Returns the {@code T} annotation object from this field if it exists; 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 getAnnotation(Class annotation) { return field.getAnnotation(annotation); } /** * Returns the annotations that are present on this field. * * @return an array of all the annotations set on the field * @since 1.4 */ public Collection getAnnotations() { return Arrays.asList(field.getAnnotations()); } /** * Returns {@code true} if the field is defined with the {@code modifier}. * *

This method is meant to be called as: * *

   * boolean hasPublicModifier = fieldAttribute.hasModifier(java.lang.reflect.Modifier.PUBLIC);
   * 
* * @see java.lang.reflect.Modifier */ public boolean hasModifier(int modifier) { return (field.getModifiers() & modifier) != 0; } @Override public String toString() { return field.toString(); } } ================================================ FILE: gson/src/main/java/com/google/gson/FieldNamingPolicy.java ================================================ /* * 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. * *

Here are a few examples of the form "Java Field Name" ---> "JSON Field Name": * *

    *
  • someFieldName ---> SomeFieldName *
  • _someFieldName ---> _SomeFieldName *
*/ 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. * *

Here are a few examples of the form "Java Field Name" ---> "JSON Field Name": * *

    *
  • someFieldName ---> Some Field Name *
  • _someFieldName ---> _Some Field Name *
* * @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 (_). * *

Here are a few examples of the form "Java Field Name" ---> "JSON Field Name": * *

    *
  • someFieldName ---> SOME_FIELD_NAME *
  • _someFieldName ---> _SOME_FIELD_NAME *
  • aStringField ---> A_STRING_FIELD *
  • aURL ---> A_U_R_L *
* * @since 2.9.0 */ 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 (_). * *

Here are a few examples of the form "Java Field Name" ---> "JSON Field Name": * *

    *
  • someFieldName ---> some_field_name *
  • _someFieldName ---> _some_field_name *
  • aStringField ---> a_string_field *
  • aURL ---> a_u_r_l *
*/ 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 (-). * *

Here are a few examples of the form "Java Field Name" ---> "JSON Field Name": * *

    *
  • someFieldName ---> some-field-name *
  • _someFieldName ---> _some-field-name *
  • aStringField ---> a-string-field *
  • aURL ---> a-u-r-l *
* * 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 (.). * *

Here are a few examples of the form "Java Field Name" ---> "JSON Field Name": * *

    *
  • someFieldName ---> some.field.name *
  • _someFieldName ---> _some.field.name *
  • aStringField ---> a.string.field *
  • aURL ---> a.u.r.l *
* * 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.4 */ 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; } } ================================================ FILE: gson/src/main/java/com/google/gson/FieldNamingStrategy.java ================================================ /* * 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.SerializedName; import java.lang.reflect.Field; import java.util.Collections; import java.util.List; /** * 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 */ String translateName(Field f); /** * Returns alternative names for this field when it is being deserialized. This is similar to * {@link SerializedName#alternate()}. * * @param f the field object * @return the list of alternative field names. * @since 2.13.1 */ default List alternateNames(Field f) { return Collections.emptyList(); } } ================================================ FILE: gson/src/main/java/com/google/gson/FormattingStyle.java ================================================ /* * Copyright (C) 2022 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.JsonWriter; import java.util.Objects; /** * A class used to control what the serialization output looks like. * *

It currently has the following configuration methods, but more methods might be added in the * future: * *

    *
  • {@link #withNewline(String)} *
  • {@link #withIndent(String)} *
  • {@link #withSpaceAfterSeparators(boolean)} *
* * @see GsonBuilder#setFormattingStyle(FormattingStyle) * @see JsonWriter#setFormattingStyle(FormattingStyle) * @see Wikipedia Newline article * @since 2.11.0 */ public class FormattingStyle { private final String newline; private final String indent; private final boolean spaceAfterSeparators; /** * The default compact formatting style: * *
    *
  • no newline *
  • no indent *
  • no space after {@code ','} and {@code ':'} *
*/ public static final FormattingStyle COMPACT = new FormattingStyle("", "", false); /** * The default pretty printing formatting style: * *
    *
  • {@code "\n"} as newline *
  • two spaces as indent *
  • a space between {@code ':'} and the subsequent value *
*/ public static final FormattingStyle PRETTY = new FormattingStyle("\n", " ", true); private FormattingStyle(String newline, String indent, boolean spaceAfterSeparators) { Objects.requireNonNull(newline, "newline == null"); Objects.requireNonNull(indent, "indent == null"); if (!newline.matches("[\r\n]*")) { throw new IllegalArgumentException( "Only combinations of \\n and \\r are allowed in newline."); } if (!indent.matches("[ \t]*")) { throw new IllegalArgumentException( "Only combinations of spaces and tabs are allowed in indent."); } this.newline = newline; this.indent = indent; this.spaceAfterSeparators = spaceAfterSeparators; } /** * Creates a {@link FormattingStyle} with the specified newline setting. * *

It can be used to accommodate certain OS convention, for example hardcode {@code "\n"} for * Linux and macOS, {@code "\r\n"} for Windows, or call {@link java.lang.System#lineSeparator()} * to match the current OS. * *

Only combinations of {@code \n} and {@code \r} are allowed. * * @param newline the string value that will be used as newline. * @return a newly created {@link FormattingStyle} * @see #getNewline() */ public FormattingStyle withNewline(String newline) { return new FormattingStyle(newline, this.indent, this.spaceAfterSeparators); } /** * Creates a {@link FormattingStyle} with the specified indent string. * *

Only combinations of spaces and tabs are allowed in indent. * * @param indent the string value that will be used as indent. * @return a newly created {@link FormattingStyle} * @see #getIndent() */ public FormattingStyle withIndent(String indent) { return new FormattingStyle(this.newline, indent, this.spaceAfterSeparators); } /** * Creates a {@link FormattingStyle} which either uses a space after the separators {@code ','} * and {@code ':'} in the JSON output, or not. * *

This setting has no effect on the {@linkplain #withNewline(String) configured newline}. If a * non-empty newline is configured, it will always be added after {@code ','} and no space is * added after the {@code ','} in that case. * * @param spaceAfterSeparators whether to output a space after {@code ','} and {@code ':'}. * @return a newly created {@link FormattingStyle} * @see #usesSpaceAfterSeparators() */ public FormattingStyle withSpaceAfterSeparators(boolean spaceAfterSeparators) { return new FormattingStyle(this.newline, this.indent, spaceAfterSeparators); } /** * Returns the string value that will be used as a newline. * * @return the newline value. * @see #withNewline(String) */ public String getNewline() { return this.newline; } /** * Returns the string value that will be used as indent. * * @return the indent value. * @see #withIndent(String) */ public String getIndent() { return this.indent; } /** * Returns whether a space will be used after {@code ','} and {@code ':'}. * * @see #withSpaceAfterSeparators(boolean) */ public boolean usesSpaceAfterSeparators() { return this.spaceAfterSeparators; } } ================================================ FILE: gson/src/main/java/com/google/gson/Gson.java ================================================ /* * 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 static com.google.gson.GsonBuilder.newImmutableList; import com.google.gson.annotations.JsonAdapter; import com.google.gson.internal.ConstructorConstructor; import com.google.gson.internal.Excluder; import com.google.gson.internal.GsonBuildConfig; import com.google.gson.internal.Primitives; import com.google.gson.internal.Streams; 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.SerializationDelegatingTypeAdapter; 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.Writer; import java.lang.reflect.Type; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * 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. * *

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 newline, custom indent, * custom {@link JsonSerializer}s, {@link JsonDeserializer}s, and {@link InstanceCreator}s. * *

Here is an example of how Gson is used for a simple Class: * *

 * 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
 * 
* *

If the type of the object that you are converting is a {@code ParameterizedType} (i.e. has at * least one type argument, for example {@code List}) then for deserialization you must use * a {@code fromJson} method with {@link Type} or {@link TypeToken} parameter to specify the * parameterized type. For serialization specifying a {@code Type} or {@code TypeToken} is optional, * otherwise Gson will use the runtime type of the object. {@link TypeToken} is a class provided by * Gson which helps creating parameterized types. Here is an example showing how this can be done: * *

 * TypeToken<List<MyType>> listType = new TypeToken<List<MyType>>() {};
 * List<MyType> target = new LinkedList<MyType>();
 * target.add(new MyType(1, "abc"));
 *
 * Gson gson = new Gson();
 * // For serialization you normally do not have to specify the type, Gson will use
 * // the runtime type of the objects, however you can also specify it explicitly
 * String json = gson.toJson(target, listType.getType());
 *
 * // But for deserialization you have to specify the type
 * List<MyType> target2 = gson.fromJson(json, listType);
 * 
* *

See the Gson User Guide * for a more complete set of examples. * *

JSON Strictness handling

* * For legacy reasons most of the {@code Gson} methods allow JSON data which does not comply with * the JSON specification when no explicit {@linkplain Strictness strictness} is set (the default). * To specify the strictness of a {@code Gson} instance, you should set it through {@link * GsonBuilder#setStrictness(Strictness)}. * *

For older Gson versions, which don't have the strictness mode API, the following workarounds * can be used: * *

Serialization

* *
    *
  1. Use {@link #getAdapter(Class)} to obtain the adapter for the type to be serialized *
  2. When using an existing {@code JsonWriter}, manually apply the writer settings of this * {@code Gson} instance listed by {@link #newJsonWriter(Writer)}.
    * Otherwise, when not using an existing {@code JsonWriter}, use {@link * #newJsonWriter(Writer)} to construct one. *
  3. Call {@link TypeAdapter#write(JsonWriter, Object)} *
* *

Deserialization

* *
    *
  1. Use {@link #getAdapter(Class)} to obtain the adapter for the type to be deserialized *
  2. When using an existing {@code JsonReader}, manually apply the reader settings of this * {@code Gson} instance listed by {@link #newJsonReader(Reader)}.
    * Otherwise, when not using an existing {@code JsonReader}, use {@link * #newJsonReader(Reader)} to construct one. *
  3. Call {@link TypeAdapter#read(JsonReader)} *
  4. Call {@link JsonReader#peek()} and verify that the result is {@link JsonToken#END_DOCUMENT} * to make sure there is no trailing data *
* * Note that the {@code JsonReader} created this way is only 'legacy strict', it mostly adheres to * the JSON specification but allows small deviations. See {@link * JsonReader#setStrictness(Strictness)} for details. * * @see TypeToken * @author Inderjeet Singh * @author Joel Leitch * @author Jesse Wilson */ public final class Gson { private static final String JSON_NON_EXECUTABLE_PREFIX = ")]}'\n"; /** * This thread local guards against reentrant calls to {@link #getAdapter(TypeToken)}. 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, {@link FutureTypeAdapter}, which is wired up once the initial adapter has * been created. * *

The map stores the type adapters for ongoing {@code getAdapter} calls, with the type token * provided to {@code getAdapter} as key and either {@code FutureTypeAdapter} or a regular {@code * TypeAdapter} as value. */ @SuppressWarnings("ThreadLocalUsage") private final ThreadLocal, TypeAdapter>> threadLocalAdapterResults = new ThreadLocal<>(); private final ConcurrentMap, TypeAdapter> typeTokenCache = new ConcurrentHashMap<>(); private final ConstructorConstructor constructorConstructor; private final JsonAdapterAnnotationTypeAdapterFactory jsonAdapterFactory; final List factories; final Excluder excluder; final FieldNamingStrategy fieldNamingStrategy; final Map> instanceCreators; final boolean serializeNulls; final boolean complexMapKeySerialization; final boolean generateNonExecutableJson; final boolean htmlSafe; final FormattingStyle formattingStyle; final Strictness strictness; final boolean serializeSpecialFloatingPointValues; final boolean useJdkUnsafe; final String datePattern; final int dateStyle; final int timeStyle; final LongSerializationPolicy longSerializationPolicy; final List builderFactories; final List builderHierarchyFactories; final ToNumberStrategy objectToNumberStrategy; final ToNumberStrategy numberToNumberStrategy; final List reflectionFilters; /** * Constructs a Gson object with default configuration. The default configuration has the * following settings: * *

    *
  • The JSON generated by {@code toJson} methods is in compact representation. This means * that all the unneeded white-space is removed. You can change this behavior with {@link * GsonBuilder#setPrettyPrinting()}. *
  • When the JSON generated contains more than one line, the kind of newline and indent to * use can be configured with {@link GsonBuilder#setFormattingStyle(FormattingStyle)}. *
  • 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()}. *
  • 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)}. *
  • 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, int)} or {@link * GsonBuilder#setDateFormat(String)}. *
  • 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()}. *
  • 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)}. *
  • The default field naming policy for the output JSON is same as in Java. So, a Java class * field {@code versionNumber} will be output as {@code "versionNumber"} in JSON. The same * rules are applied for mapping incoming JSON to the Java classes. You can change this * policy through {@link GsonBuilder#setFieldNamingPolicy(FieldNamingPolicy)}. *
  • By default, Gson excludes {@code transient} or {@code static} fields from consideration * for serialization and deserialization. You can change this behavior through {@link * GsonBuilder#excludeFieldsWithModifiers(int...)}. *
  • No explicit strictness is set. You can change this by calling {@link * GsonBuilder#setStrictness(Strictness)}. *
*/ public Gson() { this(GsonBuilder.DEFAULT); } Gson(GsonBuilder builder) { this.excluder = builder.excluder; this.fieldNamingStrategy = builder.fieldNamingPolicy; this.instanceCreators = new HashMap<>(builder.instanceCreators); this.serializeNulls = builder.serializeNulls; this.complexMapKeySerialization = builder.complexMapKeySerialization; this.generateNonExecutableJson = builder.generateNonExecutableJson; this.htmlSafe = builder.escapeHtmlChars; this.formattingStyle = builder.formattingStyle; this.strictness = builder.strictness; this.serializeSpecialFloatingPointValues = builder.serializeSpecialFloatingPointValues; this.useJdkUnsafe = builder.useJdkUnsafe; this.longSerializationPolicy = builder.longSerializationPolicy; this.datePattern = builder.datePattern; this.dateStyle = builder.dateStyle; this.timeStyle = builder.timeStyle; this.builderFactories = newImmutableList(builder.factories); this.builderHierarchyFactories = newImmutableList(builder.hierarchyFactories); this.objectToNumberStrategy = builder.objectToNumberStrategy; this.numberToNumberStrategy = builder.numberToNumberStrategy; this.reflectionFilters = newImmutableList(builder.reflectionFilters); if (builder == GsonBuilder.DEFAULT) { this.constructorConstructor = GsonBuilder.DEFAULT_CONSTRUCTOR_CONSTRUCTOR; this.jsonAdapterFactory = GsonBuilder.DEFAULT_JSON_ADAPTER_ANNOTATION_TYPE_ADAPTER_FACTORY; this.factories = GsonBuilder.DEFAULT_TYPE_ADAPTER_FACTORIES; } else { this.constructorConstructor = new ConstructorConstructor(instanceCreators, useJdkUnsafe, reflectionFilters); this.jsonAdapterFactory = new JsonAdapterAnnotationTypeAdapterFactory(constructorConstructor); this.factories = builder.createFactories(constructorConstructor, jsonAdapterFactory); } } /** * Returns a new GsonBuilder containing all custom factories and configuration used by the current * instance. * * @return a GsonBuilder instance. * @since 2.8.3 */ 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; } /** * Returns the type adapter for {@code type}. * *

When calling this method concurrently from multiple threads and requesting an adapter for * the same type this method may return different {@code TypeAdapter} instances. However, that * should normally not be an issue because {@code TypeAdapter} implementations are supposed to be * stateless. * * @throws IllegalArgumentException if this Gson instance cannot serialize and deserialize {@code * type}. */ public TypeAdapter getAdapter(TypeToken type) { Objects.requireNonNull(type, "type must not be null"); TypeAdapter cached = typeTokenCache.get(type); if (cached != null) { @SuppressWarnings("unchecked") TypeAdapter adapter = (TypeAdapter) cached; return adapter; } Map, TypeAdapter> threadCalls = threadLocalAdapterResults.get(); boolean isInitialAdapterRequest = false; if (threadCalls == null) { threadCalls = new HashMap<>(); threadLocalAdapterResults.set(threadCalls); isInitialAdapterRequest = true; } else { // the key and value type parameters always agree @SuppressWarnings("unchecked") TypeAdapter ongoingCall = (TypeAdapter) threadCalls.get(type); if (ongoingCall != null) { return ongoingCall; } } TypeAdapter candidate = null; try { FutureTypeAdapter call = new FutureTypeAdapter<>(); threadCalls.put(type, call); for (TypeAdapterFactory factory : factories) { candidate = factory.create(this, type); if (candidate != null) { call.setDelegate(candidate); // Replace future adapter with actual adapter threadCalls.put(type, candidate); break; } } } finally { if (isInitialAdapterRequest) { threadLocalAdapterResults.remove(); } } if (candidate == null) { throw new IllegalArgumentException( "GSON (" + GsonBuildConfig.VERSION + ") cannot handle " + type); } if (isInitialAdapterRequest) { /* * Publish resolved adapters to all threads * Can only do this for the initial request because cyclic dependency TypeA -> TypeB -> TypeA * would otherwise publish adapter for TypeB which uses not yet resolved adapter for TypeA * See https://github.com/google/gson/issues/625 */ typeTokenCache.putAll(threadCalls); } return candidate; } /** * Returns the type adapter for {@code type}. * * @throws IllegalArgumentException if this Gson instance cannot serialize and deserialize {@code * type}. */ public TypeAdapter getAdapter(Class type) { return getAdapter(TypeToken.get(type)); } /** * 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 feature 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: * *

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} method: * *

{@code
   * class StatsTypeAdapterFactory implements TypeAdapterFactory {
   *   public int numReads = 0;
   *   public int numWrites = 0;
   *   public  TypeAdapter create(Gson gson, TypeToken type) {
   *     TypeAdapter delegate = gson.getDelegateAdapter(this, type);
   *     return new TypeAdapter() {
   *       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);
   *       }
   *     };
   *   }
   * }
   * }
* * This factory can now be used like this: * *
{@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);
   * }
* * 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 ensure 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 the type adapter factories * for some types, see {@link GsonBuilder#registerTypeAdapter(Type, Object)}, our stats factory * will not count the number of instances of those types that will be read or written. * *

If {@code skipPast} is a factory which has neither been registered on the {@link * GsonBuilder} nor specified with the {@link JsonAdapter @JsonAdapter} annotation on a class, * then this method behaves as if {@link #getAdapter(TypeToken)} had been called. This also means * that for fields with {@code @JsonAdapter} annotation this method behaves normally like {@code * getAdapter} (except for corner cases where a custom {@link InstanceCreator} is used to create * an instance of the factory). * * @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 this (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 TypeAdapter getDelegateAdapter(TypeAdapterFactory skipPast, TypeToken type) { Objects.requireNonNull(skipPast, "skipPast must not be null"); Objects.requireNonNull(type, "type must not be null"); if (jsonAdapterFactory.isClassJsonAdapterFactory(type, skipPast)) { skipPast = jsonAdapterFactory; } boolean skipPastFound = false; for (TypeAdapterFactory factory : factories) { if (!skipPastFound) { if (factory == skipPast) { skipPastFound = true; } continue; } TypeAdapter candidate = factory.create(this, type); if (candidate != null) { return candidate; } } if (skipPastFound) { throw new IllegalArgumentException("GSON cannot serialize or deserialize " + type); } else { // Probably a factory from @JsonAdapter on a field return getAdapter(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 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 * @return JSON representation of {@code src}. * @since 1.4 * @see #toJsonTree(Object, Type) */ 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}, you should use: *

   * Type typeOfSrc = new TypeToken<Collection<Foo>>(){}.getType();
   * 
* * @return JSON representation of {@code src}. * @since 1.4 * @see #toJsonTree(Object) */ 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 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 * @return JSON representation of {@code src}. * @see #toJson(Object, Appendable) * @see #toJson(Object, Type) */ 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}, you should use: *
   * Type typeOfSrc = new TypeToken<Collection<Foo>>(){}.getType();
   * 
* * @return JSON representation of {@code src}. * @see #toJson(Object, Type, Appendable) * @see #toJson(Object) */ public String toJson(Object src, Type typeOfSrc) { StringBuilder writer = new StringBuilder(); toJson(src, typeOfSrc, writer); return writer.toString(); } /** * This method serializes the specified object into its equivalent JSON representation and writes * it to the writer. 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 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 * @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 * @see #toJson(Object) * @see #toJson(Object, Type, Appendable) */ 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 and writes it to the writer. 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}, you should use: *
   * Type typeOfSrc = new TypeToken<Collection<Foo>>(){}.getType();
   * 
* * @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 * @see #toJson(Object, Type) * @see #toJson(Object, Appendable) */ 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}. * *

If the {@code Gson} instance has an {@linkplain GsonBuilder#setStrictness(Strictness) * explicit strictness setting}, this setting will be used for writing the JSON regardless of the * {@linkplain JsonWriter#getStrictness() strictness} of the provided {@link JsonWriter}. For * legacy reasons, if the {@code Gson} instance has no explicit strictness setting and the writer * does not have the strictness {@link Strictness#STRICT}, the JSON will be written in {@link * Strictness#LENIENT} mode.
* Note that in all cases the old strictness setting of the writer will be restored when this * method returns. * *

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. * * @param src the object for which JSON representation is to be created * @param typeOfSrc the type of the object to be written * @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 */ public void toJson(Object src, Type typeOfSrc, JsonWriter writer) throws JsonIOException { @SuppressWarnings("unchecked") TypeAdapter adapter = (TypeAdapter) getAdapter(TypeToken.get(typeOfSrc)); Strictness oldStrictness = writer.getStrictness(); if (this.strictness != null) { writer.setStrictness(this.strictness); } else if (writer.getStrictness() == Strictness.LEGACY_STRICT) { // For backward compatibility change to LENIENT if writer has default strictness LEGACY_STRICT writer.setStrictness(Strictness.LENIENT); } boolean oldHtmlSafe = writer.isHtmlSafe(); boolean oldSerializeNulls = writer.getSerializeNulls(); writer.setHtmlSafe(htmlSafe); writer.setSerializeNulls(serializeNulls); try { adapter.write(writer, src); } catch (IOException e) { throw new JsonIOException(e); } catch (AssertionError e) { throw new AssertionError( "AssertionError (GSON " + GsonBuildConfig.VERSION + "): " + e.getMessage(), e); } finally { writer.setStrictness(oldStrictness); 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) { StringBuilder writer = new StringBuilder(); 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); } } /** * Writes the JSON for {@code jsonElement} to {@code writer}. * *

If the {@code Gson} instance has an {@linkplain GsonBuilder#setStrictness(Strictness) * explicit strictness setting}, this setting will be used for writing the JSON regardless of the * {@linkplain JsonWriter#getStrictness() strictness} of the provided {@link JsonWriter}. For * legacy reasons, if the {@code Gson} instance has no explicit strictness setting and the writer * does not have the strictness {@link Strictness#STRICT}, the JSON will be written in {@link * Strictness#LENIENT} mode.
* Note that in all cases the old strictness setting of the writer will be restored when this * method returns. * *

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. * * @param jsonElement the JSON element to be written * @param writer the JSON writer to which the provided element will be written * @throws JsonIOException if there was a problem writing to the writer */ public void toJson(JsonElement jsonElement, JsonWriter writer) throws JsonIOException { Strictness oldStrictness = writer.getStrictness(); boolean oldHtmlSafe = writer.isHtmlSafe(); boolean oldSerializeNulls = writer.getSerializeNulls(); writer.setHtmlSafe(htmlSafe); writer.setSerializeNulls(serializeNulls); if (this.strictness != null) { writer.setStrictness(this.strictness); } else if (writer.getStrictness() == Strictness.LEGACY_STRICT) { // For backward compatibility change to LENIENT if writer has default strictness LEGACY_STRICT writer.setStrictness(Strictness.LENIENT); } try { Streams.write(jsonElement, writer); } catch (IOException e) { throw new JsonIOException(e); } catch (AssertionError e) { throw new AssertionError( "AssertionError (GSON " + GsonBuildConfig.VERSION + "): " + e.getMessage(), e); } finally { writer.setStrictness(oldStrictness); writer.setHtmlSafe(oldHtmlSafe); writer.setSerializeNulls(oldSerializeNulls); } } /** * Returns a new JSON writer configured for the settings on this Gson instance. * *

The following settings are considered: * *

    *
  • {@link GsonBuilder#disableHtmlEscaping()} *
  • {@link GsonBuilder#generateNonExecutableJson()} *
  • {@link GsonBuilder#serializeNulls()} *
  • {@link GsonBuilder#setStrictness(Strictness)}. If no {@linkplain * GsonBuilder#setStrictness(Strictness) explicit strictness has been set} the created * writer will have a strictness of {@link Strictness#LEGACY_STRICT}. Otherwise, the * strictness of the {@code Gson} instance will be used for the created writer. *
  • {@link GsonBuilder#setPrettyPrinting()} *
  • {@link GsonBuilder#setFormattingStyle(FormattingStyle)} *
*/ public JsonWriter newJsonWriter(Writer writer) throws IOException { if (generateNonExecutableJson) { writer.write(JSON_NON_EXECUTABLE_PREFIX); } JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.setFormattingStyle(formattingStyle); jsonWriter.setHtmlSafe(htmlSafe); jsonWriter.setStrictness(strictness == null ? Strictness.LEGACY_STRICT : strictness); jsonWriter.setSerializeNulls(serializeNulls); return jsonWriter; } /** * Returns a new JSON reader configured for the settings on this Gson instance. * *

The following settings are considered: * *

    *
  • {@link GsonBuilder#setStrictness(Strictness)}. If no {@linkplain * GsonBuilder#setStrictness(Strictness) explicit strictness has been set} the created * reader will have a strictness of {@link Strictness#LEGACY_STRICT}. Otherwise, the * strictness of the {@code Gson} instance will be used for the created reader. *
*/ public JsonReader newJsonReader(Reader reader) { JsonReader jsonReader = new JsonReader(reader); jsonReader.setStrictness(strictness == null ? Strictness.LEGACY_STRICT : strictness); return jsonReader; } /** * 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 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, * TypeToken)}. If you have the JSON in a {@link Reader} instead of a String, use {@link * #fromJson(Reader, Class)} instead. * *

An exception is thrown if the JSON string has multiple top-level JSON elements, or if there * is trailing data. Use {@link #fromJson(JsonReader, Type)} if this behavior is not desired. * * @param 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 * @see #fromJson(Reader, Class) * @see #fromJson(String, TypeToken) */ public T fromJson(String json, Class classOfT) throws JsonSyntaxException { return fromJson(json, TypeToken.get(classOfT)); } /** * 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. * *

Since {@code Type} is not parameterized by T, this method is not type-safe and should be * used carefully. If you are creating the {@code Type} from a {@link TypeToken}, prefer using * {@link #fromJson(String, TypeToken)} instead since its return type is based on the {@code * TypeToken} and is therefore more type-safe. * *

An exception is thrown if the JSON string has multiple top-level JSON elements, or if there * is trailing data. Use {@link #fromJson(JsonReader, Type)} if this behavior is not desired. * * @param 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 * @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 typeOfT * @see #fromJson(Reader, Type) * @see #fromJson(String, Class) * @see #fromJson(String, TypeToken) */ @SuppressWarnings({"unchecked", "TypeParameterUnusedInFormals"}) public T fromJson(String json, Type typeOfT) throws JsonSyntaxException { return (T) fromJson(json, TypeToken.get(typeOfT)); } /** * 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, TypeToken)} instead. * *

An exception is thrown if the JSON string has multiple top-level JSON elements, or if there * is trailing data. Use {@link #fromJson(JsonReader, TypeToken)} if this behavior is not desired. * * @param 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 should create an anonymous subclass of * {@code TypeToken} with the specific generic type arguments. For example, to get the type * for {@code Collection}, you should use: *

   * new TypeToken<Collection<Foo>>(){}
   * 
* * @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 the type * typeOfT * @see #fromJson(Reader, TypeToken) * @see #fromJson(String, Class) * @since 2.10 */ public T fromJson(String json, TypeToken typeOfT) throws JsonSyntaxException { if (json == null) { return null; } StringReader reader = new StringReader(json); return fromJson(reader, typeOfT); } /** * 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 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, TypeToken)}. If you have the JSON in a String form instead of a {@link * Reader}, use {@link #fromJson(String, Class)} instead. * *

An exception is thrown if the JSON data has multiple top-level JSON elements, or if there is * trailing data. Use {@link #fromJson(JsonReader, Type)} if this behavior is not desired. * * @param 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 Reader. 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 typeOfT * @since 1.2 * @see #fromJson(String, Class) * @see #fromJson(Reader, TypeToken) */ public T fromJson(Reader json, Class classOfT) throws JsonSyntaxException, JsonIOException { return fromJson(json, TypeToken.get(classOfT)); } /** * 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. * *

Since {@code Type} is not parameterized by T, this method is not type-safe and should be * used carefully. If you are creating the {@code Type} from a {@link TypeToken}, prefer using * {@link #fromJson(Reader, TypeToken)} instead since its return type is based on the {@code * TypeToken} and is therefore more type-safe. * *

An exception is thrown if the JSON data has multiple top-level JSON elements, or if there is * trailing data. Use {@link #fromJson(JsonReader, Type)} if this behavior is not desired. * * @param 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 * @return an object of type T from the Reader. 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 typeOfT * @since 1.2 * @see #fromJson(String, Type) * @see #fromJson(Reader, Class) * @see #fromJson(Reader, TypeToken) */ @SuppressWarnings({"unchecked", "TypeParameterUnusedInFormals"}) public T fromJson(Reader json, Type typeOfT) throws JsonIOException, JsonSyntaxException { return (T) fromJson(json, TypeToken.get(typeOfT)); } /** * 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, TypeToken)} instead. * *

An exception is thrown if the JSON data has multiple top-level JSON elements, or if there is * trailing data. Use {@link #fromJson(JsonReader, TypeToken)} if this behavior is not desired. * * @param 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 should create an anonymous subclass of * {@code TypeToken} with the specific generic type arguments. For example, to get the type * for {@code Collection}, you should use: *

   * new TypeToken<Collection<Foo>>(){}
   * 
* * @return an object of type T from the Reader. 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 of * typeOfT * @see #fromJson(String, TypeToken) * @see #fromJson(Reader, Class) * @since 2.10 */ public T fromJson(Reader json, TypeToken typeOfT) throws JsonIOException, JsonSyntaxException { JsonReader jsonReader = newJsonReader(json); T object = fromJson(jsonReader, typeOfT); assertFullConsumption(object, jsonReader); return object; } // fromJson(JsonReader, Class) is unfortunately missing and cannot be added now without breaking // source compatibility in certain cases, see // https://github.com/google/gson/pull/1700#discussion_r973764414 /** * Reads the next JSON value from {@code reader} and converts it to an object of type {@code * typeOfT}. Returns {@code null}, if the {@code reader} is at EOF. * *

Since {@code Type} is not parameterized by T, this method is not type-safe and should be * used carefully. If you are creating the {@code Type} from a {@link TypeToken}, prefer using * {@link #fromJson(JsonReader, TypeToken)} instead since its return type is based on the {@code * TypeToken} and is therefore more type-safe. If the provided type is a {@code Class} the {@code * TypeToken} can be created with {@link TypeToken#get(Class)}. * *

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. * *

If the {@code Gson} instance has an {@linkplain GsonBuilder#setStrictness(Strictness) * explicit strictness setting}, this setting will be used for reading the JSON regardless of the * {@linkplain JsonReader#getStrictness() strictness} of the provided {@link JsonReader}. For * legacy reasons, if the {@code Gson} instance has no explicit strictness setting and the reader * does not have the strictness {@link Strictness#STRICT}, the JSON will be written in {@link * Strictness#LENIENT} mode.
* Note that in all cases the old strictness setting of the reader will be restored when this * method returns. * * @param the type of the desired object * @param reader the reader whose next JSON value should be deserialized * @param typeOfT The specific genericized type of src * @return an object of type T from the JsonReader. Returns {@code null} if {@code reader} is at * EOF. * @throws JsonIOException if there was a problem reading from the JsonReader * @throws JsonSyntaxException if json is not a valid representation for an object of type typeOfT * @see #fromJson(Reader, Type) * @see #fromJson(JsonReader, TypeToken) */ @SuppressWarnings({"unchecked", "TypeParameterUnusedInFormals"}) public T fromJson(JsonReader reader, Type typeOfT) throws JsonIOException, JsonSyntaxException { return (T) fromJson(reader, TypeToken.get(typeOfT)); } /** * Reads the next JSON value from {@code reader} and converts it to an object of type {@code * typeOfT}. Returns {@code null}, if the {@code reader} is at EOF. This method is useful if the * specified object is a generic type. For non-generic objects, {@link #fromJson(JsonReader, * Type)} can be called, or {@link TypeToken#get(Class)} can be used to create the type token. * *

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. * *

If the {@code Gson} instance has an {@linkplain GsonBuilder#setStrictness(Strictness) * explicit strictness setting}, this setting will be used for reading the JSON regardless of the * {@linkplain JsonReader#getStrictness() strictness} of the provided {@link JsonReader}. For * legacy reasons, if the {@code Gson} instance has no explicit strictness setting and the reader * does not have the strictness {@link Strictness#STRICT}, the JSON will be written in {@link * Strictness#LENIENT} mode.
* Note that in all cases the old strictness setting of the reader will be restored when this * method returns. * * @param the type of the desired object * @param reader the reader whose next JSON value should be deserialized * @param typeOfT The specific genericized type of src. You should create an anonymous subclass of * {@code TypeToken} with the specific generic type arguments. For example, to get the type * for {@code Collection}, you should use: *

   * new TypeToken<Collection<Foo>>(){}
   * 
* * @return an object of type T from the JsonReader. Returns {@code null} if {@code reader} is at * EOF. * @throws JsonIOException if there was a problem reading from the JsonReader * @throws JsonSyntaxException if json is not a valid representation for an object of the type * typeOfT * @see #fromJson(Reader, TypeToken) * @see #fromJson(JsonReader, Type) * @since 2.10 */ public T fromJson(JsonReader reader, TypeToken typeOfT) throws JsonIOException, JsonSyntaxException { boolean isEmpty = true; Strictness oldStrictness = reader.getStrictness(); if (this.strictness != null) { reader.setStrictness(this.strictness); } else if (reader.getStrictness() == Strictness.LEGACY_STRICT) { // For backward compatibility change to LENIENT if reader has default strictness LEGACY_STRICT reader.setStrictness(Strictness.LENIENT); } try { JsonToken unused = reader.peek(); isEmpty = false; TypeAdapter typeAdapter = getAdapter(typeOfT); T object = typeAdapter.read(reader); Class expectedTypeWrapped = Primitives.wrap(typeOfT.getRawType()); if (object != null && !expectedTypeWrapped.isInstance(object)) { throw new ClassCastException( "Type adapter '" + typeAdapter + "' returned wrong type; requested " + typeOfT.getRawType() + " but got instance of " + object.getClass() + "\nVerify that the adapter was registered for the correct type."); } 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) { throw new AssertionError( "AssertionError (GSON " + GsonBuildConfig.VERSION + "): " + e.getMessage(), e); } finally { reader.setStrictness(oldStrictness); } } /** * 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 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, TypeToken)}. * * @param 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 * classOfT * @since 1.3 * @see #fromJson(Reader, Class) * @see #fromJson(JsonElement, TypeToken) */ public T fromJson(JsonElement json, Class classOfT) throws JsonSyntaxException { return fromJson(json, TypeToken.get(classOfT)); } /** * 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. * *

Since {@code Type} is not parameterized by T, this method is not type-safe and should be * used carefully. If you are creating the {@code Type} from a {@link TypeToken}, prefer using * {@link #fromJson(JsonElement, TypeToken)} instead since its return type is based on the {@code * TypeToken} and is therefore more type-safe. * * @param 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 * @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 * @see #fromJson(Reader, Type) * @see #fromJson(JsonElement, Class) * @see #fromJson(JsonElement, TypeToken) */ @SuppressWarnings({"unchecked", "TypeParameterUnusedInFormals"}) public T fromJson(JsonElement json, Type typeOfT) throws JsonSyntaxException { return (T) fromJson(json, TypeToken.get(typeOfT)); } /** * 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 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 should create an anonymous subclass of * {@code TypeToken} with the specific generic type arguments. For example, to get the type * for {@code Collection}, you should use: *

   * new TypeToken<Collection<Foo>>(){}
   * 
* * @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 * @see #fromJson(Reader, TypeToken) * @see #fromJson(JsonElement, Class) * @since 2.10 */ public T fromJson(JsonElement json, TypeToken typeOfT) throws JsonSyntaxException { if (json == null) { return null; } return fromJson(new JsonTreeReader(json), typeOfT); } 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); } } /** * Proxy type adapter for cyclic type graphs. * *

Important: Setting the delegate adapter is not thread-safe; instances of {@code * FutureTypeAdapter} must only be published to other threads after the delegate has been set. * * @see Gson#threadLocalAdapterResults */ static class FutureTypeAdapter extends SerializationDelegatingTypeAdapter { private TypeAdapter delegate = null; public void setDelegate(TypeAdapter typeAdapter) { if (delegate != null) { throw new AssertionError("Delegate is already set"); } delegate = typeAdapter; } private TypeAdapter delegate() { TypeAdapter delegate = this.delegate; if (delegate == null) { // Can occur when adapter is leaked to other thread or when adapter is used for // (de-)serialization // directly within the TypeAdapterFactory which requested it throw new IllegalStateException( "Adapter for type with cyclic dependency has been used" + " before dependency has been resolved"); } return delegate; } @Override public TypeAdapter getSerializationDelegate() { return delegate(); } @Override public T read(JsonReader in) throws IOException { return delegate().read(in); } @Override public void write(JsonWriter out, T value) throws IOException { delegate().write(out, value); } } @Override public String toString() { return "{serializeNulls:" + serializeNulls + ",factories:" + factories + ",instanceCreators:" + constructorConstructor + "}"; } } ================================================ FILE: gson/src/main/java/com/google/gson/GsonBuilder.java ================================================ /* * 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.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.InlineMe; import com.google.gson.annotations.Since; import com.google.gson.annotations.Until; import com.google.gson.internal.ConstructorConstructor; import com.google.gson.internal.Excluder; import com.google.gson.internal.bind.ArrayTypeAdapter; import com.google.gson.internal.bind.CollectionTypeAdapterFactory; import com.google.gson.internal.bind.DefaultDateTypeAdapter; import com.google.gson.internal.bind.JsonAdapterAnnotationTypeAdapterFactory; 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.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 java.lang.reflect.Type; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLongArray; /** * 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. * *

The following example shows how to use the {@code GsonBuilder} to construct a Gson instance: * *

 * Gson gson = new GsonBuilder()
 *     .registerTypeAdapter(Id.class, new IdTypeAdapter())
 *     .enableComplexMapKeySerialization()
 *     .serializeNulls()
 *     .setDateFormat(DateFormat.LONG, DateFormat.LONG)
 *     .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
 *     .setPrettyPrinting()
 *     .setVersion(1.0)
 *     .create();
 * 
* *

Notes: * *

    *
  • The order of invocation of configuration methods does not matter. *
  • 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. *
  • By default no explicit {@link Strictness} is set; some of the {@link Gson} methods behave * as if {@link Strictness#LEGACY_STRICT} was used whereas others behave as if {@link * Strictness#LENIENT} was used. Prefer explicitly setting a strictness with {@link * #setStrictness(Strictness)} to avoid this legacy behavior. *
* * @author Inderjeet Singh * @author Joel Leitch * @author Jesse Wilson */ public final class GsonBuilder { private static final boolean DEFAULT_JSON_NON_EXECUTABLE = false; // Strictness of `null` is the legacy mode where some Gson APIs are always lenient private static final Strictness DEFAULT_STRICTNESS = null; private static final FormattingStyle DEFAULT_FORMATTING_STYLE = FormattingStyle.COMPACT; private static final boolean DEFAULT_ESCAPE_HTML = true; private static final boolean DEFAULT_SERIALIZE_NULLS = false; private static final boolean DEFAULT_COMPLEX_MAP_KEYS = false; private static final boolean DEFAULT_SPECIALIZE_FLOAT_VALUES = false; private static final boolean DEFAULT_USE_JDK_UNSAFE = true; private static final String DEFAULT_DATE_PATTERN = null; private static final FieldNamingStrategy DEFAULT_FIELD_NAMING_STRATEGY = FieldNamingPolicy.IDENTITY; private static final ToNumberStrategy DEFAULT_OBJECT_TO_NUMBER_STRATEGY = ToNumberPolicy.DOUBLE; private static final ToNumberStrategy DEFAULT_NUMBER_TO_NUMBER_STRATEGY = ToNumberPolicy.LAZILY_PARSED_NUMBER; static final ConstructorConstructor DEFAULT_CONSTRUCTOR_CONSTRUCTOR = new ConstructorConstructor( Collections.emptyMap(), DEFAULT_USE_JDK_UNSAFE, Collections.emptyList()); static final JsonAdapterAnnotationTypeAdapterFactory DEFAULT_JSON_ADAPTER_ANNOTATION_TYPE_ADAPTER_FACTORY = new JsonAdapterAnnotationTypeAdapterFactory(DEFAULT_CONSTRUCTOR_CONSTRUCTOR); /** * Default instance of the builder, to be used only by the default {@link Gson#Gson()} * constructor. Must not be used for anything else and must not be leaked to user code, since that * could lead to accidental modification of this default builder. */ static final GsonBuilder DEFAULT = new GsonBuilder(); static final List DEFAULT_TYPE_ADAPTER_FACTORIES = GsonBuilder.DEFAULT.createFactories( DEFAULT_CONSTRUCTOR_CONSTRUCTOR, DEFAULT_JSON_ADAPTER_ANNOTATION_TYPE_ADAPTER_FACTORY); Excluder excluder = Excluder.DEFAULT; LongSerializationPolicy longSerializationPolicy = LongSerializationPolicy.DEFAULT; FieldNamingStrategy fieldNamingPolicy = DEFAULT_FIELD_NAMING_STRATEGY; final Map> instanceCreators = new HashMap<>(); final List factories = new ArrayList<>(); /** tree-style hierarchy factories. These come after factories for backwards compatibility. */ final List hierarchyFactories = new ArrayList<>(); boolean serializeNulls = DEFAULT_SERIALIZE_NULLS; String datePattern = DEFAULT_DATE_PATTERN; int dateStyle = DateFormat.DEFAULT; int timeStyle = DateFormat.DEFAULT; boolean complexMapKeySerialization = DEFAULT_COMPLEX_MAP_KEYS; boolean serializeSpecialFloatingPointValues = DEFAULT_SPECIALIZE_FLOAT_VALUES; boolean escapeHtmlChars = DEFAULT_ESCAPE_HTML; FormattingStyle formattingStyle = DEFAULT_FORMATTING_STYLE; boolean generateNonExecutableJson = DEFAULT_JSON_NON_EXECUTABLE; Strictness strictness = DEFAULT_STRICTNESS; boolean useJdkUnsafe = DEFAULT_USE_JDK_UNSAFE; ToNumberStrategy objectToNumberStrategy = DEFAULT_OBJECT_TO_NUMBER_STRATEGY; ToNumberStrategy numberToNumberStrategy = DEFAULT_NUMBER_TO_NUMBER_STRATEGY; final ArrayDeque reflectionFilters = new ArrayDeque<>(); /** * 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 be 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.formattingStyle = gson.formattingStyle; this.strictness = gson.strictness; 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. Versioning support works based on the annotation * types {@link Since} and {@link Until}. It allows including or excluding fields and classes * based on the specified version. See the documentation of these annotation types for more * information. * *

By default versioning support is disabled and usage of {@code @Since} and {@code @Until} has * no effect. * * @param version the version number to use. * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern * @throws IllegalArgumentException if the version number is NaN or negative * @see Since * @see Until */ @CanIgnoreReturnValue public GsonBuilder setVersion(double version) { if (Double.isNaN(version) || version < 0.0) { throw new IllegalArgumentException("Invalid version: " + version); } excluder = excluder.withVersion(version); return this; } /** * Configures Gson to excludes all class fields that have the specified modifiers. By default, * Gson will exclude all fields marked {@code transient} or {@code static}. This method will * override that behavior. * *

This is a convenience method which behaves as if an {@link ExclusionStrategy} which excludes * these fields was {@linkplain #setExclusionStrategies(ExclusionStrategy...) registered with this * builder}. * * @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 */ @CanIgnoreReturnValue public GsonBuilder excludeFieldsWithModifiers(int... modifiers) { Objects.requireNonNull(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 Gson Issue 42 for details. * * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern * @since 1.3 */ @CanIgnoreReturnValue public GsonBuilder generateNonExecutableJson() { this.generateNonExecutableJson = true; return this; } /** * Configures Gson to exclude all fields from consideration for serialization and deserialization * that do not have the {@link com.google.gson.annotations.Expose} annotation. * *

This is a convenience method which behaves as if an {@link ExclusionStrategy} which excludes * these fields was {@linkplain #setExclusionStrategies(ExclusionStrategy...) registered with this * builder}. * * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern */ @CanIgnoreReturnValue public GsonBuilder excludeFieldsWithoutExposeAnnotation() { excluder = excluder.excludeFieldsWithoutExposeAnnotation(); return this; } /** * Configures Gson to serialize null fields. By default, Gson omits all fields that are null * during serialization. * * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern * @since 1.2 */ @CanIgnoreReturnValue public GsonBuilder serializeNulls() { this.serializeNulls = true; return this; } /** * Configures Gson to serialize {@code Map} objects with complex keys as JSON arrays. Enabling * this feature will only change the serialized form if the map key is a complex type (i.e. * non-primitive) in its serialized 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: * *

Maps as JSON objects * *

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}. * *

Below is an example: * *

{@code
   * Gson gson = new GsonBuilder()
   *     .register(Point.class, new MyPointTypeAdapter())
   *     .enableComplexMapKeySerialization()
   *     .create();
   *
   * Map original = new LinkedHashMap<>();
   * original.put(new Point(5, 6), "a");
   * original.put(new Point(8, 8), "b");
   * System.out.println(gson.toJson(original, type));
   * }
* * The above code prints this JSON object: * *
{@code
   * {
   *   "(5,6)": "a",
   *   "(8,8)": "b"
   * }
   * }
* *

Maps as JSON arrays * *

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":3}}. * *

Given the assumption above, a {@code Map} will be serialized as an array of * arrays (can be viewed as an entry set of pairs). * *

Below is an example of serializing complex types as JSON arrays: * *

{@code
   * Gson gson = new GsonBuilder()
   *     .enableComplexMapKeySerialization()
   *     .create();
   *
   * Map original = new LinkedHashMap<>();
   * original.put(new Point(5, 6), "a");
   * original.put(new Point(8, 8), "b");
   * System.out.println(gson.toJson(original, type));
   * }
* * The JSON output would look as follows: * *
{@code
   * [
   *   [
   *     {
   *       "x": 5,
   *       "y": 6
   *     },
   *     "a"
   *   ],
   *   [
   *     {
   *       "x": 8,
   *       "y": 8
   *     },
   *     "b"
   *   ]
   * ]
   * }
* * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern * @since 1.7 */ @CanIgnoreReturnValue public GsonBuilder enableComplexMapKeySerialization() { complexMapKeySerialization = true; return this; } /** * Configures Gson to exclude inner classes (= non-{@code static} nested classes) during * serialization and deserialization. This is a convenience method which behaves as if an {@link * ExclusionStrategy} which excludes inner classes was {@linkplain * #setExclusionStrategies(ExclusionStrategy...) registered with this builder}. This means inner * classes will be serialized as JSON {@code null}, and will be deserialized as Java {@code null} * with their JSON data being ignored. And fields with an inner class as type will be ignored * during serialization and deserialization. * *

By default Gson serializes and deserializes inner classes, but ignores references to the * enclosing instance. Deserialization might not be possible at all when {@link * #disableJdkUnsafe()} is used (and no custom {@link InstanceCreator} is registered), or it can * lead to unexpected {@code NullPointerException}s when the deserialized instance is used * afterwards. * *

In general using inner classes with Gson should be avoided; they should be converted to * {@code static} nested classes if possible. * * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern * @since 1.3 */ @CanIgnoreReturnValue 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 */ @CanIgnoreReturnValue public GsonBuilder setLongSerializationPolicy(LongSerializationPolicy serializationPolicy) { this.longSerializationPolicy = Objects.requireNonNull(serializationPolicy); return this; } /** * Configures Gson to apply a specific naming policy to an object's fields during serialization * and deserialization. * *

This method just delegates to {@link #setFieldNamingStrategy(FieldNamingStrategy)}. */ @CanIgnoreReturnValue public GsonBuilder setFieldNamingPolicy(FieldNamingPolicy namingConvention) { return setFieldNamingStrategy(namingConvention); } /** * Configures Gson to apply a specific naming strategy to an object's fields during serialization * and deserialization. * *

The created Gson instance might only use the field naming strategy once for a field and * cache the result. It is not guaranteed that the strategy will be used again every time the * value of a field is serialized or deserialized. * * @param fieldNamingStrategy the naming strategy to apply to the fields * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern * @since 1.3 */ @CanIgnoreReturnValue public GsonBuilder setFieldNamingStrategy(FieldNamingStrategy fieldNamingStrategy) { this.fieldNamingPolicy = Objects.requireNonNull(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 * @since 2.8.9 */ @CanIgnoreReturnValue public GsonBuilder setObjectToNumberStrategy(ToNumberStrategy objectToNumberStrategy) { this.objectToNumberStrategy = Objects.requireNonNull(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 * @since 2.8.9 */ @CanIgnoreReturnValue public GsonBuilder setNumberToNumberStrategy(ToNumberStrategy numberToNumberStrategy) { this.numberToNumberStrategy = Objects.requireNonNull(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. The strategies are * added to the existing strategies (if any); the existing strategies are not replaced. * *

Fields are excluded for serialization and deserialization when {@link * ExclusionStrategy#shouldSkipField(FieldAttributes) shouldSkipField} returns {@code true}, or * when {@link ExclusionStrategy#shouldSkipClass(Class) shouldSkipClass} returns {@code true} for * the field type. Gson behaves as if the field did not exist; its value is not serialized and on * deserialization if a JSON member with this name exists it is skipped by default.
* When objects of an excluded type (as determined by {@link * ExclusionStrategy#shouldSkipClass(Class) shouldSkipClass}) are serialized a JSON null is * written to output, and when deserialized the JSON value is skipped and {@code null} is * returned. * *

The created Gson instance might only use an exclusion strategy once for a field or class and * cache the result. It is not guaranteed that the strategy will be used again every time the * value of a field or a class is serialized or deserialized. * * @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 */ @CanIgnoreReturnValue public GsonBuilder setExclusionStrategies(ExclusionStrategy... strategies) { Objects.requireNonNull(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. * *

See the documentation of {@link #setExclusionStrategies(ExclusionStrategy...)} for a * detailed description of the effect of exclusion strategies. * * @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 */ @CanIgnoreReturnValue public GsonBuilder addSerializationExclusionStrategy(ExclusionStrategy strategy) { Objects.requireNonNull(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. * *

See the documentation of {@link #setExclusionStrategies(ExclusionStrategy...)} for a * detailed description of the effect of exclusion strategies. * * @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 */ @CanIgnoreReturnValue public GsonBuilder addDeserializationExclusionStrategy(ExclusionStrategy strategy) { Objects.requireNonNull(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. * *

This is a convenience method which simply calls {@link #setFormattingStyle(FormattingStyle)} * with {@link FormattingStyle#PRETTY}. * * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern */ @CanIgnoreReturnValue public GsonBuilder setPrettyPrinting() { return setFormattingStyle(FormattingStyle.PRETTY); } /** * Configures Gson to output JSON that uses a certain kind of formatting style (for example * newline and indent). This option only affects JSON serialization. By default Gson produces * compact JSON output without any formatting. * * @param formattingStyle the formatting style to use. * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern * @since 2.11.0 */ @CanIgnoreReturnValue public GsonBuilder setFormattingStyle(FormattingStyle formattingStyle) { this.formattingStyle = Objects.requireNonNull(formattingStyle); return this; } /** * Sets the strictness of this builder to {@link Strictness#LENIENT}. * * @deprecated This method is equivalent to calling {@link #setStrictness(Strictness)} with {@link * Strictness#LENIENT}: {@code setStrictness(Strictness.LENIENT)} * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern. * @see JsonReader#setStrictness(Strictness) * @see JsonWriter#setStrictness(Strictness) * @see #setStrictness(Strictness) */ @Deprecated @InlineMe( replacement = "this.setStrictness(Strictness.LENIENT)", imports = "com.google.gson.Strictness") @CanIgnoreReturnValue public GsonBuilder setLenient() { return setStrictness(Strictness.LENIENT); } /** * Sets the strictness of this builder to the provided parameter. * *

This changes how strict the RFC 8259 JSON * specification is enforced when parsing or writing JSON. For details on this, refer to * {@link JsonReader#setStrictness(Strictness)} and {@link JsonWriter#setStrictness(Strictness)}. * * @param strictness the new strictness mode. May not be {@code null}. * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern. * @see JsonReader#setStrictness(Strictness) * @see JsonWriter#setStrictness(Strictness) * @since 2.11.0 */ @CanIgnoreReturnValue public GsonBuilder setStrictness(Strictness strictness) { this.strictness = Objects.requireNonNull(strictness); return this; } /** * By default, Gson escapes HTML characters such as < > 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 */ @CanIgnoreReturnValue 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, int)} multiple times, but only the last * invocation will be used to decide the serialization format. * *

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}. * *

Note that this pattern must abide by the convention provided by {@code SimpleDateFormat} * class. See the documentation in {@link SimpleDateFormat} for more information on valid date and * time patterns. * * @param pattern the pattern that dates will be serialized/deserialized to/from; can be {@code * null} to reset the pattern * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern * @throws IllegalArgumentException if the pattern is invalid * @since 1.2 */ @CanIgnoreReturnValue public GsonBuilder setDateFormat(String pattern) { if (pattern != null) { try { SimpleDateFormat unused = new SimpleDateFormat(pattern); } catch (IllegalArgumentException e) { // Throw exception if it is an invalid date format throw new IllegalArgumentException("The date pattern '" + pattern + "' is not valid", e); } } this.datePattern = pattern; return this; } /** * Configures Gson to serialize {@code Date} objects according to the date style value provided. * You can call this method or {@link #setDateFormat(String)} multiple times, but only the last * invocation will be used to decide the serialization format. This methods leaves the current * 'time style' unchanged. * *

Note that this style value should be one of the predefined constants in the {@link * DateFormat} class, such as {@link DateFormat#MEDIUM}. See the documentation of the {@link * DateFormat} class for more information on the valid style constants. * * @deprecated Counterintuitively, despite this method taking only a 'date style' Gson will use a * format which includes both date and time, with the 'time style' being the last value set by * {@link #setDateFormat(int, int)}. Therefore prefer using {@link #setDateFormat(int, int)} * and explicitly provide the desired 'time style'. * @param dateStyle the predefined date style that date objects will be serialized/deserialized * to/from * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern * @throws IllegalArgumentException if the style is invalid * @since 1.2 */ @Deprecated @CanIgnoreReturnValue public GsonBuilder setDateFormat(int dateStyle) { this.dateStyle = checkDateFormatStyle(dateStyle); this.datePattern = null; return this; } /** * Configures Gson to serialize {@code Date} objects according to the style value provided. You * can call this method or {@link #setDateFormat(String)} multiple times, but only the last * invocation will be used to decide the serialization format. * *

Note that this style value should be one of the predefined constants in the {@link * DateFormat} class, such as {@link DateFormat#MEDIUM}. See the documentation of the {@link * DateFormat} class for more information on the valid style constants. * * @param dateStyle the predefined date style that date objects will be serialized/deserialized * to/from * @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 * @throws IllegalArgumentException if the style values are invalid * @since 1.2 */ @CanIgnoreReturnValue public GsonBuilder setDateFormat(int dateStyle, int timeStyle) { this.dateStyle = checkDateFormatStyle(dateStyle); this.timeStyle = checkDateFormatStyle(timeStyle); this.datePattern = null; return this; } private static int checkDateFormatStyle(int style) { // Valid DateFormat styles are: 0, 1, 2, 3 (FULL, LONG, MEDIUM, SHORT) if (style < 0 || style > 3) { throw new IllegalArgumentException("Invalid style: " + style); } return style; } /** * 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. * *

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}. And when registering an adapter for a class which has subclasses, you might * also want to register the adapter for subclasses, or use {@link * #registerTypeHierarchyAdapter(Class, Object)} instead. * *

{@link JsonSerializer} and {@link JsonDeserializer} are made "{@code null}-safe". This means * when trying to serialize {@code null}, Gson will write a JSON {@code null} and the serializer * is not called. Similarly when deserializing a JSON {@code null}, Gson will emit {@code null} * without calling the deserializer. If it is desired to handle {@code null} values, a {@link * TypeAdapter} should be used instead. * * @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 * @throws IllegalArgumentException if the type adapter being registered is for {@code Object} * class or {@link JsonElement} or any of its subclasses * @see #registerTypeHierarchyAdapter(Class, Object) */ @CanIgnoreReturnValue public GsonBuilder registerTypeAdapter(Type type, Object typeAdapter) { Objects.requireNonNull(type); Objects.requireNonNull(typeAdapter); if (!(typeAdapter instanceof JsonSerializer || typeAdapter instanceof JsonDeserializer || typeAdapter instanceof InstanceCreator || typeAdapter instanceof TypeAdapter)) { throw new IllegalArgumentException( "Class " + typeAdapter.getClass().getName() + " does not implement any supported type adapter class or interface"); } if (hasNonOverridableAdapter(type)) { throw new IllegalArgumentException("Cannot override built-in adapter for " + type); } 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) { @SuppressWarnings({"unchecked", "rawtypes"}) TypeAdapterFactory factory = TypeAdapters.newFactory(TypeToken.get(type), (TypeAdapter) typeAdapter); factories.add(factory); } return this; } /** Whether the type has a built-in adapter which cannot be overridden. */ private static boolean hasNonOverridableAdapter(Type type) { return type == Object.class; // This should also cover `JsonElement.class.isAssignableFrom(type)`, however for backward // compatibility this is not covered here because really old Gson versions had no built-in // adapter for JsonElement so users registered custom adapters. These adapters don't have any // effect in recent Gson versions. See // https://github.com/google/gson/issues/2787#issuecomment-2581568157 } /** * Registers 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. * *

The created Gson instance might only use the factory once to create an adapter for a * specific type and cache the result. It is not guaranteed that the factory will be used again * every time the type is serialized or deserialized. * * @since 2.1 */ @CanIgnoreReturnValue public GsonBuilder registerTypeAdapterFactory(TypeAdapterFactory factory) { Objects.requireNonNull(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 * @throws IllegalArgumentException if the type adapter being registered is for {@link * JsonElement} or any of its subclasses * @since 1.7 */ @CanIgnoreReturnValue public GsonBuilder registerTypeHierarchyAdapter(Class baseType, Object typeAdapter) { Objects.requireNonNull(baseType); Objects.requireNonNull(typeAdapter); if (!(typeAdapter instanceof JsonSerializer || typeAdapter instanceof JsonDeserializer || typeAdapter instanceof TypeAdapter)) { throw new IllegalArgumentException( "Class " + typeAdapter.getClass().getName() + " does not implement any supported type adapter class or interface"); } if (typeAdapter instanceof JsonDeserializer || typeAdapter instanceof JsonSerializer) { hierarchyFactories.add(TreeTypeAdapter.newTypeHierarchyFactory(baseType, typeAdapter)); } if (typeAdapter instanceof TypeAdapter) { @SuppressWarnings({"unchecked", "rawtypes"}) TypeAdapterFactory factory = TypeAdapters.newTypeHierarchyFactory(baseType, (TypeAdapter) typeAdapter); factories.add(factory); } return this; } /** * Section 6 of JSON specification disallows * special double values (NaN, Infinity, -Infinity). However, Javascript * specification (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. * *

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 */ @CanIgnoreReturnValue public GsonBuilder serializeSpecialFloatingPointValues() { this.serializeSpecialFloatingPointValues = true; return this; } /** * Disables usage of JDK's {@code sun.misc.Unsafe}. * *

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 * @since 2.9.0 */ @CanIgnoreReturnValue 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. * *

Filters will be invoked in reverse registration order, that is, the most recently added * filter will be invoked first. * *

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. * *

The created Gson instance might only use an access filter once for a class or its members * and cache the result. It is not guaranteed that the filter will be used again every time a * class or its members are accessed during serialization or deserialization. * * @param filter filter to add * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern * @since 2.9.1 */ @CanIgnoreReturnValue public GsonBuilder addReflectionAccessFilter(ReflectionAccessFilter filter) { Objects.requireNonNull(filter); 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() { return new Gson(this); } List createFactories( ConstructorConstructor constructorConstructor, JsonAdapterAnnotationTypeAdapterFactory jsonAdapterFactory) { ArrayList 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 addUserDefinedAdapters(factories); // custom Date adapters addDateTypeAdapters(factories); // 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 longAdapter = longSerializationPolicy.typeAdapter(); factories.add(TypeAdapters.newFactory(long.class, Long.class, longAdapter)); factories.add(TypeAdapters.newFactory(double.class, Double.class, doubleAdapter())); factories.add(TypeAdapters.newFactory(float.class, Float.class, floatAdapter())); factories.add(NumberTypeAdapter.getFactory(numberToNumberStrategy)); factories.add(TypeAdapters.ATOMIC_INTEGER_FACTORY); factories.add(TypeAdapters.ATOMIC_BOOLEAN_FACTORY); factories.add( TypeAdapters.newFactory(AtomicLong.class, TypeAdapters.atomicLongAdapter(longAdapter))); factories.add( TypeAdapters.newFactory( AtomicLongArray.class, TypeAdapters.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.BIG_DECIMAL_FACTORY); factories.add(TypeAdapters.BIG_INTEGER_FACTORY); // Add adapter for LazilyParsedNumber because user can obtain it from Gson and then try to // serialize it again factories.add(TypeAdapters.LAZILY_PARSED_NUMBER_FACTORY); 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(DefaultDateTypeAdapter.DEFAULT_STYLE_FACTORY); factories.add(TypeAdapters.CALENDAR_FACTORY); TypeAdapterFactory javaTimeFactory = TypeAdapters.javaTimeTypeAdapterFactory(); if (javaTimeFactory != null) { factories.add(javaTimeFactory); } factories.addAll(SqlTypesSupport.SQL_TYPE_FACTORIES); 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)); factories.add(jsonAdapterFactory); factories.add(TypeAdapters.ENUM_FACTORY); factories.add( new ReflectiveTypeAdapterFactory( constructorConstructor, fieldNamingPolicy, excluder, jsonAdapterFactory, newImmutableList(reflectionFilters))); factories.trimToSize(); return Collections.unmodifiableList(factories); } static List newImmutableList(Collection collection) { if (collection.isEmpty()) { return Collections.emptyList(); } if (collection.size() == 1) { return Collections.singletonList( collection instanceof List ? ((List) collection).get(0) : collection.iterator().next()); } @SuppressWarnings("unchecked") List list = (List) Collections.unmodifiableList(Arrays.asList(collection.toArray())); return list; } private TypeAdapter doubleAdapter() { return serializeSpecialFloatingPointValues ? TypeAdapters.DOUBLE : TypeAdapters.DOUBLE_STRICT; } private TypeAdapter floatAdapter() { return serializeSpecialFloatingPointValues ? TypeAdapters.FLOAT : TypeAdapters.FLOAT_STRICT; } private void addUserDefinedAdapters(List all) { if (!this.factories.isEmpty()) { List reversedFactories = new ArrayList<>(this.factories); Collections.reverse(reversedFactories); all.addAll(reversedFactories); } if (!this.hierarchyFactories.isEmpty()) { List reversedHierarchyFactories = new ArrayList<>(this.hierarchyFactories); Collections.reverse(reversedHierarchyFactories); all.addAll(reversedHierarchyFactories); } } private void addDateTypeAdapters(List 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); } } } ================================================ FILE: gson/src/main/java/com/google/gson/InstanceCreator.java ================================================ /* * 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. * *

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. * *

 * public class Id<T> {
 *   private final Class<T> clazz;
 *   private final long value;
 *   public Id(Class<T> clazz, long value) {
 *     this.clazz = clazz;
 *     this.value = value;
 *   }
 * }
 * 
* *

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: * *

 * private Id() {
 *   this(Object.class, 0L);
 * }
 * 
* *

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}: * *

 * class IdInstanceCreator implements InstanceCreator<Id> {
 *   public Id createInstance(Type type) {
 *     return new Id(Object.class, 0L);
 *   }
 * }
 * 
* *

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 * new 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: * *

 * Gson gson = new GsonBuilder().registerTypeAdapter(Id.class, new IdInstanceCreator()).create();
 * 
* * @param the type of object that will be created by this implementation. * @see GsonBuilder#registerTypeAdapter(Type, Object) * @author Inderjeet Singh * @author Joel Leitch */ public interface InstanceCreator { /** * 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. */ T createInstance(Type type); } ================================================ FILE: gson/src/main/java/com/google/gson/JsonArray.java ================================================ /* * 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.errorprone.annotations.CanIgnoreReturnValue; import com.google.gson.internal.NonNullElementWrapperList; 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. This class does not support {@code null} values. If {@code null} * is provided as element argument to any of the methods, it is converted to a {@link JsonNull}. * *

{@code JsonArray} only implements the {@link Iterable} interface but not the {@link List} * interface. A {@code List} view of it can be obtained with {@link #asList()}. * *

See the {@link JsonElement} documentation for details on how to convert {@code JsonArray} and * generally any {@code JsonElement} from and to JSON. * * @author Inderjeet Singh * @author Joel Leitch */ public final class JsonArray extends JsonElement implements Iterable { private final ArrayList elements; /** Creates an empty JsonArray. */ @SuppressWarnings("deprecation") // superclass constructor public JsonArray() { elements = new ArrayList<>(); } /** * Creates an empty JsonArray with the desired initial capacity. * * @param capacity initial capacity. * @throws IllegalArgumentException if the {@code capacity} is negative * @since 2.8.1 */ @SuppressWarnings("deprecation") // superclass constructor 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. * @since 2.4 */ 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. * @since 2.4 */ 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. * @since 2.4 */ 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. * @since 2.4 */ 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. * * @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 */ @CanIgnoreReturnValue public JsonElement set(int index, JsonElement element) { return elements.set(index, element == null ? JsonNull.INSTANCE : 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 */ @CanIgnoreReturnValue 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 */ @CanIgnoreReturnValue 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. * @since 2.8.7 */ 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 iterator() { return elements.iterator(); } /** * Returns the i-th element of the array. * * @param i the index of the element that is being sought. * @return the element present at the i-th index. * @throws IndexOutOfBoundsException if {@code i} is negative or greater than or equal to the * {@link #size()} of the array. */ public JsonElement get(int i) { return elements.get(i); } private JsonElement getAsSingleElement() { int size = elements.size(); if (size == 1) { return elements.get(0); } throw new IllegalStateException("Array must have size 1, but has size " + size); } /** * Convenience method to get this array as a {@link Number} if it contains a single element. This * method calls {@link JsonElement#getAsNumber()} on the element, therefore any of the exceptions * declared by that method can occur. * * @return this element as a number if it is single element array. * @throws IllegalStateException if the array is empty or has more than one element. */ @Override public Number getAsNumber() { return getAsSingleElement().getAsNumber(); } /** * Convenience method to get this array as a {@link String} if it contains a single element. This * method calls {@link JsonElement#getAsString()} on the element, therefore any of the exceptions * declared by that method can occur. * * @return this element as a String if it is single element array. * @throws IllegalStateException if the array is empty or has more than one element. */ @Override public String getAsString() { return getAsSingleElement().getAsString(); } /** * Convenience method to get this array as a double if it contains a single element. This method * calls {@link JsonElement#getAsDouble()} on the element, therefore any of the exceptions * declared by that method can occur. * * @return this element as a double if it is single element array. * @throws IllegalStateException if the array is empty or has more than one element. */ @Override public double getAsDouble() { return getAsSingleElement().getAsDouble(); } /** * Convenience method to get this array as a {@link BigDecimal} if it contains a single element. * This method calls {@link JsonElement#getAsBigDecimal()} on the element, therefore any of the * exceptions declared by that method can occur. * * @return this element as a {@link BigDecimal} if it is single element array. * @throws IllegalStateException if the array is empty or has more than one element. * @since 1.2 */ @Override public BigDecimal getAsBigDecimal() { return getAsSingleElement().getAsBigDecimal(); } /** * Convenience method to get this array as a {@link BigInteger} if it contains a single element. * This method calls {@link JsonElement#getAsBigInteger()} on the element, therefore any of the * exceptions declared by that method can occur. * * @return this element as a {@link BigInteger} if it is single element array. * @throws IllegalStateException if the array is empty or has more than one element. * @since 1.2 */ @Override public BigInteger getAsBigInteger() { return getAsSingleElement().getAsBigInteger(); } /** * Convenience method to get this array as a float if it contains a single element. This method * calls {@link JsonElement#getAsFloat()} on the element, therefore any of the exceptions declared * by that method can occur. * * @return this element as a float if it is single element array. * @throws IllegalStateException if the array is empty or has more than one element. */ @Override public float getAsFloat() { return getAsSingleElement().getAsFloat(); } /** * Convenience method to get this array as a long if it contains a single element. This method * calls {@link JsonElement#getAsLong()} on the element, therefore any of the exceptions declared * by that method can occur. * * @return this element as a long if it is single element array. * @throws IllegalStateException if the array is empty or has more than one element. */ @Override public long getAsLong() { return getAsSingleElement().getAsLong(); } /** * Convenience method to get this array as an integer if it contains a single element. This method * calls {@link JsonElement#getAsInt()} on the element, therefore any of the exceptions declared * by that method can occur. * * @return this element as an integer if it is single element array. * @throws IllegalStateException if the array is empty or has more than one element. */ @Override public int getAsInt() { return getAsSingleElement().getAsInt(); } /** * Convenience method to get this array as a primitive byte if it contains a single element. This * method calls {@link JsonElement#getAsByte()} on the element, therefore any of the exceptions * declared by that method can occur. * * @return this element as a primitive byte if it is single element array. * @throws IllegalStateException if the array is empty or has more than one element. */ @Override public byte getAsByte() { return getAsSingleElement().getAsByte(); } /** * Convenience method to get this array as a character if it contains a single element. This * method calls {@link JsonElement#getAsCharacter()} on the element, therefore any of the * exceptions declared by that method can occur. * * @return this element as a primitive short if it is single element array. * @throws IllegalStateException if the array is empty or has more than one element. * @deprecated This method is misleading, as it does not get this element as a char but rather as * a string's first character. */ @Deprecated @Override public char getAsCharacter() { return getAsSingleElement().getAsCharacter(); } /** * Convenience method to get this array as a primitive short if it contains a single element. This * method calls {@link JsonElement#getAsShort()} on the element, therefore any of the exceptions * declared by that method can occur. * * @return this element as a primitive short if it is single element array. * @throws IllegalStateException if the array is empty or has more than one element. */ @Override public short getAsShort() { return getAsSingleElement().getAsShort(); } /** * Convenience method to get this array as a boolean if it contains a single element. This method * calls {@link JsonElement#getAsBoolean()} on the element, therefore any of the exceptions * declared by that method can occur. * * @return this element as a boolean if it is single element array. * @throws IllegalStateException if the array is empty or has more than one element. */ @Override public boolean getAsBoolean() { return getAsSingleElement().getAsBoolean(); } /** * Returns a mutable {@link List} view of this {@code JsonArray}. Changes to the {@code List} are * visible in this {@code JsonArray} and the other way around. * *

The {@code List} does not permit {@code null} elements. Unlike {@code JsonArray}'s {@code * null} handling, a {@link NullPointerException} is thrown when trying to add {@code null}. Use * {@link JsonNull} for JSON null values. * * @return mutable {@code List} view * @since 2.10 */ public List asList() { return new NonNullElementWrapperList<>(elements); } /** * Returns whether the other object is equal to this. This method only considers the other object * to be equal if it is an instance of {@code JsonArray} and has equal elements in the same order. */ @Override public boolean equals(Object o) { return (o == this) || (o instanceof JsonArray && ((JsonArray) o).elements.equals(elements)); } /** * Returns the hash code of this array. This method calculates the hash code based on the elements * of this array. */ @Override public int hashCode() { return elements.hashCode(); } } ================================================ FILE: gson/src/main/java/com/google/gson/JsonDeserializationContext.java ================================================ /* * 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 The type of the deserialized object. * @return An object of type typeOfT. * @throws JsonParseException if the parse tree does not contain expected data. */ @SuppressWarnings("TypeParameterUnusedInFormals") T deserialize(JsonElement json, Type typeOfT) throws JsonParseException; } ================================================ FILE: gson/src/main/java/com/google/gson/JsonDeserializer.java ================================================ /* * 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 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)}. * *

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}. * *

 * public class Id<T> {
 *   private final Class<T> clazz;
 *   private final long value;
 *   public Id(Class<T> clazz, long value) {
 *     this.clazz = clazz;
 *     this.value = value;
 *   }
 *   public long getValue() {
 *     return value;
 *   }
 * }
 * 
* *

The default deserialization of {@code Id(com.foo.MyObject.class, 20L)} will require the JSON * string to be {"clazz":"com.foo.MyObject","value":20}. 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: * *

 * class IdDeserializer implements JsonDeserializer<Id> {
 *   public Id deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
 *       throws JsonParseException {
 *     long idValue = json.getAsJsonPrimitive().getAsLong();
 *     return new Id((Class) typeOfT, idValue);
 *   }
 * }
 * 
* *

You will also need to register {@code IdDeserializer} with Gson as follows: * *

 * Gson gson = new GsonBuilder().registerTypeAdapter(Id.class, new IdDeserializer()).create();
 * 
* *

Deserializers should be stateless and thread-safe, otherwise the thread-safety guarantees of * {@link Gson} might not apply. * *

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 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 { /** * Gson invokes this call-back method during deserialization when it encounters a field of the * specified type. * *

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 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} */ T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException; } ================================================ FILE: gson/src/main/java/com/google/gson/JsonElement.java ================================================ /* * 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.errorprone.annotations.CanIgnoreReturnValue; import com.google.gson.internal.Streams; import com.google.gson.stream.JsonWriter; import java.io.IOException; 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}. * *

This class provides multiple {@code getAs} methods which allow * *

    *
  • obtaining the represented primitive value, for example {@link #getAsString()} *
  • casting to the {@code JsonElement} subclasses in a convenient way, for example {@link * #getAsJsonObject()} *
* *

Converting {@code JsonElement} from / to JSON

* * There are two ways to parse JSON data as a {@link JsonElement}: * *
    *
  • {@link JsonParser}, for example: *
     * JsonObject jsonObject = JsonParser.parseString("{}").getAsJsonObject();
     * 
    *
  • {@link Gson#fromJson(java.io.Reader, Class) Gson.fromJson(..., JsonElement.class)}
    * It is possible to directly specify a {@code JsonElement} subclass, for example: *
     * JsonObject jsonObject = gson.fromJson("{}", JsonObject.class);
     * 
    *
* * To convert a {@code JsonElement} to JSON either {@link #toString() JsonElement.toString()} or the * method {@link Gson#toJson(JsonElement)} and its overloads can be used. * *

It is also possible to obtain the {@link TypeAdapter} for {@code JsonElement} from a {@link * Gson} instance and then use it for conversion from and to JSON: * *

{@code
 * TypeAdapter adapter = gson.getAdapter(JsonElement.class);
 *
 * JsonElement value = adapter.fromJson("{}");
 * String json = adapter.toJson(value);
 * }
* *

{@code JsonElement} as JSON data

* * {@code JsonElement} can also be treated as JSON data, allowing to deserialize from a {@code * JsonElement} and serializing to a {@code JsonElement}. The {@link Gson} class offers these * methods for this: * *
    *
  • {@link Gson#fromJson(JsonElement, Class) Gson.fromJson(JsonElement, ...)}, for example: *
     * JsonObject jsonObject = ...;
     * MyClass myObj = gson.fromJson(jsonObject, MyClass.class);
     * 
    *
  • {@link Gson#toJsonTree(Object)}, for example: *
     * MyClass myObj = ...;
     * JsonElement json = gson.toJsonTree(myObj);
     * 
    *
* * The {@link TypeAdapter} class provides corresponding methods as well: * *
    *
  • {@link TypeAdapter#fromJsonTree(JsonElement)} *
  • {@link TypeAdapter#toJsonTree(Object)} *
* * @author Inderjeet Singh * @author Joel Leitch */ public abstract class JsonElement { /** * @deprecated Creating custom {@code JsonElement} subclasses is highly discouraged and can lead * to undefined behavior.
* This constructor is only kept for backward compatibility. */ @Deprecated public 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 a check for verifying if this element is a JSON array or not. * * @return true if this element is of type {@link JsonArray}, false otherwise. */ public boolean isJsonArray() { return this instanceof JsonArray; } /** * Provides a 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 a 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 a 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 this element is of some * other type, an {@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 this element as a {@link JsonObject}. * @throws IllegalStateException if this 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 this element is of some other * type, an {@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 this element as a {@link JsonArray}. * @throws IllegalStateException if this 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 this element is of some * other type, an {@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 this element as a {@link JsonPrimitive}. * @throws IllegalStateException if this 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 this element is of some other * type, an {@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 this element as a {@link JsonNull}. * @throws IllegalStateException if this element is of another type. * @since 1.2 */ @CanIgnoreReturnValue // When this method is used only to verify that the value is JsonNull 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 this element as a primitive boolean value. * @throws UnsupportedOperationException if this element is not a {@link JsonPrimitive} or {@link * JsonArray}. * @throws IllegalStateException if this 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 this element as a {@link Number}. * @throws UnsupportedOperationException if this element is not a {@link JsonPrimitive} or {@link * JsonArray}, or cannot be converted to a number. * @throws IllegalStateException if this 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 this element as a string value. * @throws UnsupportedOperationException if this element is not a {@link JsonPrimitive} or {@link * JsonArray}. * @throws IllegalStateException if this 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 this element as a primitive double value. * @throws UnsupportedOperationException if this element is not a {@link JsonPrimitive} or {@link * JsonArray}. * @throws NumberFormatException if the value contained is not a valid double. * @throws IllegalStateException if this 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 this element as a primitive float value. * @throws UnsupportedOperationException if this element is not a {@link JsonPrimitive} or {@link * JsonArray}. * @throws NumberFormatException if the value contained is not a valid float. * @throws IllegalStateException if this 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 this element as a primitive long value. * @throws UnsupportedOperationException if this element is not a {@link JsonPrimitive} or {@link * JsonArray}. * @throws NumberFormatException if the value contained is not a valid long. * @throws IllegalStateException if this 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 this element as a primitive integer value. * @throws UnsupportedOperationException if this element is not a {@link JsonPrimitive} or {@link * JsonArray}. * @throws NumberFormatException if the value contained is not a valid integer. * @throws IllegalStateException if this 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 this element as a primitive byte value. * @throws UnsupportedOperationException if this element is not a {@link JsonPrimitive} or {@link * JsonArray}. * @throws NumberFormatException if the value contained is not a valid byte. * @throws IllegalStateException if this 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 the string value of this element. * * @return the first character of the string value. * @throws UnsupportedOperationException if this element is not a {@link JsonPrimitive} or {@link * JsonArray}, or if its string value is empty. * @throws IllegalStateException if this 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 this element as a {@link BigDecimal}. * @throws UnsupportedOperationException if this element is not a {@link JsonPrimitive} or {@link * JsonArray}. * @throws NumberFormatException if this element is not a valid {@link BigDecimal}. * @throws IllegalStateException if this 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 this element as a {@link BigInteger}. * @throws UnsupportedOperationException if this element is not a {@link JsonPrimitive} or {@link * JsonArray}. * @throws NumberFormatException if this element is not a valid {@link BigInteger}. * @throws IllegalStateException if this 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 this element as a primitive short value. * @throws UnsupportedOperationException if this element is not a {@link JsonPrimitive} or {@link * JsonArray}. * @throws NumberFormatException if the value contained is not a valid short. * @throws IllegalStateException if this element is of the type {@link JsonArray} but contains * more than a single element. */ public short getAsShort() { throw new UnsupportedOperationException(getClass().getSimpleName()); } /** * Converts this element to a JSON string. * *

For example: * *

   * JsonObject object = new JsonObject();
   * object.add("a", JsonNull.INSTANCE);
   * JsonArray array = new JsonArray();
   * array.add(1);
   * object.add("b", array);
   *
   * String json = object.toString();
   * // json: {"a":null,"b":[1]}
   * 
* * If this element or any nested elements contain {@link Double#NaN NaN} or {@link * Double#isInfinite() Infinity} that value is written to JSON, even though the JSON specification * does not permit these values. * *

To customize formatting or to directly write to an {@link Appendable} instead of creating an * intermediate {@code String} first, use {@link Gson#toJson(JsonElement, Appendable) * Gson.toJson(JsonElement, ...)}. * *

To get the contained String value (without enclosing {@code "} and without escaping), use * {@link #getAsString()} instead: * *

   * JsonPrimitive jsonPrimitive = new JsonPrimitive("with \" quote");
   * String json = jsonPrimitive.toString();
   * // json: "with \" quote"
   * String value = jsonPrimitive.getAsString();
   * // value: with " quote
   * 
*/ @Override public String toString() { try { StringBuilder stringBuilder = new StringBuilder(); JsonWriter jsonWriter = new JsonWriter(Streams.writerForAppendable(stringBuilder)); // Make writer lenient because toString() must not fail, even if for example JsonPrimitive // contains NaN jsonWriter.setStrictness(Strictness.LENIENT); Streams.write(this, jsonWriter); return stringBuilder.toString(); } catch (IOException e) { throw new AssertionError(e); } } } ================================================ FILE: gson/src/main/java/com/google/gson/JsonIOException.java ================================================ /* * 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 */ @SuppressWarnings("MemberName") // class name is part of the public API 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); } } ================================================ FILE: gson/src/main/java/com/google/gson/JsonNull.java ================================================ /* * 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 {@code JsonNull}. * * @since 1.8 */ public static final JsonNull INSTANCE = new JsonNull(); /** * Creates a new {@code JsonNull} object. * * @deprecated 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 {@code JsonNull} have the same hash code since they are indistinguishable. */ @Override public int hashCode() { return JsonNull.class.hashCode(); } /** All instances of {@code JsonNull} are considered equal. */ @Override public boolean equals(Object other) { return other instanceof JsonNull; } } ================================================ FILE: gson/src/main/java/com/google/gson/JsonObject.java ================================================ /* * 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.errorprone.annotations.CanIgnoreReturnValue; 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. * This class does not support {@code null} values. If {@code null} is provided as value argument to * any of the methods, it is converted to a {@link JsonNull}. * *

{@code JsonObject} does not implement the {@link Map} interface, but a {@code Map} view of it * can be obtained with {@link #asMap()}. * *

See the {@link JsonElement} documentation for details on how to convert {@code JsonObject} and * generally any {@code JsonElement} from and to JSON. * * @author Inderjeet Singh * @author Joel Leitch */ public final class JsonObject extends JsonElement { private final LinkedTreeMap members = new LinkedTreeMap<>(false); /** Creates an empty JsonObject. */ @SuppressWarnings("deprecation") // superclass constructor public JsonObject() {} /** * 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 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 {@link 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 object. * * @param property name of the member that should be removed. * @return the {@link JsonElement} object that is being removed, or {@code null} if no member with * this name exists. * @since 1.3 */ @CanIgnoreReturnValue public JsonElement remove(String property) { return members.remove(property); } /** * Convenience method to add a string member. The specified value is converted to a {@link * 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 number member. The specified value is converted to a {@link * 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 {@link * JsonPrimitive} of Boolean. * * @param property name of the member. * @param value the boolean 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 {@link * JsonPrimitive} of Character. * * @param property name of the member. * @param value the char 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> 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 keySet() { return members.keySet(); } /** * Returns the number of key/value pairs in the object. * * @return the number of key/value pairs in the object. * @since 2.7 */ public int size() { return members.size(); } /** * Returns true if the number of key/value pairs in the object is zero. * * @return true if the number of key/value pairs in the object is zero. * @since 2.10.1 */ public boolean isEmpty() { return members.isEmpty(); } /** * 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, or {@code null} if no such member exists. */ public JsonElement get(String memberName) { return members.get(memberName); } /** * Convenience method to get the specified member as a {@link JsonPrimitive}. * * @param memberName name of the member being requested. * @return the {@code JsonPrimitive} corresponding to the specified member, or {@code null} if no * member with this name exists. * @throws ClassCastException if the member is not of type {@code JsonPrimitive}. */ public JsonPrimitive getAsJsonPrimitive(String memberName) { return (JsonPrimitive) members.get(memberName); } /** * Convenience method to get the specified member as a {@link JsonArray}. * * @param memberName name of the member being requested. * @return the {@code JsonArray} corresponding to the specified member, or {@code null} if no * member with this name exists. * @throws ClassCastException if the member is not of type {@code JsonArray}. */ public JsonArray getAsJsonArray(String memberName) { return (JsonArray) members.get(memberName); } /** * Convenience method to get the specified member as a {@link JsonObject}. * * @param memberName name of the member being requested. * @return the {@code JsonObject} corresponding to the specified member, or {@code null} if no * member with this name exists. * @throws ClassCastException if the member is not of type {@code JsonObject}. */ public JsonObject getAsJsonObject(String memberName) { return (JsonObject) members.get(memberName); } /** * Returns a mutable {@link Map} view of this {@code JsonObject}. Changes to the {@code Map} are * visible in this {@code JsonObject} and the other way around. * *

The {@code Map} does not permit {@code null} keys or values. Unlike {@code JsonObject}'s * {@code null} handling, a {@link NullPointerException} is thrown when trying to add {@code * null}. Use {@link JsonNull} for JSON null values. * * @return mutable {@code Map} view * @since 2.10 */ public Map asMap() { // It is safe to expose the underlying map because it disallows null keys and values return members; } /** * Returns whether the other object is equal to this. This method only considers the other object * to be equal if it is an instance of {@code JsonObject} and has equal members, ignoring order. */ @Override public boolean equals(Object o) { return (o == this) || (o instanceof JsonObject && ((JsonObject) o).members.equals(members)); } /** * Returns the hash code of this object. This method calculates the hash code based on the members * of this object, ignoring order. */ @Override public int hashCode() { return members.hashCode(); } } ================================================ FILE: gson/src/main/java/com/google/gson/JsonParseException.java ================================================ /* * 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. * *

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}. * * @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); } } ================================================ FILE: gson/src/main/java/com/google/gson/JsonParser.java ================================================ /* * 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.errorprone.annotations.InlineMe; 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. * *

The JSON data is parsed in {@linkplain JsonReader#setStrictness(Strictness) lenient mode}. * *

Here's an example of parsing from a string: * *

 * String json = "{\"key\": \"value\"}";
 * JsonElement jsonElement = JsonParser.parseString(json);
 * JsonObject jsonObject = jsonElement.getAsJsonObject();
 * 
* *

It can also parse from a reader: * *

 * try (Reader reader = new FileReader("my-data.json", StandardCharsets.UTF_8)) {
 *   JsonElement jsonElement = JsonParser.parseReader(reader);
 *   JsonObject jsonObject = jsonElement.getAsJsonObject();
 * }
 * 
* *

If you want to parse from a {@link JsonReader} for more customized parsing requirements, the * following example demonstrates how to achieve it: * *

 * String json = "{\"skipObj\": {\"skipKey\": \"skipValue\"}, \"obj\": {\"key\": \"value\"}}";
 * try (JsonReader jsonReader = new JsonReader(new StringReader(json))) {
 *   jsonReader.beginObject();
 *   while (jsonReader.hasNext()) {
 *     String fieldName = jsonReader.nextName();
 *     if (fieldName.equals("skipObj")) {
 *       jsonReader.skipValue();
 *     } else {
 *       JsonElement jsonElement = JsonParser.parseReader(jsonReader);
 *       JsonObject jsonObject = jsonElement.getAsJsonObject();
 *     }
 *   }
 *   jsonReader.endObject();
 * }
 * 
* * @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. * *

The JSON string is parsed in {@linkplain JsonReader#setStrictness(Strictness) 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 * @since 2.8.6 */ 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. * *

The JSON data is parsed in {@linkplain JsonReader#setStrictness(Strictness) 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 * @since 2.8.6 */ 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 | NumberFormatException e) { throw new JsonSyntaxException(e); } catch (IOException e) { throw new JsonIOException(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. * *

If the {@linkplain JsonReader#getStrictness() strictness of the reader} is {@link * Strictness#STRICT}, that strictness will be used for parsing. Otherwise the strictness will be * temporarily changed to {@link Strictness#LENIENT} and will be restored once this method * returns. * * @throws JsonParseException if there is an IOException or if the specified text is not valid * JSON * @since 2.8.6 */ public static JsonElement parseReader(JsonReader reader) throws JsonIOException, JsonSyntaxException { Strictness strictness = reader.getStrictness(); if (strictness == Strictness.LEGACY_STRICT) { // For backward compatibility change to LENIENT if reader has default strictness LEGACY_STRICT reader.setStrictness(Strictness.LENIENT); } try { return Streams.parse(reader); } catch (StackOverflowError | OutOfMemoryError e) { throw new JsonParseException("Failed parsing JSON source: " + reader + " to Json", e); } finally { reader.setStrictness(strictness); } } /** * @deprecated Use {@link JsonParser#parseString} */ @Deprecated @InlineMe(replacement = "JsonParser.parseString(json)", imports = "com.google.gson.JsonParser") public JsonElement parse(String json) throws JsonSyntaxException { return parseString(json); } /** * @deprecated Use {@link JsonParser#parseReader(Reader)} */ @Deprecated @InlineMe(replacement = "JsonParser.parseReader(json)", imports = "com.google.gson.JsonParser") public JsonElement parse(Reader json) throws JsonIOException, JsonSyntaxException { return parseReader(json); } /** * @deprecated Use {@link JsonParser#parseReader(JsonReader)} */ @Deprecated @InlineMe(replacement = "JsonParser.parseReader(json)", imports = "com.google.gson.JsonParser") public JsonElement parse(JsonReader json) throws JsonIOException, JsonSyntaxException { return parseReader(json); } } ================================================ FILE: gson/src/main/java/com/google/gson/JsonPrimitive.java ================================================ /* * 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.LazilyParsedNumber; import com.google.gson.internal.NumberLimits; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Objects; /** * A class representing a JSON primitive value. A primitive value is either a String, a Java * primitive, or a Java primitive wrapper type. * *

See the {@link JsonElement} documentation for details on how to convert {@code JsonPrimitive} * and generally any {@code JsonElement} from and to JSON. * * @author Inderjeet Singh * @author Joel Leitch */ 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. */ // "deprecation" suppression for superclass constructor // "UnnecessaryBoxedVariable" Error Prone warning is correct since method does not accept // null, but cannot be changed anymore since this is public API @SuppressWarnings({"deprecation", "UnnecessaryBoxedVariable"}) public JsonPrimitive(Boolean bool) { value = Objects.requireNonNull(bool); } /** * Create a primitive containing a {@link Number}. * * @param number the value to create the primitive with. */ @SuppressWarnings("deprecation") // superclass constructor public JsonPrimitive(Number number) { value = Objects.requireNonNull(number); } /** * Create a primitive containing a String value. * * @param string the value to create the primitive with. */ @SuppressWarnings("deprecation") // superclass constructor public JsonPrimitive(String string) { value = Objects.requireNonNull(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. */ // "deprecation" suppression for superclass constructor // "UnnecessaryBoxedVariable" Error Prone warning is correct since method does not accept // null, but cannot be changed anymore since this is public API @SuppressWarnings({"deprecation", "UnnecessaryBoxedVariable"}) public JsonPrimitive(Character c) { // convert characters to strings since in JSON, characters are represented as a single // character string value = Objects.requireNonNull(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. If this primitive {@linkplain * #isBoolean() is not a boolean}, the string value is parsed using {@link * Boolean#parseBoolean(String)}. This means {@code "true"} (ignoring case) is considered {@code * true} and any other value is considered {@code false}. */ @Override public boolean getAsBoolean() { if (isBoolean()) { return (Boolean) value; } // 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 {@link Number}. If this primitive {@linkplain * #isString() is a string}, a lazily parsed {@code Number} is constructed which parses the string * when any of its methods are called (which can lead to a {@link NumberFormatException}). * * @throws UnsupportedOperationException if this primitive is neither a number nor a string. */ @Override public Number getAsNumber() { if (value instanceof Number) { return (Number) value; } else if (value instanceof String) { return new LazilyParsedNumber((String) value); } throw new UnsupportedOperationException("Primitive is neither a number nor a string"); } /** * 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; } // Don't add Javadoc, inherit it from super implementation; no exceptions are thrown here @Override public String getAsString() { if (value instanceof String) { return (String) value; } else if (isNumber()) { return getAsNumber().toString(); } else if (isBoolean()) { return ((Boolean) value).toString(); } throw new AssertionError("Unexpected value type: " + value.getClass()); } /** * @throws NumberFormatException {@inheritDoc} */ @Override public double getAsDouble() { return isNumber() ? getAsNumber().doubleValue() : Double.parseDouble(getAsString()); } /** * @throws NumberFormatException {@inheritDoc} */ @Override public BigDecimal getAsBigDecimal() { return value instanceof BigDecimal ? (BigDecimal) value : NumberLimits.parseBigDecimal(getAsString()); } /** * @throws NumberFormatException {@inheritDoc} */ @Override public BigInteger getAsBigInteger() { return value instanceof BigInteger ? (BigInteger) value : isIntegral(this) ? BigInteger.valueOf(this.getAsNumber().longValue()) : NumberLimits.parseBigInteger(this.getAsString()); } /** * @throws NumberFormatException {@inheritDoc} */ @Override public float getAsFloat() { return isNumber() ? getAsNumber().floatValue() : Float.parseFloat(getAsString()); } /** * Convenience method to get this element as a primitive long. * * @return this element as a primitive long. * @throws NumberFormatException {@inheritDoc} */ @Override public long getAsLong() { return isNumber() ? getAsNumber().longValue() : Long.parseLong(getAsString()); } /** * @throws NumberFormatException {@inheritDoc} */ @Override public short getAsShort() { return isNumber() ? getAsNumber().shortValue() : Short.parseShort(getAsString()); } /** * @throws NumberFormatException {@inheritDoc} */ @Override public int getAsInt() { return isNumber() ? getAsNumber().intValue() : Integer.parseInt(getAsString()); } /** * @throws NumberFormatException {@inheritDoc} */ @Override public byte getAsByte() { return isNumber() ? getAsNumber().byteValue() : Byte.parseByte(getAsString()); } /** * @throws UnsupportedOperationException if the string value of this primitive is empty. * @deprecated This method is misleading, as it does not get this element as a char but rather as * a string's first character. */ @Deprecated @Override public char getAsCharacter() { String s = getAsString(); if (s.isEmpty()) { throw new UnsupportedOperationException("String value is empty"); } else { return s.charAt(0); } } /** Returns the hash code of this object. */ @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(); } /** * Returns whether the other object is equal to this. This method only considers the other object * to be equal if it is an instance of {@code JsonPrimitive} and has an equal value. */ @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 (this.value instanceof BigInteger || other.value instanceof BigInteger) ? this.getAsBigInteger().equals(other.getAsBigInteger()) : this.getAsNumber().longValue() == other.getAsNumber().longValue(); } if (value instanceof Number && other.value instanceof Number) { if (value instanceof BigDecimal && other.value instanceof BigDecimal) { // Uses compareTo to ignore scale of values, e.g. `0` and `0.00` should be considered equal return this.getAsBigDecimal().compareTo(other.getAsBigDecimal()) == 0; } double thisAsDouble = this.getAsDouble(); double otherAsDouble = other.getAsDouble(); // Don't use Double.compare(double, double) because that considers -0.0 and +0.0 not equal return (thisAsDouble == otherAsDouble) || (Double.isNaN(thisAsDouble) && Double.isNaN(otherAsDouble)); } 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; } } ================================================ FILE: gson/src/main/java/com/google/gson/JsonSerializationContext.java ================================================ /* * 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}. */ 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}. */ JsonElement serialize(Object src, Type typeOfSrc); } ================================================ FILE: gson/src/main/java/com/google/gson/JsonSerializer.java ================================================ /* * 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)}. * *

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}. * *

 * public class Id<T> {
 *   private final Class<T> clazz;
 *   private final long value;
 *
 *   public Id(Class<T> clazz, long value) {
 *     this.clazz = clazz;
 *     this.value = value;
 *   }
 *
 *   public long getValue() {
 *     return value;
 *   }
 * }
 * 
* *

The default serialization of {@code Id(com.foo.MyObject.class, 20L)} will be * {"clazz":"com.foo.MyObject","value":20}. 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: * *

 * class IdSerializer implements JsonSerializer<Id> {
 *   public JsonElement serialize(Id id, Type typeOfId, JsonSerializationContext context) {
 *     return new JsonPrimitive(id.getValue());
 *   }
 * }
 * 
* *

You will also need to register {@code IdSerializer} with Gson as follows: * *

 * Gson gson = new GsonBuilder().registerTypeAdapter(Id.class, new IdSerializer()).create();
 * 
* *

Serializers should be stateless and thread-safe, otherwise the thread-safety guarantees of * {@link Gson} might not apply. * *

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 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 { /** * Gson invokes this call-back method during serialization when it encounters a field of the * specified type. * *

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). * * @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. */ JsonElement serialize(T src, Type typeOfSrc, JsonSerializationContext context); } ================================================ FILE: gson/src/main/java/com/google/gson/JsonStreamParser.java ================================================ /* * 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; import java.util.Iterator; import java.util.NoSuchElementException; /** * 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#setStrictness(Strictness)}. * *

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: * *

 * 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();
 *   }
 * }
 * 
* * @author Inderjeet Singh * @author Joel Leitch * @since 1.4 */ public final class JsonStreamParser implements Iterator { 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.setStrictness(Strictness.LENIENT); 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 JsonParseException 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 | OutOfMemoryError e) { throw new JsonParseException("Failed parsing JSON source to Json", 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 JsonParseException 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(); } } ================================================ FILE: gson/src/main/java/com/google/gson/JsonSyntaxException.java ================================================ /* * 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); } } ================================================ FILE: gson/src/main/java/com/google/gson/LongSerializationPolicy.java ================================================ /* * 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.bind.TypeAdapters; /** * 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}} * *

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); } @Override TypeAdapter typeAdapter() { return TypeAdapters.LONG; } }, /** * 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"}} * *

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()); } @Override TypeAdapter typeAdapter() { return TypeAdapters.LONG_AS_STRING; } }; /** * 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); /** Returns the corresponding {@link TypeAdapter} for this serialization policy. */ // Internal method abstract TypeAdapter typeAdapter(); } ================================================ FILE: gson/src/main/java/com/google/gson/ReflectionAccessFilter.java ================================================ /* * Copyright (C) 2022 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.ReflectionAccessFilterHelper; import java.lang.reflect.AccessibleObject; /** * Filter for determining whether reflection based serialization and deserialization is allowed for * a class. * *

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}. * *

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. * *

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) * @since 2.9.1 */ public interface ReflectionAccessFilter { /** * Result of a filter check. * * @since 2.9.1 */ enum FilterResult { /** * Reflection access for the class is allowed. * *

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 open the * complete module or certain packages for reflection and will consider such packages * inaccessible. * *

Note that this only works for Java 9 and higher, 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 (JLS 11 * §6.6), restrictions imposed by a {@link SecurityManager} are not considered. * *

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). * *

If this filter encounters a class other than a standard Java class it returns {@link * FilterResult#INDECISIVE}. * *

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 only works * for Java 9 and higher, when using an older Java version its functionality will be limited. * *

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; } @Override public String toString() { return "ReflectionAccessFilter#BLOCK_INACCESSIBLE_JAVA"; } }; /** * Blocks all reflection access to members of standard Java classes. * *

If this filter encounters a class other than a standard Java class it returns {@link * FilterResult#INDECISIVE}. * *

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. * *

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; } @Override public String toString() { return "ReflectionAccessFilter#BLOCK_ALL_JAVA"; } }; /** * Blocks all reflection access to members of standard Android classes. * *

If this filter encounters a class other than a standard Android class it returns {@link * FilterResult#INDECISIVE}. * *

This filter is mainly intended to prevent depending on implementation details of the Android * platform. * *

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; } @Override public String toString() { return "ReflectionAccessFilter#BLOCK_ALL_ANDROID"; } }; /** * Blocks all reflection access to members of classes belonging to programming language platforms, * such as Java, Android, Kotlin or Scala. * *

If this filter encounters a class other than a standard platform class it returns {@link * FilterResult#INDECISIVE}. * *

This filter is mainly intended to prevent depending on implementation details of the * platform classes. * *

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; } @Override public String toString() { return "ReflectionAccessFilter#BLOCK_ALL_PLATFORM"; } }; /** * 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); } ================================================ FILE: gson/src/main/java/com/google/gson/Strictness.java ================================================ package com.google.gson; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; /** * Modes that indicate how strictly a JSON {@linkplain JsonReader reader} or {@linkplain JsonWriter * writer} follows the syntax laid out in the RFC * 8259 JSON specification. * *

You can look at {@link JsonReader#setStrictness(Strictness)} to see how the strictness affects * the {@link JsonReader} and you can look at {@link JsonWriter#setStrictness(Strictness)} to see * how the strictness affects the {@link JsonWriter}. * * @see GsonBuilder#setStrictness(Strictness) * @see JsonReader#setStrictness(Strictness) * @see JsonWriter#setStrictness(Strictness) * @since 2.11.0 */ public enum Strictness { /** Allow large deviations from the JSON specification. */ LENIENT, /** Allow certain small deviations from the JSON specification for legacy reasons. */ LEGACY_STRICT, /** Strict compliance with the JSON specification. */ STRICT } ================================================ FILE: gson/src/main/java/com/google/gson/ToNumberPolicy.java ================================================ /* * 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 com.google.gson.internal.LazilyParsedNumber; import com.google.gson.internal.NumberLimits; import com.google.gson.stream.JsonReader; import com.google.gson.stream.MalformedJsonException; import java.io.IOException; import java.math.BigDecimal; /** * 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 * @since 2.8.9 */ 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(); if (value.indexOf('.') >= 0) { return parseAsDouble(value, in); } else { try { return Long.parseLong(value); } catch (NumberFormatException e) { return parseAsDouble(value, in); } } } private Number parseAsDouble(String value, JsonReader in) throws IOException { try { Double d = Double.valueOf(value); if ((d.isInfinite() || d.isNaN()) && !in.isLenient()) { throw new MalformedJsonException( "JSON forbids NaN and infinities: " + d + "; at path " + in.getPreviousPath()); } return d; } catch (NumberFormatException e) { throw new JsonParseException( "Cannot parse " + value + "; at path " + in.getPreviousPath(), e); } } }, /** * 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 NumberLimits.parseBigDecimal(value); } catch (NumberFormatException e) { throw new JsonParseException( "Cannot parse " + value + "; at path " + in.getPreviousPath(), e); } } } } ================================================ FILE: gson/src/main/java/com/google/gson/ToNumberStrategy.java ================================================ /* * 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 com.google.gson.stream.JsonReader; import java.io.IOException; /** * 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: * *

    *
  • {@link Double} values are returned for JSON numbers if the deserialization type is declared * as {@code Object}, see {@link ToNumberPolicy#DOUBLE}; *
  • Lazily parsed number values are returned if the deserialization type is declared as {@code * Number}, see {@link ToNumberPolicy#LAZILY_PARSED_NUMBER}. *
* *

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, RFC 8259 permits this: * *

 *   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.
 * 
* *

To overcome the precision loss, use for example {@link ToNumberPolicy#LONG_OR_DOUBLE} or * {@link ToNumberPolicy#BIG_DECIMAL}. * * @see ToNumberPolicy * @see GsonBuilder#setObjectToNumberStrategy(ToNumberStrategy) * @see GsonBuilder#setNumberToNumberStrategy(ToNumberStrategy) * @since 2.8.9 */ 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. */ Number readNumber(JsonReader in) throws IOException; } ================================================ FILE: gson/src/main/java/com/google/gson/TypeAdapter.java ================================================ /* * 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.Streams; 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.Writer; /** * Converts Java objects to and from JSON. * *

Defining a type's JSON form

* * 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: * *
{@code
 * public class PointAdapter extends TypeAdapter {
 *   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);
 *   }
 * }
 * }
* * 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. * *

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()} or {@code nullValue()}. For arrays, type adapters * should start with a call to {@code beginArray()}, convert all elements, and finish with a call to * {@code endArray()}. For objects, they should start with {@code beginObject()}, convert the * object, and finish with {@code endObject()}. Failing to convert a value or converting too many * values may cause the application to crash. * *

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. * *

Type adapters should be stateless and thread-safe, otherwise the thread-safety guarantees of * {@link Gson} might not apply. * *

To use a custom type adapter with Gson, you must register it with a {@link * GsonBuilder}: * *

{@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();
 * }
* * @since 2.1 */ // non-Javadoc: // //

JSON Conversion

//

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:

{@code
//   String json = "{'origin':'0,0','points':['1,2','3,4']}";
//   TypeAdapter graphAdapter = gson.getAdapter(Graph.class);
//   Graph graph = graphAdapter.fromJson(json);
// }
// And an example for serialization:
{@code
//   Graph graph = new Graph(...);
//   TypeAdapter graphAdapter = gson.getAdapter(Graph.class);
//   String json = graphAdapter.toJson(graph);
// }
// //

Type adapters are type-specific. For example, a {@code // TypeAdapter} can convert {@code Date} instances to JSON and JSON to // instances of {@code Date}, but cannot convert any other types. // public abstract class TypeAdapter { public TypeAdapter() {} /** * 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}. * *

A {@link JsonWriter} with default configuration is used for writing the JSON data. To * customize this behavior, create a {@link JsonWriter}, configure it and then use {@link * #write(JsonWriter, Object)} instead. * * @param value the Java object to convert. May be {@code null}. * @since 2.2 */ public final void toJson(Writer out, T value) throws IOException { JsonWriter writer = new JsonWriter(out); write(writer, value); } /** * Converts {@code value} to a JSON document. * *

A {@link JsonWriter} with default configuration is used for writing the JSON data. To * customize this behavior, create a {@link JsonWriter}, configure it and then use {@link * #write(JsonWriter, Object)} instead. * * @throws JsonIOException wrapping {@code IOException}s thrown by {@link #write(JsonWriter, * Object)} * @param value the Java object to convert. May be {@code null}. * @since 2.2 */ public final String toJson(T value) { StringBuilder stringBuilder = new StringBuilder(); try { toJson(Streams.writerForAppendable(stringBuilder), value); } catch (IOException e) { throw new JsonIOException(e); } return stringBuilder.toString(); } /** * Converts {@code value} to a JSON tree. * * @param value the Java object to convert. May be {@code null}. * @return the converted JSON tree. May be {@link JsonNull}. * @throws JsonIOException wrapping {@code IOException}s thrown by {@link #write(JsonWriter, * Object)} * @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 {@code null}. */ public abstract T read(JsonReader in) throws IOException; /** * Converts the JSON document in {@code in} to a Java object. * *

A {@link JsonReader} with default configuration (that is with {@link * Strictness#LEGACY_STRICT} as strictness) is used for reading the JSON data. To customize this * behavior, create a {@link JsonReader}, configure it and then use {@link #read(JsonReader)} * instead. * *

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 {@code 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. * *

A {@link JsonReader} with default configuration (that is with {@link * Strictness#LEGACY_STRICT} as strictness) is used for reading the JSON data. To customize this * behavior, create a {@link JsonReader}, configure it and then use {@link #read(JsonReader)} * instead. * *

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 {@code 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 {@code null}. * @throws JsonIOException wrapping {@code IOException}s thrown by {@link #read(JsonReader)} * @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); } } /** * 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:
* *

{@code
   * Gson gson = new GsonBuilder().registerTypeAdapter(Foo.class,
   *   new TypeAdapter() {
   *     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();
   * }
* * 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: * *
{@code
   * Gson gson = new GsonBuilder().registerTypeAdapter(Foo.class,
   *   new TypeAdapter() {
   *     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();
   * }
* * Note that we didn't need to check for nulls in our type adapter after we used nullSafe. */ public final TypeAdapter nullSafe() { if (!(this instanceof TypeAdapter.NullSafeTypeAdapter)) { return new NullSafeTypeAdapter(); } return this; } private final class NullSafeTypeAdapter extends TypeAdapter { @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); } @Override public String toString() { return "NullSafeTypeAdapter[" + TypeAdapter.this + "]"; } } } ================================================ FILE: gson/src/main/java/com/google/gson/TypeAdapterFactory.java ================================================ /* * 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. * *

Examples

* *

Example: Converting enums to lowercase

* * 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: * *
{@code
 * public class LowercaseEnumTypeAdapterFactory implements TypeAdapterFactory {
 *   public  TypeAdapter create(Gson gson, TypeToken type) {
 *     Class rawType = (Class) type.getRawType();
 *     if (!rawType.isEnum()) {
 *       return null;
 *     }
 *
 *     final Map lowercaseToConstant = new HashMap<>();
 *     for (T constant : rawType.getEnumConstants()) {
 *       lowercaseToConstant.put(toLowercase(constant), constant);
 *     }
 *
 *     return new TypeAdapter() {
 *       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);
 *   }
 * }
 * }
* *

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. * *

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. * *

As with type adapters, factories must be registered with a {@link * com.google.gson.GsonBuilder} for them to take effect: * *

{@code
 * GsonBuilder builder = new GsonBuilder();
 * builder.registerTypeAdapterFactory(new LowercaseEnumTypeAdapterFactory());
 * ...
 * Gson gson = builder.create();
 * }
* * If multiple factories support the same type, the factory registered earlier takes precedence. * *

Example: Composing other type adapters

* * 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} is different from the type adapter for {@code Multiset}. * *

The type adapter delegates 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: * *

{@code
 * public class MultisetTypeAdapterFactory implements TypeAdapterFactory {
 *   public  TypeAdapter create(Gson gson, TypeToken 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) newMultisetAdapter(elementAdapter);
 *   }
 *
 *   private  TypeAdapter> newMultisetAdapter(
 *       TypeAdapter elementAdapter) {
 *     return new TypeAdapter>() {
 *       public void write(JsonWriter out, Multiset value) throws IOException {
 *         if (value == null) {
 *           out.nullValue();
 *           return;
 *         }
 *
 *         out.beginArray();
 *         for (Multiset.Entry entry : value.entrySet()) {
 *           out.value(entry.getCount());
 *           elementAdapter.write(out, entry.getElement());
 *         }
 *         out.endArray();
 *       }
 *
 *       public Multiset read(JsonReader in) throws IOException {
 *         if (in.peek() == JsonToken.NULL) {
 *           in.nextNull();
 *           return null;
 *         }
 *
 *         Multiset 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;
 *       }
 *     };
 *   }
 * }
 * }
* * 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}. */ TypeAdapter create(Gson gson, TypeToken type); } ================================================ FILE: gson/src/main/java/com/google/gson/annotations/Expose.java ================================================ /* * 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. * *

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. * *

Here is an example of how this annotation is meant to be used: * *

 * public class User {
 *   @Expose private String firstName;
 *   @Expose(serialize = false) private String lastName;
 *   @Expose (serialize = false, deserialize = false) private String emailAddress;
 *   private String password;
 * }
 * 
* * 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. * *

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 */ 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 */ boolean deserialize() default true; } ================================================ FILE: gson/src/main/java/com/google/gson/annotations/JsonAdapter.java ================================================ /* * 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.Gson; import com.google.gson.GsonBuilder; import com.google.gson.InstanceCreator; 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. * *

Here is an example of how this annotation is used: * *

 * @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<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();
 *   }
 *
 *   @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]);
 *   }
 * }
 * 
* * Since {@code User} class specified {@code UserJsonAdapter.class} in {@code @JsonAdapter} * annotation, it will automatically be invoked to serialize/deserialize {@code User} instances. * *

Here is an example of how to apply this annotation to a field. * *

 * private static final class Gadget {
 *   @JsonAdapter(UserJsonAdapter.class)
 *   final User user;
 *
 *   Gadget(User user) {
 *     this.user = user;
 *   }
 * }
 * 
* * It's possible to specify different type adapters on a field, that field's type, and in the {@link * GsonBuilder}. Field annotations take precedence over {@code GsonBuilder}-registered type * adapters, which in turn take precedence over annotated types. * *

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 * {@link Gson} instance. By default the specified adapter will not be called for {@code null} * values; set {@link #nullSafe()} to {@code false} to let the adapter handle {@code null} values * itself. * *

The type adapter is created in the same way Gson creates instances of custom classes during * deserialization, that means: * *

    *
  1. If a custom {@link InstanceCreator} has been registered for the adapter class, it will be * used to create the instance *
  2. Otherwise, if the adapter class has a no-args constructor (regardless of which visibility), * it will be invoked to create the instance *
  3. Otherwise, JDK {@code Unsafe} will be used to create the instance; see {@link * GsonBuilder#disableJdkUnsafe()} for the unexpected side-effects this might have *
* *

{@code Gson} instances might cache the adapter they create for a {@code @JsonAdapter} * annotation. It is not guaranteed that a new adapter is created every time the annotated class or * field is serialized or deserialized. * * @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(); /** * Whether the adapter referenced by {@link #value()} should be made {@linkplain * TypeAdapter#nullSafe() null-safe}. * *

If {@code true} (the default), it will be made null-safe and Gson will handle {@code null} * Java objects on serialization and JSON {@code null} on deserialization without calling the * adapter. If {@code false}, the adapter will have to handle the {@code null} values. */ boolean nullSafe() default true; } ================================================ FILE: gson/src/main/java/com/google/gson/annotations/SerializedName.java ================================================ /* * 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. * *

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. * *

Here is an example of how this annotation is meant to be used: * *

 * public class MyClass {
 *   @SerializedName("name") String a;
 *   @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;
 *   }
 * }
 * 
* *

The following shows the output that is generated when serializing an instance of the above * example class: * *

 * 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"}
 * 
* *

NOTE: The value you specify in this annotation must be a valid JSON field name. While * deserializing, all values specified in the annotation will be deserialized into the field. For * example: * *

 *   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);
 * 
* * 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 { /** * The desired name of the field when it is serialized or deserialized. * * @return the desired name of the field when it is serialized or deserialized */ String value(); /** * The alternative names of the field when it is deserialized * * @return the alternative names of the field when it is deserialized */ String[] alternate() default {}; } ================================================ FILE: gson/src/main/java/com/google/gson/annotations/Since.java ================================================ /* * 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 com.google.gson.GsonBuilder; 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. * *

This annotation has no effect unless you build {@link com.google.gson.Gson} with a {@code * GsonBuilder} and invoke the {@link GsonBuilder#setVersion(double)} method. * *

Here is an example of how this annotation is meant to be used: * *

 * public class User {
 *   private String firstName;
 *   private String lastName;
 *   @Since(1.0) private String emailAddress;
 *   @Since(1.0) private String password;
 *   @Since(1.1) private Address address;
 * }
 * 
* *

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}. * * @author Inderjeet Singh * @author Joel Leitch * @see GsonBuilder#setVersion(double) * @see Until */ @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. The number is * inclusive; annotated elements will be included if {@code gsonVersion >= value}. */ double value(); } ================================================ FILE: gson/src/main/java/com/google/gson/annotations/Until.java ================================================ /* * 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 com.google.gson.GsonBuilder; 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 is equal to or 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. * *

This annotation has no effect unless you build {@link com.google.gson.Gson} with a {@code * GsonBuilder} and invoke the {@link GsonBuilder#setVersion(double)} method. * *

Here is an example of how this annotation is meant to be used: * *

 * public class User {
 *   private String firstName;
 *   private String lastName;
 *   @Until(1.1) private String emailAddress;
 *   @Until(1.1) private String password;
 * }
 * 
* *

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 * @see GsonBuilder#setVersion(double) * @see Since * @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 included. The number * is exclusive; annotated elements will be included if {@code gsonVersion < value}. */ double value(); } ================================================ FILE: gson/src/main/java/com/google/gson/annotations/package-info.java ================================================ /* * 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. */ /** * This package provides annotations that can be used with {@link com.google.gson.Gson}. * * @author Inderjeet Singh, Joel Leitch */ @com.google.errorprone.annotations.CheckReturnValue package com.google.gson.annotations; ================================================ FILE: gson/src/main/java/com/google/gson/internal/ConstructorConstructor.java ================================================ /* * 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.TreeMap; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListMap; /** Returns a function that can construct an instance of a requested type. */ public final class ConstructorConstructor { private final Map> instanceCreators; private final boolean useJdkUnsafe; private final List reflectionFilters; public ConstructorConstructor( Map> instanceCreators, boolean useJdkUnsafe, List reflectionFilters) { this.instanceCreators = instanceCreators; this.useJdkUnsafe = useJdkUnsafe; this.reflectionFilters = reflectionFilters; } /** * 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)) { // R8 performs aggressive optimizations where it removes the default constructor of a class // and makes the class `abstract`; check for that here explicitly /* * Note: Ideally should only show this R8-specific message when it is clear that R8 was * used (e.g. when `c.getDeclaredConstructors().length == 0`), but on Android where this * issue with R8 occurs most, R8 seems to keep some constructors for some reason while * still making the class abstract */ return "Abstract classes can't be instantiated! Adjust the R8 configuration or register" + " an InstanceCreator or a TypeAdapter for this type. Class name: " + c.getName() + "\nSee " + TroubleshootingGuide.createUrl("r8-abstract-class"); } return null; } /** Calls {@link #get(TypeToken, boolean)}, and allows usage of JDK Unsafe. */ public ObjectConstructor get(TypeToken typeToken) { return get(typeToken, true); } /** * Retrieves an object constructor for the given type. * * @param typeToken type for which a constructor should be retrieved * @param allowUnsafe whether to allow usage of JDK Unsafe; has no effect if {@link #useJdkUnsafe} * is false */ public ObjectConstructor get(TypeToken typeToken, boolean allowUnsafe) { Type type = typeToken.getType(); Class rawType = typeToken.getRawType(); // first try an instance creator @SuppressWarnings("unchecked") // types must agree InstanceCreator typeCreator = (InstanceCreator) instanceCreators.get(type); if (typeCreator != null) { return new InstanceCreatorConstructor<>(typeCreator, type); } // Next try raw type match for instance creators @SuppressWarnings("unchecked") // types must agree InstanceCreator rawTypeCreator = (InstanceCreator) instanceCreators.get(rawType); if (rawTypeCreator != null) { return new InstanceCreatorConstructor<>(rawTypeCreator, 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 specialConstructor = newSpecialCollectionConstructor(type, rawType); if (specialConstructor != null) { return specialConstructor; } FilterResult filterResult = ReflectionAccessFilterHelper.getFilterResult(reflectionFilters, rawType); ObjectConstructor defaultConstructor = newDefaultConstructor(rawType, filterResult); if (defaultConstructor != null) { return defaultConstructor; } ObjectConstructor 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 String exceptionMessage = checkInstantiable(rawType); if (exceptionMessage != null) { return new ThrowingObjectConstructor<>(exceptionMessage); } if (!allowUnsafe) { String message = "Unable to create instance of " + rawType + "; Register an InstanceCreator or a TypeAdapter for this type."; return new ThrowingObjectConstructor<>(message); } // 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) { 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 ThrowingObjectConstructor<>(message); } // finally try unsafe return newUnsafeAllocator(rawType); } /** * Creates constructors for special JDK collection types which do not have a public no-args * constructor. */ private static ObjectConstructor newSpecialCollectionConstructor( Type type, Class rawType) { if (EnumSet.class.isAssignableFrom(rawType)) { return () -> { 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); } } else { throw new JsonIOException("Invalid EnumSet type: " + type); } }; } // 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 () -> { 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); } } else { throw new JsonIOException("Invalid EnumMap type: " + type); } }; } return null; } private static ObjectConstructor newDefaultConstructor( Class rawType, FilterResult filterResult) { // Cannot invoke constructor of abstract class if (Modifier.isAbstract(rawType.getModifiers())) { return null; } Constructor 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) { 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 ThrowingObjectConstructor<>(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) { String exceptionMessage = ReflectionHelper.tryMakeAccessible(constructor); if (exceptionMessage != null) { return new ThrowingObjectConstructor<>(exceptionMessage); } } return () -> { try { @SuppressWarnings("unchecked") // T is the same raw type as is requested T newInstance = (T) constructor.newInstance(); return newInstance; } // Note: InstantiationException should be impossible because check at start of method made // sure that class is not abstract catch (InstantiationException e) { throw new RuntimeException( "Failed to invoke constructor '" + ReflectionHelper.constructorToString(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 '" + ReflectionHelper.constructorToString(constructor) + "' with no args", e.getCause()); } catch (IllegalAccessException e) { throw ReflectionHelper.createExceptionForUnexpectedIllegalAccess(e); } }; } /** Constructors for common interface types like Map and List and their subtypes. */ private static ObjectConstructor newDefaultImplementationConstructor( Type type, Class 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)) { @SuppressWarnings("unchecked") ObjectConstructor constructor = (ObjectConstructor) newCollectionConstructor(rawType); return constructor; } if (Map.class.isAssignableFrom(rawType)) { @SuppressWarnings("unchecked") ObjectConstructor constructor = (ObjectConstructor) newMapConstructor(type, rawType); return constructor; } // Unsupported type; try other means of creating constructor return null; } private static ObjectConstructor> newCollectionConstructor( Class rawType) { // First try List implementation if (rawType.isAssignableFrom(ArrayList.class)) { return ArrayList::new; } // Then try Set implementation else if (rawType.isAssignableFrom(LinkedHashSet.class)) { return LinkedHashSet::new; } // Then try SortedSet / NavigableSet implementation else if (rawType.isAssignableFrom(TreeSet.class)) { return TreeSet::new; } // Then try Queue implementation else if (rawType.isAssignableFrom(ArrayDeque.class)) { return ArrayDeque::new; } // Was unable to create matching Collection constructor return null; } private static boolean hasStringKeyType(Type mapType) { // If mapType is not parameterized, assume it might have String as key type if (!(mapType instanceof ParameterizedType)) { return true; } Type[] typeArguments = ((ParameterizedType) mapType).getActualTypeArguments(); if (typeArguments.length == 0) { return false; } return GsonTypes.getRawType(typeArguments[0]) == String.class; } private static ObjectConstructor> newMapConstructor( Type type, Class rawType) { // First try Map implementation /* * Legacy special casing for Map to avoid DoS from colliding String hashCode * values for older JDKs; use own LinkedTreeMap instead */ if (rawType.isAssignableFrom(LinkedTreeMap.class) && hasStringKeyType(type)) { // Must use lambda instead of method reference (`LinkedTreeMap::new`) here, otherwise this // causes an exception when Gson is used by a custom system class loader, see // https://github.com/google/gson/pull/2864#issuecomment-3528623716 return () -> new LinkedTreeMap<>(); } else if (rawType.isAssignableFrom(LinkedHashMap.class)) { return LinkedHashMap::new; } // Then try SortedMap / NavigableMap implementation else if (rawType.isAssignableFrom(TreeMap.class)) { return TreeMap::new; } // Then try ConcurrentMap implementation else if (rawType.isAssignableFrom(ConcurrentHashMap.class)) { return ConcurrentHashMap::new; } // Then try ConcurrentNavigableMap implementation else if (rawType.isAssignableFrom(ConcurrentSkipListMap.class)) { return ConcurrentSkipListMap::new; } // Was unable to create matching Map constructor return null; } private ObjectConstructor newUnsafeAllocator(Class rawType) { if (useJdkUnsafe) { return () -> { try { @SuppressWarnings("unchecked") T newInstance = (T) UnsafeAllocator.INSTANCE.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 { 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."; // Check if R8 removed all constructors if (rawType.getDeclaredConstructors().length == 0) { // R8 with Unsafe disabled might not be common enough to warrant a separate Troubleshooting // Guide entry exceptionMessage += " Or adjust your R8 configuration to keep the no-args constructor of the class."; } return new ThrowingObjectConstructor<>(exceptionMessage); } } @Override public String toString() { return instanceCreators.toString(); } /** * {@link ObjectConstructor} which always throws an exception. * *

This keeps backward compatibility, compared to using a {@code null} {@code * ObjectConstructor}, which would then choose another way of creating the object. And it supports * types which are only serialized but not deserialized (compared to directly throwing an * exception when the {@code ObjectConstructor} is requested), e.g. when the runtime type of an * object is inaccessible, but the compile-time type is accessible. */ private static final class ThrowingObjectConstructor implements ObjectConstructor { private final String exceptionMessage; ThrowingObjectConstructor(String exceptionMessage) { this.exceptionMessage = exceptionMessage; } @Override public T construct() { // New exception is created every time to avoid keeping a reference to an exception with // potentially long stack trace, causing a memory leak // (which would happen if the exception was already created when the // `ThrowingObjectConstructor` is created) throw new JsonIOException(exceptionMessage); } } private static final class InstanceCreatorConstructor implements ObjectConstructor { private final InstanceCreator instanceCreator; private final Type type; InstanceCreatorConstructor(InstanceCreator instanceCreator, Type type) { this.instanceCreator = instanceCreator; this.type = type; } @Override public T construct() { return instanceCreator.createInstance(type); } } } ================================================ FILE: gson/src/main/java/com/google/gson/internal/Excluder.java ================================================ /* * 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.internal.reflect.ReflectionHelper; 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. * *

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 serializationStrategies = Collections.emptyList(); private List 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 TypeAdapter create(Gson gson, TypeToken type) { Class rawType = type.getRawType(); boolean skipSerialize = excludeClass(rawType, true); boolean skipDeserialize = excludeClass(rawType, false); if (!skipSerialize && !skipDeserialize) { return null; } return new TypeAdapter() { /** * The delegate is lazily created because it may not be needed, and creating it may fail. * Field has to be {@code volatile} because {@link Gson} guarantees to be thread-safe. */ private volatile TypeAdapter 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 delegate() { // A race might lead to `delegate` being assigned by multiple threads but the last // assignment will stick TypeAdapter d = delegate; if (d == null) { d = delegate = gson.getDelegateAdapter(Excluder.this, type); } return d; } }; } 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 (excludeClass(field.getType(), serialize)) { return true; } List list = serialize ? serializationStrategies : deserializationStrategies; if (!list.isEmpty()) { FieldAttributes fieldAttributes = new FieldAttributes(field); for (ExclusionStrategy exclusionStrategy : list) { if (exclusionStrategy.shouldSkipField(fieldAttributes)) { return true; } } } return false; } // public for unit tests; can otherwise be private public boolean excludeClass(Class clazz, boolean serialize) { if (version != Excluder.IGNORE_VERSIONS && !isValidVersion(clazz.getAnnotation(Since.class), clazz.getAnnotation(Until.class))) { return true; } if (!serializeInnerClasses && isInnerClass(clazz)) { return true; } /* * Exclude anonymous and local classes because they can have synthetic fields capturing enclosing * values which makes serialization and deserialization unreliable. * Don't exclude anonymous enum subclasses because enum types have a built-in adapter. * * Exclude only for deserialization; for serialization allow because custom adapter might be * used; if no custom adapter exists reflection-based adapter otherwise excludes value. * * Cannot allow deserialization reliably here because some custom adapters like Collection adapter * fall back to creating instances using Unsafe, which would likely lead to runtime exceptions * for anonymous and local classes if they capture values. */ if (!serialize && !Enum.class.isAssignableFrom(clazz) && ReflectionHelper.isAnonymousOrNonStaticLocal(clazz)) { return true; } List list = serialize ? serializationStrategies : deserializationStrategies; for (ExclusionStrategy exclusionStrategy : list) { if (exclusionStrategy.shouldSkipClass(clazz)) { return true; } } return false; } private static boolean isInnerClass(Class clazz) { return clazz.isMemberClass() && !ReflectionHelper.isStatic(clazz); } private boolean isValidVersion(Since since, Until until) { return isValidSince(since) && isValidUntil(until); } private boolean isValidSince(Since annotation) { if (annotation != null) { double annotationVersion = annotation.value(); return version >= annotationVersion; } return true; } private boolean isValidUntil(Until annotation) { if (annotation != null) { double annotationVersion = annotation.value(); return version < annotationVersion; } return true; } } ================================================ FILE: gson/src/main/java/com/google/gson/internal/GsonTypes.java ================================================ /* * 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 static java.util.Objects.requireNonNull; 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.Objects; import java.util.Properties; /** * Static methods for working with types. * * @author Bob Lee * @author Jesse Wilson */ public final class GsonTypes { static final Type[] EMPTY_TYPE_ARRAY = new Type[] {}; private GsonTypes() { 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, Class 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(), (Class) 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; // getRawType() returns Type instead of Class; that seems to be an API mistake, // see https://bugs.openjdk.org/browse/JDK-8250659 Type rawType = parameterizedType.getRawType(); 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 Objects.equals(a, 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 Objects.equals(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} and the * result when the supertype is {@code Collection.class} is {@code Collection}. */ 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}, this returns {@code Iterable} 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]; } if (!supertype.isAssignableFrom(contextRawType)) { throw new IllegalArgumentException( contextRawType + " is not the same as or a subtype of " + supertype); } return resolve( context, contextRawType, GsonTypes.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, but it's declared to * extend Hashtable. */ if (Properties.class.isAssignableFrom(contextRawType)) { return new Type[] {String.class, String.class}; } 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, Type>()); } private static Type resolve( Type context, Class contextRawType, Type toResolve, Map, 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 ownerChanged = !equal(newOwnerType, ownerType); Type[] args = original.getActualTypeArguments(); boolean argsChanged = false; for (int t = 0, length = args.length; t < length; t++) { Type resolvedTypeArgument = resolve(context, contextRawType, args[t], visitedTypeVariables); if (!equal(resolvedTypeArgument, args[t])) { if (!argsChanged) { args = args.clone(); argsChanged = true; } args[t] = resolvedTypeArgument; } } toResolve = ownerChanged || argsChanged ? newParameterizedTypeWithOwner( newOwnerType, (Class) 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) { if (type instanceof Class && ((Class) type).isPrimitive()) { throw new IllegalArgumentException("Primitive type is not allowed"); } } /** * Whether an {@linkplain ParameterizedType#getOwnerType() owner type} must be specified when * constructing a {@link ParameterizedType} for {@code rawType}. * *

Note that this method might not require an owner type for all cases where Java reflection * would create parameterized types with owner type. */ public static boolean requiresOwnerType(Type rawType) { if (rawType instanceof Class) { Class rawTypeAsClass = (Class) rawType; return !Modifier.isStatic(rawTypeAsClass.getModifiers()) && rawTypeAsClass.getDeclaringClass() != null; } return false; } // Here and below we put @SuppressWarnings("serial") on fields of type `Type`. Recent Java // compilers complain that the declared type is not Serializable. But in this context we go out of // our way to ensure that the Type in question is either Class (which is serializable) or one of // the nested Type implementations here (which are also serializable). private static final class ParameterizedTypeImpl implements ParameterizedType, Serializable { @SuppressWarnings("serial") private final Type ownerType; @SuppressWarnings("serial") private final Type rawType; @SuppressWarnings("serial") private final Type[] typeArguments; ParameterizedTypeImpl(Type ownerType, Class rawType, Type... typeArguments) { requireNonNull(rawType); if (ownerType == null && requiresOwnerType(rawType)) { throw new IllegalArgumentException("Must specify owner type for " + rawType); } 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++) { requireNonNull(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 && GsonTypes.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 { @SuppressWarnings("serial") private final Type componentType; GenericArrayTypeImpl(Type componentType) { requireNonNull(componentType); this.componentType = canonicalize(componentType); } @Override public Type getGenericComponentType() { return componentType; } @Override public boolean equals(Object o) { return o instanceof GenericArrayType && GsonTypes.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 { @SuppressWarnings("serial") private final Type upperBound; @SuppressWarnings("serial") private final Type lowerBound; WildcardTypeImpl(Type[] upperBounds, Type[] lowerBounds) { if (lowerBounds.length > 1) { throw new IllegalArgumentException("At most one lower bound is supported"); } if (upperBounds.length != 1) { throw new IllegalArgumentException("Exactly one upper bound must be specified"); } if (lowerBounds.length == 1) { requireNonNull(lowerBounds[0]); checkNotPrimitive(lowerBounds[0]); if (upperBounds[0] != Object.class) { throw new IllegalArgumentException( "When lower bound is specified, upper bound must be Object"); } this.lowerBound = canonicalize(lowerBounds[0]); this.upperBound = Object.class; } else { requireNonNull(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 && GsonTypes.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; } } ================================================ FILE: gson/src/main/java/com/google/gson/internal/JavaVersion.java ================================================ /* * 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 parseMajorJavaVersion(javaVersion); } // Visible for testing only static int parseMajorJavaVersion(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("[._]", 3); 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; } } /** * Gets the major Java version * * @return the major Java version, i.e. '8' for Java 1.8, '9' for Java 9 etc. */ public static int getMajorJavaVersion() { return majorJavaVersion; } /** * Gets a boolean value depending if the application is running on Java 9 or later * * @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() {} } ================================================ FILE: gson/src/main/java/com/google/gson/internal/JsonReaderInternalAccess.java ================================================ /* * 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 { // Suppress warnings because field is initialized by `JsonReader` class during class loading // (and therefore should be thread-safe), and any usage appears after `JsonReader` was loaded @SuppressWarnings({"ConstantField", "NonFinalStaticField"}) public static volatile JsonReaderInternalAccess INSTANCE; /** Changes the type of the current property name token to a string value. */ public abstract void promoteNameToValue(JsonReader reader) throws IOException; } ================================================ FILE: gson/src/main/java/com/google/gson/internal/LazilyParsedNumber.java ================================================ /* * 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 */ @SuppressWarnings("serial") // ignore warning about missing serialVersionUID public final class LazilyParsedNumber extends Number { private final String value; /** * @param value must not be null */ public LazilyParsedNumber(String value) { this.value = value; } private BigDecimal asBigDecimal() { return NumberLimits.parseBigDecimal(value); } @Override public int intValue() { try { return Integer.parseInt(value); } catch (NumberFormatException e) { try { return (int) Long.parseLong(value); } catch (NumberFormatException nfe) { return asBigDecimal().intValue(); } } } @Override public long longValue() { try { return Long.parseLong(value); } catch (NumberFormatException e) { return asBigDecimal().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 asBigDecimal(); } 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.equals(other.value); } return false; } } ================================================ FILE: gson/src/main/java/com/google/gson/internal/LinkedTreeMap.java ================================================ /* * 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 com.google.errorprone.annotations.CanIgnoreReturnValue; 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.Objects; 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. * *

This implementation was derived from Android 4.1's TreeMap class. */ @SuppressWarnings("serial") // ignore warning about missing serialVersionUID public final class LinkedTreeMap extends AbstractMap implements Serializable { @SuppressWarnings({"unchecked", "rawtypes"}) // to avoid Comparable>> private static final Comparator NATURAL_ORDER = new Comparator() { @Override public int compare(Comparable a, Comparable b) { return a.compareTo(b); } }; private final Comparator comparator; private final boolean allowNullValues; Node root; int size = 0; int modCount = 0; // Used to preserve iteration order final Node header; /** * Create a natural order, empty tree map whose keys must be mutually comparable and non-null, and * whose values can be {@code null}. */ @SuppressWarnings("unchecked") // unsafe! this assumes K is comparable public LinkedTreeMap() { this((Comparator) NATURAL_ORDER, true); } /** * Create a natural order, empty tree map whose keys must be mutually comparable and non-null. * * @param allowNullValues whether {@code null} is allowed as entry value */ @SuppressWarnings("unchecked") // unsafe! this assumes K is comparable public LinkedTreeMap(boolean allowNullValues) { this((Comparator) NATURAL_ORDER, allowNullValues); } /** * 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. * @param allowNullValues whether {@code null} is allowed as entry value */ // unsafe! if comparator is null, this assumes K is comparable @SuppressWarnings({"unchecked", "rawtypes"}) public LinkedTreeMap(Comparator comparator, boolean allowNullValues) { this.comparator = comparator != null ? comparator : (Comparator) NATURAL_ORDER; this.allowNullValues = allowNullValues; this.header = new Node<>(allowNullValues); } @Override public int size() { return size; } @Override public V get(Object key) { Node node = findByObject(key); return node != null ? node.value : null; } @Override public boolean containsKey(Object key) { return findByObject(key) != null; } @CanIgnoreReturnValue @Override public V put(K key, V value) { if (key == null) { throw new NullPointerException("key == null"); } if (value == null && !allowNullValues) { throw new NullPointerException("value == null"); } Node 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 header = this.header; header.next = header.prev = header; } @Override public V remove(Object key) { Node 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 find(K key, boolean create) { Comparator comparator = this.comparator; Node 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 comparableKey = (comparator == NATURAL_ORDER) ? (Comparable) 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 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 header = this.header; Node 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<>(allowNullValues, nearest, key, header, header.prev); root = created; } else { created = new Node<>(allowNullValues, 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 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. * *

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 findByEntry(Entry entry) { Node mine = findByObject(entry.getKey()); boolean valuesEqual = mine != null && equal(mine.value, entry.getValue()); return valuesEqual ? mine : null; } private static boolean equal(Object a, Object b) { return Objects.equals(a, 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 node, boolean unlink) { if (unlink) { node.prev.next = node.next; node.next.prev = node.prev; } Node left = node.left; Node right = node.right; Node 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 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 removeInternalByKey(Object key) { Node node = findByObject(key); if (node != null) { removeInternal(node, true); } return node; } @SuppressWarnings("ReferenceEquality") private void replaceInParent(Node node, Node replacement) { Node 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 unbalanced, boolean insert) { for (Node node = unbalanced; node != null; node = node.parent) { Node left = node.left; Node 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 rightLeft = right.left; Node 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 leftLeft = left.left; Node 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 root) { Node left = root.left; Node pivot = root.right; Node pivotLeft = pivot.left; Node 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 root) { Node pivot = root.left; Node right = root.right; Node pivotLeft = pivot.left; Node 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> entrySet() { EntrySet result = entrySet; if (result == null) { result = entrySet = new EntrySet(); } return result; } @Override public Set keySet() { KeySet result = keySet; if (result == null) { result = keySet = new KeySet(); } return result; } static final class Node implements Entry { Node parent; Node left; Node right; Node next; Node prev; final K key; final boolean allowNullValue; V value; int height; /** Create the header entry */ Node(boolean allowNullValue) { key = null; this.allowNullValue = allowNullValue; next = prev = this; } /** Create a regular entry */ Node(boolean allowNullValue, Node parent, K key, Node next, Node prev) { this.parent = parent; this.key = key; this.allowNullValue = allowNullValue; 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) { if (value == null && !allowNullValue) { throw new NullPointerException("value == null"); } V oldValue = this.value; this.value = value; return oldValue; } @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 first() { Node node = this; Node child = node.left; while (child != null) { node = child; child = node.left; } return node; } /** Returns the last node in this subtree. */ public Node last() { Node node = this; Node child = node.right; while (child != null) { node = child; child = node.right; } return node; } } private abstract class LinkedTreeMapIterator implements Iterator { Node next = header.next; Node lastReturned = null; int expectedModCount = modCount; LinkedTreeMapIterator() {} @Override @SuppressWarnings("ReferenceEquality") public final boolean hasNext() { return next != header; } @SuppressWarnings("ReferenceEquality") final Node nextNode() { Node e = next; if (e == header) { throw new NoSuchElementException(); } if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } next = e.next; lastReturned = e; return e; } @Override public final void remove() { if (lastReturned == null) { throw new IllegalStateException(); } removeInternal(lastReturned, true); lastReturned = null; expectedModCount = modCount; } } class EntrySet extends AbstractSet> { @Override public int size() { return size; } @Override public Iterator> iterator() { return new LinkedTreeMapIterator>() { @Override public Entry 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 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 { @Override public int size() { return size; } @Override public Iterator iterator() { return new LinkedTreeMapIterator() { @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"); } } ================================================ FILE: gson/src/main/java/com/google/gson/internal/NonNullElementWrapperList.java ================================================ /* * Copyright (C) 2018 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.util.AbstractList; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.RandomAccess; /** * {@link List} which wraps another {@code List} but prevents insertion of {@code null} elements. * Methods which only perform checks with the element argument (e.g. {@link #contains(Object)}) do * not throw exceptions for {@code null} arguments. */ public class NonNullElementWrapperList extends AbstractList implements RandomAccess { // Explicitly specify ArrayList as type to guarantee that delegate implements RandomAccess private final ArrayList delegate; @SuppressWarnings("NonApiType") public NonNullElementWrapperList(ArrayList delegate) { this.delegate = Objects.requireNonNull(delegate); } @Override public E get(int index) { return delegate.get(index); } @Override public int size() { return delegate.size(); } private E nonNull(E element) { if (element == null) { throw new NullPointerException("Element must be non-null"); } return element; } @Override public E set(int index, E element) { return delegate.set(index, nonNull(element)); } @Override public void add(int index, E element) { delegate.add(index, nonNull(element)); } @Override public E remove(int index) { return delegate.remove(index); } /* The following methods are overridden because their default implementation is inefficient */ @Override public void clear() { delegate.clear(); } @SuppressWarnings("UngroupedOverloads") // this is intentionally ungrouped, see comment above @Override public boolean remove(Object o) { return delegate.remove(o); } @Override public boolean removeAll(Collection c) { return delegate.removeAll(c); } @Override public boolean retainAll(Collection c) { return delegate.retainAll(c); } @Override public boolean contains(Object o) { return delegate.contains(o); } @Override public int indexOf(Object o) { return delegate.indexOf(o); } @Override public int lastIndexOf(Object o) { return delegate.lastIndexOf(o); } @Override public Object[] toArray() { return delegate.toArray(); } @Override public T[] toArray(T[] a) { return delegate.toArray(a); } @Override public boolean equals(Object o) { return delegate.equals(o); } @Override public int hashCode() { return delegate.hashCode(); } // Maybe also delegate List#sort and List#spliterator in the future, but that // requires Android API level 24 } ================================================ FILE: gson/src/main/java/com/google/gson/internal/NumberLimits.java ================================================ package com.google.gson.internal; import java.math.BigDecimal; import java.math.BigInteger; /** * This class enforces limits on numbers parsed from JSON to avoid potential performance problems * when extremely large numbers are used. */ public class NumberLimits { private NumberLimits() {} private static final int MAX_NUMBER_STRING_LENGTH = 10_000; private static void checkNumberStringLength(String s) { if (s.length() > MAX_NUMBER_STRING_LENGTH) { throw new NumberFormatException("Number string too large: " + s.substring(0, 30) + "..."); } } public static BigDecimal parseBigDecimal(String s) throws NumberFormatException { checkNumberStringLength(s); BigDecimal decimal = new BigDecimal(s); // Cast to long to avoid issues with abs when value is Integer.MIN_VALUE if (Math.abs((long) decimal.scale()) >= 10_000) { throw new NumberFormatException("Number has unsupported scale: " + s); } return decimal; } public static BigInteger parseBigInteger(String s) throws NumberFormatException { checkNumberStringLength(s); return new BigInteger(s); } } ================================================ FILE: gson/src/main/java/com/google/gson/internal/ObjectConstructor.java ================================================ /* * 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 { /** Returns a new instance. */ T construct(); } ================================================ FILE: gson/src/main/java/com/google/gson/internal/PreJava9DateFormatProvider.java ================================================ /* * 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 { private PreJava9DateFormatProvider() {} /** * 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 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); } } } ================================================ FILE: gson/src/main/java/com/google/gson/internal/Primitives.java ================================================ /* * 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. * *

   *     wrap(int.class) == Integer.class
   *     wrap(Integer.class) == Integer.class
   *     wrap(String.class) == String.class
   * 
*/ @SuppressWarnings({"unchecked", "MissingBraces"}) public static Class wrap(Class type) { if (type == int.class) return (Class) Integer.class; if (type == float.class) return (Class) Float.class; if (type == byte.class) return (Class) Byte.class; if (type == double.class) return (Class) Double.class; if (type == long.class) return (Class) Long.class; if (type == char.class) return (Class) Character.class; if (type == boolean.class) return (Class) Boolean.class; if (type == short.class) return (Class) Short.class; if (type == void.class) return (Class) Void.class; return type; } /** * Returns the corresponding primitive type of {@code type} if it is a wrapper type; otherwise * returns {@code type} itself. Idempotent. * *
   *     unwrap(Integer.class) == int.class
   *     unwrap(int.class) == int.class
   *     unwrap(String.class) == String.class
   * 
*/ @SuppressWarnings({"unchecked", "MissingBraces"}) public static Class unwrap(Class type) { if (type == Integer.class) return (Class) int.class; if (type == Float.class) return (Class) float.class; if (type == Byte.class) return (Class) byte.class; if (type == Double.class) return (Class) double.class; if (type == Long.class) return (Class) long.class; if (type == Character.class) return (Class) char.class; if (type == Boolean.class) return (Class) boolean.class; if (type == Short.class) return (Class) short.class; if (type == Void.class) return (Class) void.class; return type; } } ================================================ FILE: gson/src/main/java/com/google/gson/internal/ReflectionAccessFilterHelper.java ================================================ /* * Copyright (C) 2022 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.ReflectionAccessFilter; import com.google.gson.ReflectionAccessFilter.FilterResult; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Method; import java.util.List; /** 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 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 abstract static class AccessChecker { static final AccessChecker INSTANCE; static { AccessChecker accessChecker = null; // TODO: Ideally should use Multi-Release JAR for this version specific code if (JavaVersion.isJava9OrLater()) { try { 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) { // OK: will assume everything is accessible } } 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; } abstract boolean canAccess(AccessibleObject accessibleObject, Object object); } } ================================================ FILE: gson/src/main/java/com/google/gson/internal/Streams.java ================================================ /* * 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.JsonElementTypeAdapter; 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.Closeable; import java.io.EOFException; import java.io.Flushable; import java.io.IOException; import java.io.Writer; import java.util.Objects; /** 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 { JsonToken unused = reader.peek(); isEmpty = false; return JsonElementTypeAdapter.ADAPTER.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 { JsonElementTypeAdapter.ADAPTER.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; } @SuppressWarnings("UngroupedOverloads") // this is intentionally ungrouped, see comment below @Override public void write(char[] chars, int offset, int length) throws IOException { currentWrite.setChars(chars); appendable.append(currentWrite, offset, offset + length); } @Override public void flush() throws IOException { if (appendable instanceof Flushable) { ((Flushable) appendable).flush(); } } @Override public void close() throws IOException { if (appendable instanceof Closeable) { ((Closeable) appendable).close(); } } // Override these methods for better performance // They would otherwise unnecessarily create Strings or char arrays @Override public void write(int i) throws IOException { appendable.append((char) i); } @Override public void write(String str, int off, int len) throws IOException { // Appendable.append turns null -> "null", which is not desired here Objects.requireNonNull(str); appendable.append(str, off, off + len); } @Override public Writer append(CharSequence csq) throws IOException { appendable.append(csq); return this; } @Override public Writer append(CharSequence csq, int start, int end) throws IOException { appendable.append(csq, start, end); return this; } /** A mutable char sequence pointing at a single char[]. */ private static class CurrentWrite implements CharSequence { private char[] chars; private String cachedString; void setChars(char[] chars) { this.chars = chars; this.cachedString = null; } @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); } // Must return string representation to satisfy toString() contract @Override public String toString() { if (cachedString == null) { cachedString = new String(chars); } return cachedString; } } } } ================================================ FILE: gson/src/main/java/com/google/gson/internal/TroubleshootingGuide.java ================================================ package com.google.gson.internal; public class TroubleshootingGuide { private TroubleshootingGuide() {} /** Creates a URL referring to the specified troubleshooting section. */ public static String createUrl(String id) { return "https://github.com/google/gson/blob/main/Troubleshooting.md#" + id; } } ================================================ FILE: gson/src/main/java/com/google/gson/internal/UnsafeAllocator.java ================================================ /* * 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; /** * Do sneaky things to allocate objects without invoking their constructors. * * @author Joel Leitch * @author Jesse Wilson */ public abstract class UnsafeAllocator { public abstract T newInstance(Class c) throws Exception; /** * 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 = ConstructorConstructor.checkInstantiable(c); if (exceptionMessage != null) { throw new AssertionError( "UnsafeAllocator is used for non-instantiable type: " + exceptionMessage); } } public static final UnsafeAllocator INSTANCE = create(); private 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); Object unsafe = f.get(null); Method allocateInstance = unsafeClass.getMethod("allocateInstance", Class.class); return new UnsafeAllocator() { @Override @SuppressWarnings("unchecked") public T newInstance(Class c) throws Exception { assertInstantiable(c); return (T) allocateInstance.invoke(unsafe, c); } }; } catch (Exception ignored) { // OK: try the next way } // 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); int constructorId = (Integer) getConstructorId.invoke(null, Object.class); Method newInstance = ObjectStreamClass.class.getDeclaredMethod("newInstance", Class.class, int.class); newInstance.setAccessible(true); return new UnsafeAllocator() { @Override @SuppressWarnings("unchecked") public T newInstance(Class c) throws Exception { assertInstantiable(c); return (T) newInstance.invoke(null, c, constructorId); } }; } catch (Exception ignored) { // OK: try the next way } // try dalvikvm, pre-gingerbread // public class ObjectInputStream { // private static native Object newInstance( // Class instantiationClass, Class constructorClass); // } try { Method newInstance = ObjectInputStream.class.getDeclaredMethod("newInstance", Class.class, Class.class); newInstance.setAccessible(true); return new UnsafeAllocator() { @Override @SuppressWarnings("unchecked") public T newInstance(Class c) throws Exception { assertInstantiable(c); return (T) newInstance.invoke(null, c, Object.class); } }; } catch (Exception ignored) { // OK: try the next way } // give up return new UnsafeAllocator() { @Override public T newInstance(Class 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."); } }; } } ================================================ FILE: gson/src/main/java/com/google/gson/internal/bind/ArrayTypeAdapter.java ================================================ /* * 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.GsonTypes; 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.Array; import java.lang.reflect.GenericArrayType; import java.lang.reflect.Type; import java.util.ArrayList; /** Adapter for arrays. */ public final class ArrayTypeAdapter extends TypeAdapter { public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() { @Override public TypeAdapter create(Gson gson, TypeToken typeToken) { Type type = typeToken.getType(); if (!(type instanceof GenericArrayType || (type instanceof Class && ((Class) type).isArray()))) { return null; } Type componentType = GsonTypes.getArrayComponentType(type); TypeAdapter componentTypeAdapter = gson.getAdapter(TypeToken.get(componentType)); @SuppressWarnings({"unchecked", "rawtypes"}) TypeAdapter arrayAdapter = new ArrayTypeAdapter(gson, componentTypeAdapter, GsonTypes.getRawType(componentType)); return arrayAdapter; } }; private final Class componentType; private final TypeAdapter componentTypeAdapter; public ArrayTypeAdapter( Gson context, TypeAdapter componentTypeAdapter, Class 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; } ArrayList list = new ArrayList<>(); in.beginArray(); while (in.hasNext()) { E instance = componentTypeAdapter.read(in); list.add(instance); } in.endArray(); int size = list.size(); // Have to copy primitives one by one to primitive array if (componentType.isPrimitive()) { Object array = Array.newInstance(componentType, size); for (int i = 0; i < size; i++) { Array.set(array, i, list.get(i)); } return array; } // But for Object[] can use ArrayList.toArray else { @SuppressWarnings("unchecked") E[] array = (E[]) Array.newInstance(componentType, size); return list.toArray(array); } } @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++) { @SuppressWarnings("unchecked") E value = (E) Array.get(array, i); componentTypeAdapter.write(out, value); } out.endArray(); } } ================================================ FILE: gson/src/main/java/com/google/gson/internal/bind/CollectionTypeAdapterFactory.java ================================================ /* * 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.ConstructorConstructor; import com.google.gson.internal.GsonTypes; 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 TypeAdapter create(Gson gson, TypeToken typeToken) { Type type = typeToken.getType(); Class rawType = typeToken.getRawType(); if (!Collection.class.isAssignableFrom(rawType)) { return null; } Type elementType = GsonTypes.getCollectionElementType(type, rawType); TypeAdapter elementTypeAdapter = gson.getAdapter(TypeToken.get(elementType)); TypeAdapter wrappedTypeAdapter = new TypeAdapterRuntimeTypeWrapper<>(gson, elementTypeAdapter, elementType); // Don't allow Unsafe usage to create instance; instances might be in broken state and calling // Collection methods could lead to confusing exceptions boolean allowUnsafe = false; ObjectConstructor constructor = constructorConstructor.get(typeToken, allowUnsafe); @SuppressWarnings({"unchecked", "rawtypes"}) // create() doesn't define a type parameter TypeAdapter result = new Adapter(wrappedTypeAdapter, constructor); return result; } private static final class Adapter extends TypeAdapter> { private final TypeAdapter elementTypeAdapter; private final ObjectConstructor> constructor; Adapter( TypeAdapter elementTypeAdapter, ObjectConstructor> constructor) { this.elementTypeAdapter = elementTypeAdapter; this.constructor = constructor; } @Override public Collection read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } Collection 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 collection) throws IOException { if (collection == null) { out.nullValue(); return; } out.beginArray(); for (E element : collection) { elementTypeAdapter.write(out, element); } out.endArray(); } } } ================================================ FILE: gson/src/main/java/com/google/gson/internal/bind/DefaultDateTypeAdapter.java ================================================ /* * 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 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.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Objects; import java.util.TimeZone; /** * This type adapter supports subclasses of date by defining a {@link * DefaultDateTypeAdapter.DateType} and then using its {@code createAdapterFactory} methods. * *

Important: Instances of this class (or rather the {@link SimpleDateFormat} they use) * capture the current default {@link Locale} and {@link TimeZone} when they are created. Therefore * avoid storing factories obtained from {@link DateType} in {@code static} fields, since they only * create a single adapter instance and its behavior would then depend on when Gson classes are * loaded first, and which default {@code Locale} and {@code TimeZone} was used at that point. * * @author Inderjeet Singh * @author Joel Leitch */ public final class DefaultDateTypeAdapter extends TypeAdapter { private static final String SIMPLE_NAME = "DefaultDateTypeAdapter"; /** Factory for {@link Date} adapters which use {@link DateFormat#DEFAULT} as style. */ public static final TypeAdapterFactory DEFAULT_STYLE_FACTORY = // Because SimpleDateFormat captures the default TimeZone when it was created, let the factory // always create new DefaultDateTypeAdapter instances (which are then cached by the Gson // instances) instead of having a single static DefaultDateTypeAdapter instance // Otherwise the behavior would depend on when an application first loads Gson classes and // which default TimeZone is set at that point, which would be quite brittle new TypeAdapterFactory() { @SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal @Override public TypeAdapter create(Gson gson, TypeToken typeToken) { return typeToken.getRawType() == Date.class ? (TypeAdapter) new DefaultDateTypeAdapter<>( DateType.DATE, DateFormat.DEFAULT, DateFormat.DEFAULT) : null; } @Override public String toString() { return "DefaultDateTypeAdapter#DEFAULT_STYLE_FACTORY"; } }; public abstract static class DateType { public static final DateType DATE = new DateType(Date.class) { @Override protected Date deserialize(Date date) { return date; } }; private final Class dateClass; protected DateType(Class dateClass) { this.dateClass = dateClass; } protected abstract T deserialize(Date date); private TypeAdapterFactory createFactory(DefaultDateTypeAdapter adapter) { return TypeAdapters.newFactory(dateClass, adapter); } public final TypeAdapterFactory createAdapterFactory(String datePattern) { return createFactory(new DefaultDateTypeAdapter<>(this, datePattern)); } public final TypeAdapterFactory createAdapterFactory(int dateStyle, int timeStyle) { return createFactory(new DefaultDateTypeAdapter<>(this, dateStyle, timeStyle)); } } private final DateType 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 dateFormats = new ArrayList<>(); private DefaultDateTypeAdapter(DateType dateType, String datePattern) { this.dateType = Objects.requireNonNull(dateType); dateFormats.add(new SimpleDateFormat(datePattern, Locale.US)); if (!Locale.getDefault().equals(Locale.US)) { dateFormats.add(new SimpleDateFormat(datePattern)); } } private DefaultDateTypeAdapter(DateType dateType, int dateStyle, int timeStyle) { this.dateType = Objects.requireNonNull(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)); } } @Override public void write(JsonWriter out, Date value) throws IOException { if (value == null) { out.nullValue(); return; } DateFormat dateFormat = dateFormats.get(0); String dateFormatAsString; // Needs to be synchronized since JDK DateFormat classes are not thread-safe 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(); // Needs to be synchronized since JDK DateFormat classes are not thread-safe synchronized (dateFormats) { for (DateFormat dateFormat : dateFormats) { TimeZone originalTimeZone = dateFormat.getTimeZone(); try { return dateFormat.parse(s); } catch (ParseException ignored) { // OK: try the next format } finally { dateFormat.setTimeZone(originalTimeZone); } } } 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() + ')'; } } } ================================================ FILE: gson/src/main/java/com/google/gson/internal/bind/EnumTypeAdapter.java ================================================ /* * Copyright (C) 2024 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.annotations.SerializedName; 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.util.Arrays; import java.util.HashMap; import java.util.Map; /** Adapter for enum classes (but not for the base class {@code java.lang.Enum}). */ class EnumTypeAdapter> extends TypeAdapter { static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() { @Override public TypeAdapter create(Gson gson, TypeToken typeToken) { Class rawType = typeToken.getRawType(); if (!Enum.class.isAssignableFrom(rawType) || rawType == Enum.class) { return null; } if (!rawType.isEnum()) { rawType = rawType.getSuperclass(); // handle anonymous subclasses } @SuppressWarnings({"rawtypes", "unchecked"}) TypeAdapter adapter = (TypeAdapter) new EnumTypeAdapter(rawType); return adapter; } }; /** * Taken from Java 19 method {@link HashMap.newHashMap}, using default load factor {@code 0.75F}. */ private static int calculateHashMapCapacity(int numMappings) { return (int) Math.ceil(numMappings / 0.75F); } private final Map nameToConstant; private final Map stringToConstant; private final Map constantToName; private EnumTypeAdapter(Class classOfT) { try { // Uses reflection to find enum constants to work around name mismatches for obfuscated // classes Field[] fields = classOfT.getDeclaredFields(); int constantCount = 0; for (Field f : fields) { // Filter out non-constant fields, replacing elements as we go if (f.isEnumConstant()) { fields[constantCount++] = f; } } // Trim the array to the new length. Every enum type can be expected to have at least // one declared field which is not an enum constant, namely the implicit $VALUES array fields = Arrays.copyOf(fields, constantCount); int hashMapCapacity = calculateHashMapCapacity(constantCount); nameToConstant = new HashMap<>(hashMapCapacity); stringToConstant = new HashMap<>(hashMapCapacity); // Don't use `EnumMap` here; that can break when using ProGuard or R8 constantToName = new HashMap<>(hashMapCapacity); AccessibleObject.setAccessible(fields, true); for (Field constantField : fields) { @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) { // IllegalAccessException should be impossible due to the `setAccessible` call above; // and even that should probably not fail since enum constants are implicitly public 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); // Note: If none of the approaches find the constant, this returns null 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)); } } ================================================ FILE: gson/src/main/java/com/google/gson/internal/bind/IgnoreJRERequirement.java ================================================ package com.google.gson.internal.bind; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.CLASS) @Target({ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.TYPE, ElementType.FIELD}) @SuppressWarnings("IdentifierName") @interface IgnoreJRERequirement {} ================================================ FILE: gson/src/main/java/com/google/gson/internal/bind/JavaTimeTypeAdapters.java ================================================ package com.google.gson.internal.bind; import static java.lang.Math.toIntExact; 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.bind.TypeAdapters.IntegerFieldsTypeAdapter; 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.time.Duration; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.MonthDay; import java.time.OffsetDateTime; import java.time.OffsetTime; import java.time.Period; import java.time.Year; import java.time.YearMonth; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; /** * Type adapters for {@code java.time} types. * *

These adapters mimic what {@link ReflectiveTypeAdapterFactory} would produce for the same * types. That is by no means a natural encoding, given that many of the types have standard ISO * representations. If Gson had added support for the types at the same time they appeared (in Java * 8, released in 2014), it would surely have used those representations. Unfortunately, in the * intervening time, people have been using the reflective representations, and changing that would * potentially be incompatible. Meanwhile, depending on the details of private fields in JDK classes * is obviously fragile, and it also needs special {@code --add-opens} configuration with more * recent JDK versions. So here we freeze the representation that was current with JDK 21, in a way * that does not use reflection. */ @IgnoreJRERequirement // Protected by a reflective check final class JavaTimeTypeAdapters implements TypeAdapters.FactorySupplier { @Override public TypeAdapterFactory get() { return JAVA_TIME_FACTORY; } private static final TypeAdapter DURATION = new IntegerFieldsTypeAdapter("seconds", "nanos") { @Override Duration create(long[] values) { return Duration.ofSeconds(values[0], values[1]); } @Override @SuppressWarnings("JavaDurationGetSecondsGetNano") long[] integerValues(Duration duration) { return new long[] {duration.getSeconds(), duration.getNano()}; } }; private static final TypeAdapter INSTANT = new IntegerFieldsTypeAdapter("seconds", "nanos") { @Override Instant create(long[] values) { return Instant.ofEpochSecond(values[0], values[1]); } @Override @SuppressWarnings("JavaInstantGetSecondsGetNano") long[] integerValues(Instant instant) { return new long[] {instant.getEpochSecond(), instant.getNano()}; } }; private static final TypeAdapter LOCAL_DATE = new IntegerFieldsTypeAdapter("year", "month", "day") { @Override LocalDate create(long[] values) { return LocalDate.of(toIntExact(values[0]), toIntExact(values[1]), toIntExact(values[2])); } @Override long[] integerValues(LocalDate localDate) { return new long[] { localDate.getYear(), localDate.getMonthValue(), localDate.getDayOfMonth() }; } }; public static final TypeAdapter LOCAL_TIME = new IntegerFieldsTypeAdapter("hour", "minute", "second", "nano") { @Override LocalTime create(long[] values) { return LocalTime.of( toIntExact(values[0]), toIntExact(values[1]), toIntExact(values[2]), toIntExact(values[3])); } @Override long[] integerValues(LocalTime localTime) { return new long[] { localTime.getHour(), localTime.getMinute(), localTime.getSecond(), localTime.getNano() }; } }; private static TypeAdapter localDateTime(Gson gson) { TypeAdapter localDateAdapter = gson.getAdapter(LocalDate.class); TypeAdapter localTimeAdapter = gson.getAdapter(LocalTime.class); return new TypeAdapter() { @Override public LocalDateTime read(JsonReader in) throws IOException { LocalDate localDate = null; LocalTime localTime = null; in.beginObject(); while (in.peek() != JsonToken.END_OBJECT) { String name = in.nextName(); switch (name) { case "date": localDate = localDateAdapter.read(in); break; case "time": localTime = localTimeAdapter.read(in); break; default: // Ignore other fields. in.skipValue(); } } in.endObject(); return LocalDateTime.of( requireNonNullField(localDate, "date", in), requireNonNullField(localTime, "time", in)); } @Override public void write(JsonWriter out, LocalDateTime value) throws IOException { out.beginObject(); out.name("date"); localDateAdapter.write(out, value.toLocalDate()); out.name("time"); localTimeAdapter.write(out, value.toLocalTime()); out.endObject(); } }.nullSafe(); } private static final TypeAdapter MONTH_DAY = new IntegerFieldsTypeAdapter("month", "day") { @Override MonthDay create(long[] values) { return MonthDay.of(toIntExact(values[0]), toIntExact(values[1])); } @Override long[] integerValues(MonthDay monthDay) { return new long[] {monthDay.getMonthValue(), monthDay.getDayOfMonth()}; } }; private static TypeAdapter offsetDateTime(Gson gson) { TypeAdapter localDateTimeAdapter = localDateTime(gson); TypeAdapter zoneOffsetAdapter = gson.getAdapter(ZoneOffset.class); return new TypeAdapter() { @Override public OffsetDateTime read(JsonReader in) throws IOException { in.beginObject(); LocalDateTime localDateTime = null; ZoneOffset zoneOffset = null; while (in.peek() != JsonToken.END_OBJECT) { String name = in.nextName(); switch (name) { case "dateTime": localDateTime = localDateTimeAdapter.read(in); break; case "offset": zoneOffset = zoneOffsetAdapter.read(in); break; default: // Ignore other fields. in.skipValue(); } } in.endObject(); return OffsetDateTime.of( requireNonNullField(localDateTime, "dateTime", in), requireNonNullField(zoneOffset, "offset", in)); } @Override public void write(JsonWriter out, OffsetDateTime value) throws IOException { out.beginObject(); out.name("dateTime"); localDateTimeAdapter.write(out, value.toLocalDateTime()); out.name("offset"); zoneOffsetAdapter.write(out, value.getOffset()); out.endObject(); } }.nullSafe(); } private static TypeAdapter offsetTime(Gson gson) { TypeAdapter localTimeAdapter = gson.getAdapter(LocalTime.class); TypeAdapter zoneOffsetAdapter = gson.getAdapter(ZoneOffset.class); return new TypeAdapter() { @Override public OffsetTime read(JsonReader in) throws IOException { in.beginObject(); LocalTime localTime = null; ZoneOffset zoneOffset = null; while (in.peek() != JsonToken.END_OBJECT) { String name = in.nextName(); switch (name) { case "time": localTime = localTimeAdapter.read(in); break; case "offset": zoneOffset = zoneOffsetAdapter.read(in); break; default: // Ignore other fields. in.skipValue(); } } in.endObject(); return OffsetTime.of( requireNonNullField(localTime, "time", in), requireNonNullField(zoneOffset, "offset", in)); } @Override public void write(JsonWriter out, OffsetTime value) throws IOException { out.beginObject(); out.name("time"); localTimeAdapter.write(out, value.toLocalTime()); out.name("offset"); zoneOffsetAdapter.write(out, value.getOffset()); out.endObject(); } }.nullSafe(); } private static final TypeAdapter PERIOD = new IntegerFieldsTypeAdapter("years", "months", "days") { @Override Period create(long[] values) { return Period.of(toIntExact(values[0]), toIntExact(values[1]), toIntExact(values[2])); } @Override long[] integerValues(Period period) { return new long[] {period.getYears(), period.getMonths(), period.getDays()}; } }; private static final TypeAdapter YEAR = new IntegerFieldsTypeAdapter("year") { @Override Year create(long[] values) { return Year.of(toIntExact(values[0])); } @Override long[] integerValues(Year year) { return new long[] {year.getValue()}; } }; private static final TypeAdapter YEAR_MONTH = new IntegerFieldsTypeAdapter("year", "month") { @Override YearMonth create(long[] values) { return YearMonth.of(toIntExact(values[0]), toIntExact(values[1])); } @Override long[] integerValues(YearMonth yearMonth) { return new long[] {yearMonth.getYear(), yearMonth.getMonthValue()}; } }; // A ZoneId is either a ZoneOffset or a ZoneRegion, where ZoneOffset is public and ZoneRegion is // not. For compatibility with reflection-based serialization, we need to write the "id" field of // ZoneRegion if we have a ZoneRegion, and we need to write the "totalSeconds" field of ZoneOffset // if we have a ZoneOffset. When reading, we need to construct the the appropriate thing depending // on which of those two fields we see. private static final TypeAdapter ZONE_ID = new TypeAdapter() { @Override public ZoneId read(JsonReader in) throws IOException { in.beginObject(); String id = null; Integer totalSeconds = null; while (in.peek() != JsonToken.END_OBJECT) { String name = in.nextName(); switch (name) { case "id": id = in.nextString(); break; case "totalSeconds": totalSeconds = in.nextInt(); break; default: // Ignore other fields. in.skipValue(); } } in.endObject(); if (id != null) { return ZoneId.of(id); } else if (totalSeconds != null) { return ZoneOffset.ofTotalSeconds(totalSeconds); } else { throw new JsonSyntaxException( "Missing id or totalSeconds field; at path " + in.getPreviousPath()); } } @Override public void write(JsonWriter out, ZoneId value) throws IOException { if (value instanceof ZoneOffset) { out.beginObject(); out.name("totalSeconds"); out.value(((ZoneOffset) value).getTotalSeconds()); out.endObject(); } else { out.beginObject(); out.name("id"); out.value(value.getId()); out.endObject(); } } }.nullSafe(); private static TypeAdapter zonedDateTime(Gson gson) { TypeAdapter localDateTimeAdapter = localDateTime(gson); TypeAdapter zoneOffsetAdapter = gson.getAdapter(ZoneOffset.class); TypeAdapter zoneIdAdapter = gson.getAdapter(ZoneId.class); return new TypeAdapter() { @Override public ZonedDateTime read(JsonReader in) throws IOException { in.beginObject(); LocalDateTime localDateTime = null; ZoneOffset zoneOffset = null; ZoneId zoneId = null; while (in.peek() != JsonToken.END_OBJECT) { String name = in.nextName(); switch (name) { case "dateTime": localDateTime = localDateTimeAdapter.read(in); break; case "offset": zoneOffset = zoneOffsetAdapter.read(in); break; case "zone": zoneId = zoneIdAdapter.read(in); break; default: // Ignore other fields. in.skipValue(); } } in.endObject(); return ZonedDateTime.ofInstant( requireNonNullField(localDateTime, "dateTime", in), requireNonNullField(zoneOffset, "offset", in), requireNonNullField(zoneId, "zone", in)); } @Override public void write(JsonWriter out, ZonedDateTime value) throws IOException { if (value == null) { out.nullValue(); return; } out.beginObject(); out.name("dateTime"); localDateTimeAdapter.write(out, value.toLocalDateTime()); out.name("offset"); zoneOffsetAdapter.write(out, value.getOffset()); out.name("zone"); zoneIdAdapter.write(out, value.getZone()); out.endObject(); } }.nullSafe(); } static final TypeAdapterFactory JAVA_TIME_FACTORY = new TypeAdapterFactory() { @Override public TypeAdapter create(Gson gson, TypeToken typeToken) { Class rawType = typeToken.getRawType(); if (!rawType.getName().startsWith("java.time.")) { // Immediately return null so we don't load all these classes when nobody's doing // anything with java.time. return null; } TypeAdapter adapter = null; if (rawType == Duration.class) { adapter = DURATION; } else if (rawType == Instant.class) { adapter = INSTANT; } else if (rawType == LocalDate.class) { adapter = LOCAL_DATE; } else if (rawType == LocalTime.class) { adapter = LOCAL_TIME; } else if (rawType == LocalDateTime.class) { adapter = localDateTime(gson); } else if (rawType == MonthDay.class) { adapter = MONTH_DAY; } else if (rawType == OffsetDateTime.class) { adapter = offsetDateTime(gson); } else if (rawType == OffsetTime.class) { adapter = offsetTime(gson); } else if (rawType == Period.class) { adapter = PERIOD; } else if (rawType == Year.class) { adapter = YEAR; } else if (rawType == YearMonth.class) { adapter = YEAR_MONTH; } else if (rawType == ZoneId.class || rawType == ZoneOffset.class) { // We don't check ZoneId.class.isAssignableFrom(rawType) because we don't want to match // the non-public class ZoneRegion in the runtime type check in // TypeAdapterRuntimeTypeWrapper.write. If we did, then our ZONE_ID would take // precedence over a ZoneId adapter that the user might have registered. (This exact // situation showed up in a Google-internal test.) adapter = ZONE_ID; } else if (rawType == ZonedDateTime.class) { adapter = zonedDateTime(gson); } @SuppressWarnings("unchecked") TypeAdapter result = (TypeAdapter) adapter; return result; } }; private static T requireNonNullField(T field, String fieldName, JsonReader reader) { if (field == null) { throw new JsonSyntaxException( "Missing " + fieldName + " field; at path " + reader.getPreviousPath()); } return field; } } ================================================ FILE: gson/src/main/java/com/google/gson/internal/bind/JsonAdapterAnnotationTypeAdapterFactory.java ================================================ /* * 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; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * 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 static class DummyTypeAdapterFactory implements TypeAdapterFactory { @Override public TypeAdapter create(Gson gson, TypeToken type) { throw new AssertionError("Factory should not be used"); } } /** Factory used for {@link TreeTypeAdapter}s created for {@code @JsonAdapter} on a class. */ private static final TypeAdapterFactory TREE_TYPE_CLASS_DUMMY_FACTORY = new DummyTypeAdapterFactory(); /** Factory used for {@link TreeTypeAdapter}s created for {@code @JsonAdapter} on a field. */ private static final TypeAdapterFactory TREE_TYPE_FIELD_DUMMY_FACTORY = new DummyTypeAdapterFactory(); private final ConstructorConstructor constructorConstructor; /** * For a class, if it is annotated with {@code @JsonAdapter} and refers to a {@link * TypeAdapterFactory}, stores the factory instance in case it has been requested already. Has to * be a {@link ConcurrentMap} because {@link Gson} guarantees to be thread-safe. */ // Note: In case these strong reference to TypeAdapterFactory instances are considered // a memory leak in the future, could consider switching to WeakReference private final ConcurrentMap, TypeAdapterFactory> adapterFactoryMap; public JsonAdapterAnnotationTypeAdapterFactory(ConstructorConstructor constructorConstructor) { this.constructorConstructor = constructorConstructor; this.adapterFactoryMap = new ConcurrentHashMap<>(); } // Separate helper method to make sure callers retrieve annotation in a consistent way private static JsonAdapter getAnnotation(Class rawType) { return rawType.getAnnotation(JsonAdapter.class); } // this is not safe; requires that user has specified correct adapter class for @JsonAdapter @SuppressWarnings("unchecked") @Override public TypeAdapter create(Gson gson, TypeToken targetType) { Class rawType = targetType.getRawType(); JsonAdapter annotation = getAnnotation(rawType); if (annotation == null) { return null; } return (TypeAdapter) getTypeAdapter(constructorConstructor, gson, targetType, annotation, true); } // Separate helper method to make sure callers create adapter in a consistent way private static Object createAdapter( ConstructorConstructor constructorConstructor, Class adapterClass) { // TODO: The exception messages created by ConstructorConstructor are currently written in the // context of deserialization and for example suggest usage of TypeAdapter, which would not work // for @JsonAdapter usage // TODO: Should probably not allow usage of Unsafe; instances might be in broken state and // calling adapter methods on them might lead to confusing exceptions boolean allowUnsafe = true; return constructorConstructor.get(TypeToken.get(adapterClass), allowUnsafe).construct(); } private TypeAdapterFactory putFactoryAndGetCurrent(Class rawType, TypeAdapterFactory factory) { // Uses putIfAbsent in case multiple threads concurrently create factory TypeAdapterFactory existingFactory = adapterFactoryMap.putIfAbsent(rawType, factory); return existingFactory != null ? existingFactory : factory; } TypeAdapter getTypeAdapter( ConstructorConstructor constructorConstructor, Gson gson, TypeToken type, JsonAdapter annotation, boolean isClassAnnotation) { Object instance = createAdapter(constructorConstructor, annotation.value()); TypeAdapter typeAdapter; boolean nullSafe = annotation.nullSafe(); if (instance instanceof TypeAdapter) { typeAdapter = (TypeAdapter) instance; } else if (instance instanceof TypeAdapterFactory) { TypeAdapterFactory factory = (TypeAdapterFactory) instance; if (isClassAnnotation) { factory = putFactoryAndGetCurrent(type.getRawType(), factory); } typeAdapter = factory.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; // Uses dummy factory instances because TreeTypeAdapter needs a 'skipPast' factory for // `Gson.getDelegateAdapter` call and has to differentiate there whether TreeTypeAdapter was // created for @JsonAdapter on class or field TypeAdapterFactory skipPast; if (isClassAnnotation) { skipPast = TREE_TYPE_CLASS_DUMMY_FACTORY; } else { skipPast = TREE_TYPE_FIELD_DUMMY_FACTORY; } @SuppressWarnings({"unchecked", "rawtypes"}) TypeAdapter tempAdapter = new TreeTypeAdapter(serializer, deserializer, gson, type, skipPast, nullSafe); typeAdapter = tempAdapter; // TreeTypeAdapter handles nullSafe; don't additionally call `nullSafe()` nullSafe = false; } 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 && nullSafe) { typeAdapter = typeAdapter.nullSafe(); } return typeAdapter; } /** * Returns whether {@code factory} is a type adapter factory created for {@code @JsonAdapter} * placed on {@code type}. */ public boolean isClassJsonAdapterFactory(TypeToken type, TypeAdapterFactory factory) { Objects.requireNonNull(type); Objects.requireNonNull(factory); if (factory == TREE_TYPE_CLASS_DUMMY_FACTORY) { return true; } // Using raw type to match behavior of `create(Gson, TypeToken)` above Class rawType = type.getRawType(); TypeAdapterFactory existingFactory = adapterFactoryMap.get(rawType); if (existingFactory != null) { // Checks for reference equality, like it is done by `Gson.getDelegateAdapter` return existingFactory == factory; } // If no factory has been created for the type yet check manually for a @JsonAdapter annotation // which specifies a TypeAdapterFactory // Otherwise behavior would not be consistent, depending on whether or not adapter had been // requested before call to `isClassJsonAdapterFactory` was made JsonAdapter annotation = getAnnotation(rawType); if (annotation == null) { return false; } Class adapterClass = annotation.value(); if (!TypeAdapterFactory.class.isAssignableFrom(adapterClass)) { return false; } Object adapter = createAdapter(constructorConstructor, adapterClass); TypeAdapterFactory newFactory = (TypeAdapterFactory) adapter; return putFactoryAndGetCurrent(rawType, newFactory) == factory; } } ================================================ FILE: gson/src/main/java/com/google/gson/internal/bind/JsonElementTypeAdapter.java ================================================ /* * Copyright (C) 2024 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.TypeAdapter; import com.google.gson.internal.LazilyParsedNumber; 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.Deque; import java.util.Map; /** Adapter for {@link JsonElement} and subclasses. */ public class JsonElementTypeAdapter extends TypeAdapter { public static final JsonElementTypeAdapter ADAPTER = new JsonElementTypeAdapter(); private JsonElementTypeAdapter() {} /** * 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 { // Optimization if value already exists as JsonElement 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 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 e : value.getAsJsonObject().entrySet()) { out.name(e.getKey()); write(out, e.getValue()); } out.endObject(); } else { throw new IllegalArgumentException("Couldn't write " + value.getClass()); } } } ================================================ FILE: gson/src/main/java/com/google/gson/internal/bind/JsonTreeReader.java ================================================ /* * 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.errorprone.annotations.CanIgnoreReturnValue; 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 com.google.gson.stream.MalformedJsonException; import java.io.IOException; import java.io.Reader; import java.util.Arrays; import java.util.Iterator; import java.util.Map; /** * 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) { throw new AssertionError(); } @Override public void close() { 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]; /** * The used size of {@link #stack}; the value at {@code stackSize - 1} is the value last placed on * the stack. {@code stackSize} might differ from the nesting depth, because the stack also * contains temporary additional objects, for example for a JsonArray it contains the JsonArray * object as well as the corresponding iterator. */ 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); pathNames[stackSize - 1] = null; // Free the last path name so that it can be garbage collected 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 MalformedJsonException( "Custom JsonElement subclass " + o.getClass().getName() + " is not supported"); } } private Object peekStack() { return stack[stackSize - 1]; } @CanIgnoreReturnValue 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()); } } private String nextName(boolean skipName) throws IOException { expect(JsonToken.NAME); Iterator i = (Iterator) peekStack(); Map.Entry entry = (Map.Entry) i.next(); String result = (String) entry.getKey(); pathNames[stackSize - 1] = skipName ? "" : result; push(entry.getValue()); return result; } @Override public String nextName() throws IOException { return nextName(false); } @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 MalformedJsonException("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 { 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."); } 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 { JsonToken peeked = peek(); switch (peeked) { case NAME: @SuppressWarnings("unused") String unused = nextName(true); break; case END_ARRAY: endArray(); break; case END_OBJECT: endObject(); break; case END_DOCUMENT: // Do nothing break; default: popStack(); if (stackSize > 0) { pathIndices[stackSize - 1]++; } break; } } @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 getPath() { return getPath(false); } @Override public String getPreviousPath() { return getPath(true); } private String locationString() { return " at path " + getPath(); } } ================================================ FILE: gson/src/main/java/com/google/gson/internal/bind/JsonTreeWriter.java ================================================ /* * 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.errorprone.annotations.CanIgnoreReturnValue; 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; import java.util.Objects; /** 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() { throw new AssertionError(); } @Override public void close() { 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 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(); } } } @CanIgnoreReturnValue @Override public JsonWriter beginArray() throws IOException { JsonArray array = new JsonArray(); put(array); stack.add(array); return this; } @CanIgnoreReturnValue @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(); } @CanIgnoreReturnValue @Override public JsonWriter beginObject() throws IOException { JsonObject object = new JsonObject(); put(object); stack.add(object); return this; } @CanIgnoreReturnValue @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(); } @CanIgnoreReturnValue @Override public JsonWriter name(String name) throws IOException { Objects.requireNonNull(name, "name == null"); if (stack.isEmpty() || pendingName != null) { throw new IllegalStateException("Did not expect a name"); } JsonElement element = peek(); if (element instanceof JsonObject) { pendingName = name; return this; } throw new IllegalStateException("Please begin an object before writing a name."); } @CanIgnoreReturnValue @Override public JsonWriter value(String value) throws IOException { if (value == null) { return nullValue(); } put(new JsonPrimitive(value)); return this; } @CanIgnoreReturnValue @Override public JsonWriter value(boolean value) throws IOException { put(new JsonPrimitive(value)); return this; } @CanIgnoreReturnValue @Override public JsonWriter value(Boolean value) throws IOException { if (value == null) { return nullValue(); } put(new JsonPrimitive(value)); return this; } @CanIgnoreReturnValue @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; } @CanIgnoreReturnValue @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; } @CanIgnoreReturnValue @Override public JsonWriter value(long value) throws IOException { put(new JsonPrimitive(value)); return this; } @CanIgnoreReturnValue @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; } @CanIgnoreReturnValue @Override public JsonWriter nullValue() throws IOException { put(JsonNull.INSTANCE); return this; } @Override public JsonWriter jsonValue(String value) throws IOException { throw new UnsupportedOperationException(); } @Override public void flush() throws IOException {} @Override public void close() throws IOException { if (!stack.isEmpty()) { throw new IOException("Incomplete document"); } stack.add(SENTINEL_CLOSED); } } ================================================ FILE: gson/src/main/java/com/google/gson/internal/bind/MapTypeAdapterFactory.java ================================================ /* * 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.ConstructorConstructor; import com.google.gson.internal.GsonTypes; 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. * *

Maps as JSON objects

* * 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: * *
{@code
 * Map original = new LinkedHashMap<>();
 * original.put(new Point(5, 6), "a");
 * original.put(new Point(8, 8), "b");
 * System.out.println(gson.toJson(original, type));
 * }
* * The above code prints this JSON object: * *
{@code
 * {
 *   "(5,6)": "a",
 *   "(8,8)": "b"
 * }
 * }
* * 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: * *
com.google.gson.JsonParseException: Expecting object found: "(5,6)"
 *   at com.google.gson.JsonObjectDeserializationVisitor.visitFieldUsingCustomHandler
 *   at com.google.gson.ObjectNavigator.navigateClassFields
 *   ...
* *

Maps as JSON arrays

* * 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. * *

Register this adapter when you are creating your GSON instance. * *

{@code
 * Gson gson = new GsonBuilder()
 *   .registerTypeAdapter(Map.class, new MapAsArrayTypeAdapter())
 *   .create();
 * }
* * 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: * *
{@code
 * [
 *   [
 *     {
 *       "x": 5,
 *       "y": 6
 *     },
 *     "a",
 *   ],
 *   [
 *     {
 *       "x": 8,
 *       "y": 8
 *     },
 *     "b"
 *   ]
 * ]
 * }
* * 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 TypeAdapter create(Gson gson, TypeToken typeToken) { Type type = typeToken.getType(); Class rawType = typeToken.getRawType(); if (!Map.class.isAssignableFrom(rawType)) { return null; } Type[] keyAndValueTypes = GsonTypes.getMapKeyAndValueTypes(type, rawType); Type keyType = keyAndValueTypes[0]; Type valueType = keyAndValueTypes[1]; TypeAdapter keyAdapter = getKeyAdapter(gson, keyType); TypeAdapter wrappedKeyAdapter = new TypeAdapterRuntimeTypeWrapper<>(gson, keyAdapter, keyType); TypeAdapter valueAdapter = gson.getAdapter(TypeToken.get(valueType)); TypeAdapter wrappedValueAdapter = new TypeAdapterRuntimeTypeWrapper<>(gson, valueAdapter, valueType); // Don't allow Unsafe usage to create instance; instances might be in broken state and calling // Map methods could lead to confusing exceptions boolean allowUnsafe = false; ObjectConstructor constructor = constructorConstructor.get(typeToken, allowUnsafe); @SuppressWarnings({"unchecked", "rawtypes"}) // we don't define a type parameter for the key or value types TypeAdapter result = new Adapter(wrappedKeyAdapter, wrappedValueAdapter, 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 extends TypeAdapter> { private final TypeAdapter keyTypeAdapter; private final TypeAdapter valueTypeAdapter; private final ObjectConstructor> constructor; Adapter( TypeAdapter keyTypeAdapter, TypeAdapter valueTypeAdapter, ObjectConstructor> constructor) { this.keyTypeAdapter = keyTypeAdapter; this.valueTypeAdapter = valueTypeAdapter; this.constructor = constructor; } @Override public Map read(JsonReader in) throws IOException { JsonToken peek = in.peek(); if (peek == JsonToken.NULL) { in.nextNull(); return null; } Map 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 map) throws IOException { if (map == null) { out.nullValue(); return; } if (!complexMapKeySerialization) { out.beginObject(); for (Map.Entry entry : map.entrySet()) { out.name(String.valueOf(entry.getKey())); valueTypeAdapter.write(out, entry.getValue()); } out.endObject(); return; } boolean hasComplexKeys = false; List keys = new ArrayList<>(map.size()); List values = new ArrayList<>(map.size()); for (Map.Entry 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(); } } } } ================================================ FILE: gson/src/main/java/com/google/gson/internal/bind/NumberTypeAdapter.java ================================================ /* * 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.ToNumberPolicy; import com.google.gson.ToNumberStrategy; 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 { /** 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) { NumberTypeAdapter adapter = new NumberTypeAdapter(toNumberStrategy); return new TypeAdapterFactory() { @SuppressWarnings("unchecked") @Override public TypeAdapter create(Gson gson, TypeToken type) { return type.getRawType() == Number.class ? (TypeAdapter) 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); } } ================================================ FILE: gson/src/main/java/com/google/gson/internal/bind/ObjectTypeAdapter.java ================================================ /* * 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 { /** 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(ToNumberStrategy toNumberStrategy) { return new TypeAdapterFactory() { @SuppressWarnings("unchecked") @Override public TypeAdapter create(Gson gson, TypeToken type) { if (type.getRawType() == Object.class) { return (TypeAdapter) 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 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 list = (List) current; list.add(value); } else { @SuppressWarnings("unchecked") Map map = (Map) 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(); } } } @Override public void write(JsonWriter out, Object value) throws IOException { if (value == null) { out.nullValue(); return; } @SuppressWarnings("unchecked") TypeAdapter typeAdapter = (TypeAdapter) gson.getAdapter(value.getClass()); if (typeAdapter instanceof ObjectTypeAdapter) { out.beginObject(); out.endObject(); return; } typeAdapter.write(out, value); } } ================================================ FILE: gson/src/main/java/com/google/gson/internal/bind/ReflectiveTypeAdapterFactory.java ================================================ /* * 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.JsonParseException; 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.ConstructorConstructor; import com.google.gson.internal.Excluder; import com.google.gson.internal.GsonTypes; import com.google.gson.internal.ObjectConstructor; import com.google.gson.internal.Primitives; import com.google.gson.internal.ReflectionAccessFilterHelper; import com.google.gson.internal.TroubleshootingGuide; 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.AccessibleObject; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; 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 reflectionFilters; public ReflectiveTypeAdapterFactory( ConstructorConstructor constructorConstructor, FieldNamingStrategy fieldNamingPolicy, Excluder excluder, JsonAdapterAnnotationTypeAdapterFactory jsonAdapterFactory, List 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.excludeField(f, serialize); } /** first element holds the default name */ @SuppressWarnings("MixedMutabilityReturnType") private List getFieldNames(Field f) { String fieldName; List alternates; SerializedName annotation = f.getAnnotation(SerializedName.class); if (annotation == null) { fieldName = fieldNamingPolicy.translateName(f); alternates = fieldNamingPolicy.alternateNames(f); } else { fieldName = annotation.value(); alternates = Arrays.asList(annotation.alternate()); } if (alternates.isEmpty()) { return Collections.singletonList(fieldName); } List fieldNames = new ArrayList<>(alternates.size() + 1); fieldNames.add(fieldName); fieldNames.addAll(alternates); return fieldNames; } @Override public TypeAdapter create(Gson gson, TypeToken type) { Class raw = type.getRawType(); if (!Object.class.isAssignableFrom(raw)) { return null; // it's a primitive! } // Don't allow using reflection on anonymous and local classes because synthetic fields for // captured enclosing values make this unreliable if (ReflectionHelper.isAnonymousOrNonStaticLocal(raw)) { // This adapter just serializes and deserializes null, ignoring the actual values // This is done for backward compatibility; troubleshooting-wise it might be better to throw // exceptions return new TypeAdapter() { @Override public T read(JsonReader in) throws IOException { in.skipValue(); return null; } @Override public void write(JsonWriter out, T value) throws IOException { out.nullValue(); } @Override public String toString() { return "AnonymousOrNonStaticLocalClassAdapter"; } }; } 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; // If the type is actually a Java Record, we need to use the RecordAdapter instead. This will // always be false on JVMs that do not support records. if (ReflectionHelper.isRecord(raw)) { @SuppressWarnings("unchecked") TypeAdapter adapter = (TypeAdapter) new RecordAdapter<>( raw, getBoundFields(gson, type, raw, blockInaccessible, true), blockInaccessible); return adapter; } ObjectConstructor constructor = constructorConstructor.get(type, true); return new FieldReflectionAdapter<>( constructor, getBoundFields(gson, type, raw, blockInaccessible, false)); } private static void checkAccessible( Object object, M member) { if (!ReflectionAccessFilterHelper.canAccess( member, Modifier.isStatic(member.getModifiers()) ? null : object)) { String memberDescription = ReflectionHelper.getAccessibleObjectDescription(member, true); throw new JsonIOException( memberDescription + " is not accessible and ReflectionAccessFilter does not permit making it" + " accessible. Register a TypeAdapter for the declaring type, adjust the access" + " filter or increase the visibility of the element and its declaring type."); } } private BoundField createBoundField( Gson context, Field field, Method accessor, String serializedName, TypeToken fieldType, boolean serialize, boolean blockInaccessible) { boolean isPrimitive = Primitives.isPrimitive(fieldType.getRawType()); int modifiers = field.getModifiers(); boolean isStaticFinalField = Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers); JsonAdapter annotation = field.getAnnotation(JsonAdapter.class); TypeAdapter mapped = null; if (annotation != null) { // This is not safe; requires that user has specified correct adapter class for @JsonAdapter mapped = jsonAdapterFactory.getTypeAdapter( constructorConstructor, context, fieldType, annotation, false); } boolean jsonAdapterPresent = mapped != null; if (mapped == null) { mapped = context.getAdapter(fieldType); } @SuppressWarnings("unchecked") TypeAdapter typeAdapter = (TypeAdapter) mapped; TypeAdapter writeTypeAdapter; if (serialize) { writeTypeAdapter = jsonAdapterPresent ? typeAdapter : new TypeAdapterRuntimeTypeWrapper<>(context, typeAdapter, fieldType.getType()); } else { // Will never actually be used, but we set it to avoid confusing nullness-analysis tools writeTypeAdapter = typeAdapter; } return new BoundField(serializedName, field) { @Override void write(JsonWriter writer, Object source) throws IOException, IllegalAccessException { if (blockInaccessible) { if (accessor == null) { checkAccessible(source, field); } else { // Note: This check might actually be redundant because access check for canonical // constructor should have failed already checkAccessible(source, accessor); } } Object fieldValue; if (accessor != null) { try { fieldValue = accessor.invoke(source); } catch (InvocationTargetException e) { String accessorDescription = ReflectionHelper.getAccessibleObjectDescription(accessor, false); throw new JsonIOException( "Accessor " + accessorDescription + " threw exception", e.getCause()); } } else { fieldValue = field.get(source); } if (fieldValue == source) { // avoid direct recursion return; } writer.name(serializedName); writeTypeAdapter.write(writer, fieldValue); } @Override void readIntoArray(JsonReader reader, int index, Object[] target) throws IOException, JsonParseException { Object fieldValue = typeAdapter.read(reader); if (fieldValue == null && isPrimitive) { throw new JsonParseException( "null is not allowed as value for record component '" + fieldName + "' of primitive type; at path " + reader.getPath()); } target[index] = fieldValue; } @Override void readIntoField(JsonReader reader, Object target) throws IOException, IllegalAccessException { Object fieldValue = typeAdapter.read(reader); if (fieldValue != null || !isPrimitive) { if (blockInaccessible) { checkAccessible(target, field); } else if (isStaticFinalField) { // Reflection does not permit setting value of `static final` field, even after calling // `setAccessible` // Handle this here to avoid causing IllegalAccessException when calling `Field.set` String fieldDescription = ReflectionHelper.getAccessibleObjectDescription(field, false); throw new JsonIOException("Cannot set value of 'static final' " + fieldDescription); } field.set(target, fieldValue); } } }; } private static class FieldsData { static final FieldsData EMPTY = new FieldsData(Collections.emptyMap(), Collections.emptyList()); /** Maps from JSON member name to field */ final Map deserializedFields; final List serializedFields; FieldsData(Map deserializedFields, List serializedFields) { this.deserializedFields = deserializedFields; this.serializedFields = serializedFields; } } private static IllegalArgumentException createDuplicateFieldException( Class declaringType, String duplicateName, Field field1, Field field2) { throw new IllegalArgumentException( "Class " + declaringType.getName() + " declares multiple JSON fields named '" + duplicateName + "'; conflict is caused by fields " + ReflectionHelper.fieldToString(field1) + " and " + ReflectionHelper.fieldToString(field2) + "\nSee " + TroubleshootingGuide.createUrl("duplicate-fields")); } private FieldsData getBoundFields( Gson context, TypeToken type, Class raw, boolean blockInaccessible, boolean isRecord) { if (raw.isInterface()) { return FieldsData.EMPTY; } Map deserializedFields = new LinkedHashMap<>(); // For serialized fields use a Map to track duplicate field names; otherwise this could be a // List instead Map serializedFields = new LinkedHashMap<>(); 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; } // The accessor method is only used for records. If the type is a record, we will read out // values via its accessor method instead of via reflection. This way we will bypass the // accessible restrictions Method accessor = null; if (isRecord) { // If there is a static field on a record, there will not be an accessor. Instead we will // use the default field serialization logic, but for deserialization the field is // excluded for simplicity. // Note that Gson ignores static fields by default, but // GsonBuilder.excludeFieldsWithModifiers can overwrite this. if (Modifier.isStatic(field.getModifiers())) { deserialize = false; } else { accessor = ReflectionHelper.getAccessor(raw, field); // If blockInaccessible, skip and perform access check later if (!blockInaccessible) { ReflectionHelper.makeAccessible(accessor); } // @SerializedName can be placed on accessor method, but it is not supported there // If field and method have annotation it is not easily possible to determine if // accessor method is implicit and has inherited annotation, or if it is explicitly // declared with custom annotation if (accessor.getAnnotation(SerializedName.class) != null && field.getAnnotation(SerializedName.class) == null) { String methodDescription = ReflectionHelper.getAccessibleObjectDescription(accessor, false); throw new JsonIOException( "@SerializedName on " + methodDescription + " is not supported"); } } } // If blockInaccessible, skip and perform access check later // For Records if the accessor method is used the field does not have to be made accessible if (!blockInaccessible && accessor == null) { ReflectionHelper.makeAccessible(field); } Type fieldType = GsonTypes.resolve(type.getType(), raw, field.getGenericType()); List fieldNames = getFieldNames(field); String serializedName = fieldNames.get(0); BoundField boundField = createBoundField( context, field, accessor, serializedName, TypeToken.get(fieldType), serialize, blockInaccessible); if (deserialize) { for (String name : fieldNames) { BoundField replaced = deserializedFields.put(name, boundField); if (replaced != null) { throw createDuplicateFieldException(originalRaw, name, replaced.field, field); } } } if (serialize) { BoundField replaced = serializedFields.put(serializedName, boundField); if (replaced != null) { throw createDuplicateFieldException(originalRaw, serializedName, replaced.field, field); } } } type = TypeToken.get(GsonTypes.resolve(type.getType(), raw, raw.getGenericSuperclass())); raw = type.getRawType(); } return new FieldsData(deserializedFields, new ArrayList<>(serializedFields.values())); } abstract static class BoundField { /** Name used for serialization (but not for deserialization) */ final String serializedName; final Field field; /** Name of the underlying field */ final String fieldName; protected BoundField(String serializedName, Field field) { this.serializedName = serializedName; this.field = field; this.fieldName = field.getName(); } /** Read this field value from the source, and append its JSON value to the writer */ abstract void write(JsonWriter writer, Object source) throws IOException, IllegalAccessException; /** Read the value into the target array, used to provide constructor arguments for records */ abstract void readIntoArray(JsonReader reader, int index, Object[] target) throws IOException, JsonParseException; /** * Read the value from the reader, and set it on the corresponding field on target via * reflection */ abstract void readIntoField(JsonReader reader, Object target) throws IOException, IllegalAccessException; } /** * Base class for Adapters produced by this factory. * *

The {@link RecordAdapter} is a special case to handle records for JVMs that support it, for * all other types we use the {@link FieldReflectionAdapter}. This class encapsulates the common * logic for serialization and deserialization. During deserialization, we construct an * accumulator A, which we use to accumulate values from the source JSON. After the object has * been read in full, the {@link #finalize(Object)} method is used to convert the accumulator to * an instance of T. * * @param type of objects that this Adapter creates. * @param type of accumulator used to build the deserialization result. */ // This class is public because external projects check for this class with `instanceof` (even // though it is internal) public abstract static class Adapter extends TypeAdapter { private final FieldsData fieldsData; Adapter(FieldsData fieldsData) { this.fieldsData = fieldsData; } @Override public void write(JsonWriter out, T value) throws IOException { if (value == null) { out.nullValue(); return; } out.beginObject(); try { for (BoundField boundField : fieldsData.serializedFields) { boundField.write(out, value); } } catch (IllegalAccessException e) { throw ReflectionHelper.createExceptionForUnexpectedIllegalAccess(e); } out.endObject(); } @Override public T read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } A accumulator = createAccumulator(); Map deserializedFields = fieldsData.deserializedFields; try { in.beginObject(); while (in.hasNext()) { String name = in.nextName(); BoundField field = deserializedFields.get(name); if (field == null) { in.skipValue(); } else { readField(accumulator, in, field); } } } catch (IllegalStateException e) { throw new JsonSyntaxException(e); } catch (IllegalAccessException e) { throw ReflectionHelper.createExceptionForUnexpectedIllegalAccess(e); } in.endObject(); return finalize(accumulator); } /** Create the Object that will be used to collect each field value */ abstract A createAccumulator(); /** * Read a single BoundField into the accumulator. The JsonReader will be pointed at the start of * the value for the BoundField to read from. */ abstract void readField(A accumulator, JsonReader in, BoundField field) throws IllegalAccessException, IOException; /** Convert the accumulator to a final instance of T. */ abstract T finalize(A accumulator); } private static final class FieldReflectionAdapter extends Adapter { private final ObjectConstructor constructor; FieldReflectionAdapter(ObjectConstructor constructor, FieldsData fieldsData) { super(fieldsData); this.constructor = constructor; } @Override T createAccumulator() { return constructor.construct(); } @Override void readField(T accumulator, JsonReader in, BoundField field) throws IllegalAccessException, IOException { field.readIntoField(in, accumulator); } @Override T finalize(T accumulator) { return accumulator; } } private static final class RecordAdapter extends Adapter { static final Map, Object> PRIMITIVE_DEFAULTS = primitiveDefaults(); // The canonical constructor of the record private final Constructor constructor; // Array of arguments to the constructor, initialized with default values for primitives private final Object[] constructorArgsDefaults; // Map from component names to index into the constructors arguments. private final Map componentIndices = new HashMap<>(); RecordAdapter(Class raw, FieldsData fieldsData, boolean blockInaccessible) { super(fieldsData); constructor = ReflectionHelper.getCanonicalRecordConstructor(raw); if (blockInaccessible) { checkAccessible(null, constructor); } else { // Ensure the constructor is accessible ReflectionHelper.makeAccessible(constructor); } String[] componentNames = ReflectionHelper.getRecordComponentNames(raw); for (int i = 0; i < componentNames.length; i++) { componentIndices.put(componentNames[i], i); } Class[] parameterTypes = constructor.getParameterTypes(); // We need to ensure that we are passing non-null values to primitive fields in the // constructor. To do this, we create an Object[] where all primitives are initialized to // non-null values. constructorArgsDefaults = new Object[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { // This will correctly be null for non-primitive types: constructorArgsDefaults[i] = PRIMITIVE_DEFAULTS.get(parameterTypes[i]); } } private static Map, Object> primitiveDefaults() { Map, Object> zeroes = new HashMap<>(); zeroes.put(byte.class, (byte) 0); zeroes.put(short.class, (short) 0); zeroes.put(int.class, 0); zeroes.put(long.class, 0L); zeroes.put(float.class, 0F); zeroes.put(double.class, 0D); zeroes.put(char.class, '\0'); zeroes.put(boolean.class, false); return zeroes; } @Override Object[] createAccumulator() { return constructorArgsDefaults.clone(); } @Override void readField(Object[] accumulator, JsonReader in, BoundField field) throws IOException { // Obtain the component index from the name of the field backing it Integer componentIndex = componentIndices.get(field.fieldName); if (componentIndex == null) { throw new IllegalStateException( "Could not find the index in the constructor '" + ReflectionHelper.constructorToString(constructor) + "' for field with name '" + field.fieldName + "', unable to determine which argument in the constructor the field corresponds" + " to. This is unexpected behavior, as we expect the RecordComponents to have the" + " same names as the fields in the Java class, and that the order of the" + " RecordComponents is the same as the order of the canonical constructor" + " parameters."); } field.readIntoArray(in, componentIndex, accumulator); } @Override T finalize(Object[] accumulator) { try { return constructor.newInstance(accumulator); } catch (IllegalAccessException e) { throw ReflectionHelper.createExceptionForUnexpectedIllegalAccess(e); } // Note: InstantiationException should be impossible because record class is not abstract; // IllegalArgumentException should not be possible unless a bad adapter returns objects of // the wrong type catch (InstantiationException | IllegalArgumentException e) { throw new RuntimeException( "Failed to invoke constructor '" + ReflectionHelper.constructorToString(constructor) + "' with args " + Arrays.toString(accumulator), e); } catch (InvocationTargetException e) { // TODO: JsonParseException ? throw new RuntimeException( "Failed to invoke constructor '" + ReflectionHelper.constructorToString(constructor) + "' with args " + Arrays.toString(accumulator), e.getCause()); } } } } ================================================ FILE: gson/src/main/java/com/google/gson/internal/bind/SerializationDelegatingTypeAdapter.java ================================================ /* * Copyright (C) 2022 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.TypeAdapter; /** Type adapter which might delegate serialization to another adapter. */ public abstract class SerializationDelegatingTypeAdapter extends TypeAdapter { /** * Returns the adapter used for serialization, might be {@code this} or another adapter. That * other adapter might itself also be a {@code SerializationDelegatingTypeAdapter}. */ public abstract TypeAdapter getSerializationDelegate(); } ================================================ FILE: gson/src/main/java/com/google/gson/internal/bind/TreeTypeAdapter.java ================================================ /* * 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.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; import java.util.Objects; /** * 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 look up a delegate type * adapter on demand. */ public final class TreeTypeAdapter extends SerializationDelegatingTypeAdapter { private final JsonSerializer serializer; private final JsonDeserializer deserializer; final Gson gson; private final TypeToken typeToken; /** * Only intended as {@code skipPast} for {@link Gson#getDelegateAdapter(TypeAdapterFactory, * TypeToken)}, must not be used in any other way. */ private final TypeAdapterFactory skipPastForGetDelegateAdapter; private final GsonContextImpl context = new GsonContextImpl(); private final boolean nullSafe; /** * The delegate is lazily created because it may not be needed, and creating it may fail. Field * has to be {@code volatile} because {@link Gson} guarantees to be thread-safe. */ private volatile TypeAdapter delegate; public TreeTypeAdapter( JsonSerializer serializer, JsonDeserializer deserializer, Gson gson, TypeToken typeToken, TypeAdapterFactory skipPast, boolean nullSafe) { this.serializer = serializer; this.deserializer = deserializer; this.gson = gson; this.typeToken = typeToken; this.skipPastForGetDelegateAdapter = skipPast; this.nullSafe = nullSafe; } public TreeTypeAdapter( JsonSerializer serializer, JsonDeserializer deserializer, Gson gson, TypeToken typeToken, TypeAdapterFactory skipPast) { this(serializer, deserializer, gson, typeToken, skipPast, true); } @Override public T read(JsonReader in) throws IOException { if (deserializer == null) { return delegate().read(in); } JsonElement value = Streams.parse(in); if (nullSafe && 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 (nullSafe && value == null) { out.nullValue(); return; } JsonElement tree = serializer.serialize(value, typeToken.getType(), context); Streams.write(tree, out); } private TypeAdapter delegate() { // A race might lead to `delegate` being assigned by multiple threads but the last assignment // will stick TypeAdapter d = delegate; if (d == null) { d = delegate = gson.getDelegateAdapter(skipPastForGetDelegateAdapter, typeToken); } return d; } /** * Returns the type adapter which is used for serialization. Returns {@code this} if this {@code * TreeTypeAdapter} has a {@link #serializer}; otherwise returns the delegate. */ @Override public TypeAdapter getSerializationDelegate() { return serializer != null ? this : delegate(); } /** 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; if (serializer == null && deserializer == null) { Objects.requireNonNull(typeAdapter); throw new IllegalArgumentException( "Type adapter " + typeAdapter.getClass().getName() + " must implement JsonSerializer or JsonDeserializer"); } this.exactType = exactType; this.matchRawType = matchRawType; this.hierarchyType = hierarchyType; } @SuppressWarnings("unchecked") // guarded by typeToken.equals() call @Override public TypeAdapter create(Gson gson, TypeToken type) { boolean matches = exactType != null ? exactType.equals(type) || (matchRawType && exactType.getType() == type.getRawType()) : hierarchyType.isAssignableFrom(type.getRawType()); return matches ? new TreeTypeAdapter<>( (JsonSerializer) serializer, (JsonDeserializer) 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); } @Override @SuppressWarnings("TypeParameterUnusedInFormals") public R deserialize(JsonElement json, Type typeOfT) throws JsonParseException { return gson.fromJson(json, typeOfT); } } } ================================================ FILE: gson/src/main/java/com/google/gson/internal/bind/TypeAdapterRuntimeTypeWrapper.java ================================================ /* * 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.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.lang.reflect.TypeVariable; final class TypeAdapterRuntimeTypeWrapper extends TypeAdapter { private final Gson context; private final TypeAdapter delegate; private final Type type; TypeAdapterRuntimeTypeWrapper(Gson context, TypeAdapter delegate, Type type) { this.context = context; this.delegate = delegate; this.type = type; } @Override public T read(JsonReader in) throws IOException { return delegate.read(in); } @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 subclass of the declared type) // Fourth preference: reflective type adapter for the declared type TypeAdapter chosen = delegate; Type runtimeType = getRuntimeTypeIfMoreSpecific(type, value); if (runtimeType != type) { @SuppressWarnings("unchecked") TypeAdapter runtimeTypeAdapter = (TypeAdapter) context.getAdapter(TypeToken.get(runtimeType)); // For backward compatibility only check ReflectiveTypeAdapterFactory.Adapter here but not any // other wrapping adapters, see // https://github.com/google/gson/pull/1787#issuecomment-1222175189 if (!(runtimeTypeAdapter instanceof ReflectiveTypeAdapterFactory.Adapter)) { // The user registered a type adapter for the runtime type, so we will use that chosen = runtimeTypeAdapter; } else if (!isReflective(delegate)) { // 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); } /** * Returns whether the type adapter uses reflection. * * @param typeAdapter the type adapter to check. */ private static boolean isReflective(TypeAdapter typeAdapter) { // Run this in loop in case multiple delegating adapters are nested while (typeAdapter instanceof SerializationDelegatingTypeAdapter) { TypeAdapter delegate = ((SerializationDelegatingTypeAdapter) typeAdapter).getSerializationDelegate(); // Break if adapter does not delegate serialization if (delegate == typeAdapter) { break; } typeAdapter = delegate; } return typeAdapter instanceof ReflectiveTypeAdapterFactory.Adapter; } /** Finds a compatible runtime type if it is more specific */ private static Type getRuntimeTypeIfMoreSpecific(Type type, Object value) { if (value != null && (type instanceof Class || type instanceof TypeVariable)) { type = value.getClass(); } return type; } } ================================================ FILE: gson/src/main/java/com/google/gson/internal/bind/TypeAdapters.java ================================================ /* * 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.JsonIOException; import com.google.gson.JsonSyntaxException; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.internal.LazilyParsedNumber; import com.google.gson.internal.NumberLimits; import com.google.gson.internal.TroubleshootingGuide; 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.math.BigDecimal; import java.math.BigInteger; import java.net.InetAddress; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Calendar; import java.util.Currency; import java.util.GregorianCalendar; import java.util.List; import java.util.Locale; import java.util.Objects; 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; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLongArray; /** * Type adapters for basic types. More complex adapters exist as separate classes in the enclosing * package. */ public final class TypeAdapters { private TypeAdapters() { throw new UnsupportedOperationException(); } @SuppressWarnings("rawtypes") public static final TypeAdapter CLASS = new TypeAdapter() { @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?" + "\nSee " + TroubleshootingGuide.createUrl("java-lang-class-unsupported")); } @Override public Class read(JsonReader in) throws IOException { throw new UnsupportedOperationException( "Attempted to deserialize a java.lang.Class. Forgot to register a type adapter?" + "\nSee " + TroubleshootingGuide.createUrl("java-lang-class-unsupported")); } }.nullSafe(); public static final TypeAdapterFactory CLASS_FACTORY = newFactory(Class.class, CLASS); public static final TypeAdapter BIT_SET = new TypeAdapter() { @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 = new TypeAdapter() { @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_AS_STRING = new TypeAdapter() { @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 BYTE = new TypeAdapter() { @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 { if (value == null) { out.nullValue(); } else { out.value(value.byteValue()); } } }; public static final TypeAdapterFactory BYTE_FACTORY = newFactory(byte.class, Byte.class, BYTE); public static final TypeAdapter SHORT = new TypeAdapter() { @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 { if (value == null) { out.nullValue(); } else { out.value(value.shortValue()); } } }; public static final TypeAdapterFactory SHORT_FACTORY = newFactory(short.class, Short.class, SHORT); public static final TypeAdapter INTEGER = new TypeAdapter() { @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 { if (value == null) { out.nullValue(); } else { out.value(value.intValue()); } } }; public static final TypeAdapterFactory INTEGER_FACTORY = newFactory(int.class, Integer.class, INTEGER); public static final TypeAdapter ATOMIC_INTEGER = new TypeAdapter() { @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 TypeAdapter atomicLongAdapter(TypeAdapter longAdapter) { Objects.requireNonNull(longAdapter); return new TypeAdapter() { @Override public AtomicLong read(JsonReader in) throws IOException { Number value = longAdapter.read(in); return new AtomicLong(value.longValue()); } @Override public void write(JsonWriter out, AtomicLong value) throws IOException { longAdapter.write(out, value.get()); } }.nullSafe(); } public static final TypeAdapter ATOMIC_BOOLEAN = new TypeAdapter() { @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 ATOMIC_INTEGER_ARRAY = new TypeAdapter() { @Override public AtomicIntegerArray read(JsonReader in) throws IOException { List 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 TypeAdapter atomicLongArrayAdapter( TypeAdapter longAdapter) { Objects.requireNonNull(longAdapter); return new TypeAdapter() { @Override public AtomicLongArray read(JsonReader in) throws IOException { List 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; } @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(); } }.nullSafe(); } public static final TypeAdapter LONG = new TypeAdapter() { @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 { if (value == null) { out.nullValue(); } else { out.value(value.longValue()); } } }; public static final TypeAdapter LONG_AS_STRING = new TypeAdapter() { @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 class FloatAdapter extends TypeAdapter { private final boolean strict; FloatAdapter(boolean strict) { this.strict = strict; } @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(); if (strict) { checkValidFloatingPoint(floatValue); } // For backward compatibility don't call `JsonWriter.value(float)` because that method has // been newly added and not all custom JsonWriter implementations might override it yet Number floatNumber = value instanceof Float ? value : floatValue; out.value(floatNumber); } } private static class DoubleAdapter extends TypeAdapter { private final boolean strict; DoubleAdapter(boolean strict) { this.strict = strict; } @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(); if (strict) { checkValidFloatingPoint(doubleValue); } out.value(doubleValue); } } private 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."); } } public static final TypeAdapter FLOAT = new FloatAdapter(false); public static final TypeAdapter FLOAT_STRICT = new FloatAdapter(true); public static final TypeAdapter DOUBLE = new DoubleAdapter(false); public static final TypeAdapter DOUBLE_STRICT = new DoubleAdapter(true); public static final TypeAdapter CHARACTER = new TypeAdapter() { @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 = new TypeAdapter() { @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 BIG_DECIMAL = new TypeAdapter() { @Override public BigDecimal read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } String s = in.nextString(); try { return NumberLimits.parseBigDecimal(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 TypeAdapterFactory BIG_DECIMAL_FACTORY = newFactory(BigDecimal.class, BIG_DECIMAL); public static final TypeAdapter BIG_INTEGER = new TypeAdapter() { @Override public BigInteger read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } String s = in.nextString(); try { return NumberLimits.parseBigInteger(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 TypeAdapterFactory BIG_INTEGER_FACTORY = newFactory(BigInteger.class, BIG_INTEGER); public static final TypeAdapter LAZILY_PARSED_NUMBER = new TypeAdapter() { // 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 LAZILY_PARSED_NUMBER_FACTORY = newFactory(LazilyParsedNumber.class, LAZILY_PARSED_NUMBER); public static final TypeAdapterFactory STRING_FACTORY = newFactory(String.class, STRING); public static final TypeAdapter STRING_BUILDER = new TypeAdapter() { @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 STRING_BUFFER = new TypeAdapter() { @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 = new TypeAdapter() { @Override public URL read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } String nextString = in.nextString(); return nextString.equals("null") ? 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 = new TypeAdapter() { @Override public URI read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } try { String nextString = in.nextString(); return nextString.equals("null") ? 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 INET_ADDRESS = new TypeAdapter() { @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 // For compatibility, we use InetAddress.getByName rather than the possibly-better // .getAllByName @SuppressWarnings("AddressSelection") InetAddress addr = InetAddress.getByName(in.nextString()); return addr; } @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 = new TypeAdapter() { @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 = new TypeAdapter() { @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); /** * An abstract {@link TypeAdapter} for classes whose JSON serialization consists of a fixed set of * integer fields. That is the case for {@link Calendar} and the legacy serialization of various * {@code java.time} types. */ abstract static class IntegerFieldsTypeAdapter extends TypeAdapter { private final List fields; IntegerFieldsTypeAdapter(String... fields) { this.fields = Arrays.asList(fields); } abstract T create(long[] values); abstract long[] integerValues(T t); @Override public T read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } in.beginObject(); long[] values = new long[fields.size()]; while (in.peek() != JsonToken.END_OBJECT) { String name = in.nextName(); int index = fields.indexOf(name); if (index >= 0) { values[index] = in.nextLong(); } else { in.skipValue(); } } in.endObject(); return create(values); } @Override public void write(JsonWriter out, T value) throws IOException { if (value == null) { out.nullValue(); return; } out.beginObject(); long[] values = integerValues(value); for (int i = 0; i < fields.size(); i++) { out.name(fields.get(i)); out.value(values[i]); } out.endObject(); } } public static final TypeAdapter CALENDAR = new IntegerFieldsTypeAdapter( "year", "month", "dayOfMonth", "hourOfDay", "minute", "second") { @Override Calendar create(long[] values) { return new GregorianCalendar( toIntExact(values[0]), toIntExact(values[1]), toIntExact(values[2]), toIntExact(values[3]), toIntExact(values[4]), toIntExact(values[5])); } @Override long[] integerValues(Calendar calendar) { return new long[] { calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND) }; } }; // TODO: update this when we are on at least Android API Level 24. private static int toIntExact(long x) { int i = (int) x; if (i != x) { throw new IllegalArgumentException("Too big for an int: " + x); } return i; } public static final TypeAdapterFactory CALENDAR_FACTORY = newFactoryForMultipleTypes(Calendar.class, GregorianCalendar.class, CALENDAR); public static final TypeAdapter LOCALE = new TypeAdapter() { @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 JSON_ELEMENT = JsonElementTypeAdapter.ADAPTER; public static final TypeAdapterFactory JSON_ELEMENT_FACTORY = newTypeHierarchyFactory(JsonElement.class, JSON_ELEMENT); public static final TypeAdapterFactory ENUM_FACTORY = EnumTypeAdapter.FACTORY; interface FactorySupplier { TypeAdapterFactory get(); } public static TypeAdapterFactory javaTimeTypeAdapterFactory() { try { Class javaTimeTypeAdapterFactoryClass = Class.forName("com.google.gson.internal.bind.JavaTimeTypeAdapters"); FactorySupplier supplier = (FactorySupplier) javaTimeTypeAdapterFactoryClass.getDeclaredConstructor().newInstance(); return supplier.get(); } catch (ReflectiveOperationException | LinkageError e) { return null; } } @SuppressWarnings("TypeParameterNaming") public static TypeAdapterFactory newFactory( TypeToken type, TypeAdapter typeAdapter) { return new TypeAdapterFactory() { @SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal @Override public TypeAdapter create(Gson gson, TypeToken typeToken) { return typeToken.equals(type) ? (TypeAdapter) typeAdapter : null; } }; } @SuppressWarnings("TypeParameterNaming") public static TypeAdapterFactory newFactory(Class type, TypeAdapter typeAdapter) { return new TypeAdapterFactory() { @SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal @Override public TypeAdapter create(Gson gson, TypeToken typeToken) { return typeToken.getRawType() == type ? (TypeAdapter) typeAdapter : null; } @Override public String toString() { return "Factory[type=" + type.getName() + ",adapter=" + typeAdapter + "]"; } }; } @SuppressWarnings("TypeParameterNaming") public static TypeAdapterFactory newFactory( Class unboxed, Class boxed, TypeAdapter typeAdapter) { return new TypeAdapterFactory() { @SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal @Override public TypeAdapter create(Gson gson, TypeToken typeToken) { Class rawType = typeToken.getRawType(); return (rawType == unboxed || rawType == boxed) ? (TypeAdapter) typeAdapter : null; } @Override public String toString() { return "Factory[type=" + boxed.getName() + "+" + unboxed.getName() + ",adapter=" + typeAdapter + "]"; } }; } @SuppressWarnings("TypeParameterNaming") public static TypeAdapterFactory newFactoryForMultipleTypes( Class base, Class sub, TypeAdapter typeAdapter) { return new TypeAdapterFactory() { @SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal @Override public TypeAdapter create(Gson gson, TypeToken typeToken) { Class rawType = typeToken.getRawType(); return (rawType == base || rawType == sub) ? (TypeAdapter) 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 TypeAdapterFactory newTypeHierarchyFactory( Class clazz, TypeAdapter typeAdapter) { return new TypeAdapterFactory() { @SuppressWarnings("unchecked") @Override public TypeAdapter create(Gson gson, TypeToken typeToken) { Class requestedType = typeToken.getRawType(); if (!clazz.isAssignableFrom(requestedType)) { return null; } return (TypeAdapter) new TypeAdapter() { @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 + "]"; } }; } } ================================================ FILE: gson/src/main/java/com/google/gson/internal/bind/util/ISO8601Utils.java ================================================ /* * 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.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 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 this specification */ // Date parsing code from Jackson databind ISO8601Utils.java // https://github.com/FasterXML/jackson-databind/blob/2.8/src/main/java/com/fasterxml/jackson/databind/util/ISO8601Utils.java @SuppressWarnings("MemberName") // legacy class name public class ISO8601Utils { private 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; // always use 0 otherwise returned date will include millis of current time int milliseconds = 0; // 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 (timezoneOffset.equals("+0000") || timezoneOffset.equals("+00:00")) { 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 | 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(); } } ================================================ FILE: gson/src/main/java/com/google/gson/internal/package-info.java ================================================ /* * 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. */ /** * 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 */ @com.google.errorprone.annotations.CheckReturnValue package com.google.gson.internal; ================================================ FILE: gson/src/main/java/com/google/gson/internal/reflect/ReflectionHelper.java ================================================ /* * 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.internal.reflect; import com.google.gson.JsonIOException; import com.google.gson.internal.GsonBuildConfig; import com.google.gson.internal.TroubleshootingGuide; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; public class ReflectionHelper { private static final RecordHelper RECORD_HELPER; static { RecordHelper instance; try { // Try to construct the RecordSupportedHelper, if this fails, records are not supported on // this JVM. instance = new RecordSupportedHelper(); } catch (ReflectiveOperationException e) { instance = new RecordNotSupportedHelper(); } RECORD_HELPER = instance; } private ReflectionHelper() {} private static String getInaccessibleTroubleshootingSuffix(Exception e) { // Class was added in Java 9, therefore cannot use instanceof if (e.getClass().getName().equals("java.lang.reflect.InaccessibleObjectException")) { String message = e.getMessage(); String troubleshootingId = message != null && message.contains("to module com.google.gson") ? "reflection-inaccessible-to-module-gson" : "reflection-inaccessible"; return "\nSee " + TroubleshootingGuide.createUrl(troubleshootingId); } return ""; } /** * Internal implementation of making an {@link AccessibleObject} accessible. * * @param object the object that {@link AccessibleObject#setAccessible(boolean)} should be called * on. * @throws JsonIOException if making the object accessible fails */ public static void makeAccessible(AccessibleObject object) throws JsonIOException { try { object.setAccessible(true); } catch (Exception exception) { String description = getAccessibleObjectDescription(object, false); throw new JsonIOException( "Failed making " + description + " accessible; either increase its visibility" + " or write a custom TypeAdapter for its declaring type." + getInaccessibleTroubleshootingSuffix(exception), exception); } } /** * Returns a short string describing the {@link AccessibleObject} in a human-readable way. The * result is normally shorter than {@link AccessibleObject#toString()} because it omits modifiers * (e.g. {@code final}) and uses simple names for constructor and method parameter types. * * @param object object to describe * @param uppercaseFirstLetter whether the first letter of the description should be uppercased */ public static String getAccessibleObjectDescription( AccessibleObject object, boolean uppercaseFirstLetter) { String description; if (object instanceof Field) { description = "field '" + fieldToString((Field) object) + "'"; } else if (object instanceof Method) { Method method = (Method) object; StringBuilder methodSignatureBuilder = new StringBuilder(method.getName()); appendExecutableParameters(method, methodSignatureBuilder); String methodSignature = methodSignatureBuilder.toString(); description = "method '" + method.getDeclaringClass().getName() + "#" + methodSignature + "'"; } else if (object instanceof Constructor) { description = "constructor '" + constructorToString((Constructor) object) + "'"; } else { description = " " + object.toString(); } if (uppercaseFirstLetter && Character.isLowerCase(description.charAt(0))) { description = Character.toUpperCase(description.charAt(0)) + description.substring(1); } return description; } /** Creates a string representation for a field, omitting modifiers and the field type. */ public static String fieldToString(Field field) { return field.getDeclaringClass().getName() + "#" + field.getName(); } /** * Creates a string representation for a constructor. E.g.: {@code java.lang.String(char[], int, * int)} */ public static String constructorToString(Constructor constructor) { StringBuilder stringBuilder = new StringBuilder(constructor.getDeclaringClass().getName()); appendExecutableParameters(constructor, stringBuilder); return stringBuilder.toString(); } // Ideally parameter type would be java.lang.reflect.Executable, but that was added // in Android API level 26 private static void appendExecutableParameters( AccessibleObject executable, StringBuilder stringBuilder) { stringBuilder.append('('); Class[] parameters = (executable instanceof Method) ? ((Method) executable).getParameterTypes() : ((Constructor) executable).getParameterTypes(); for (int i = 0; i < parameters.length; i++) { if (i > 0) { stringBuilder.append(", "); } stringBuilder.append(parameters[i].getSimpleName()); } stringBuilder.append(')'); } public static boolean isStatic(Class clazz) { return Modifier.isStatic(clazz.getModifiers()); } /** Returns whether the class is anonymous or a non-static local class. */ public static boolean isAnonymousOrNonStaticLocal(Class clazz) { return !isStatic(clazz) && (clazz.isAnonymousClass() || clazz.isLocalClass()); } /** * 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 increase 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() + getInaccessibleTroubleshootingSuffix(exception); } } /** If records are supported on the JVM, this is equivalent to a call to Class.isRecord() */ public static boolean isRecord(Class raw) { return RECORD_HELPER.isRecord(raw); } public static String[] getRecordComponentNames(Class raw) { return RECORD_HELPER.getRecordComponentNames(raw); } /** Looks up the record accessor method that corresponds to the given record field */ public static Method getAccessor(Class raw, Field field) { return RECORD_HELPER.getAccessor(raw, field); } public static Constructor getCanonicalRecordConstructor(Class raw) { return RECORD_HELPER.getCanonicalRecordConstructor(raw); } 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); } private static RuntimeException createExceptionForRecordReflectionException( ReflectiveOperationException exception) { throw new RuntimeException( "Unexpected ReflectiveOperationException occurred" + " (Gson " + GsonBuildConfig.VERSION + ")." + " To support Java records, reflection is utilized to read out information" + " about records. All these invocations happens after it is established" + " that records exist in the JVM. This exception is unexpected behavior.", exception); } /** Internal abstraction over reflection when Records are supported. */ private abstract static class RecordHelper { abstract boolean isRecord(Class clazz); abstract String[] getRecordComponentNames(Class clazz); abstract Constructor getCanonicalRecordConstructor(Class raw); abstract Method getAccessor(Class raw, Field field); } private static class RecordSupportedHelper extends RecordHelper { private final Method isRecord; private final Method getRecordComponents; private final Method getName; private final Method getType; private RecordSupportedHelper() throws NoSuchMethodException, ClassNotFoundException { isRecord = Class.class.getMethod("isRecord"); getRecordComponents = Class.class.getMethod("getRecordComponents"); Class classRecordComponent = Class.forName("java.lang.reflect.RecordComponent"); getName = classRecordComponent.getMethod("getName"); getType = classRecordComponent.getMethod("getType"); } @Override boolean isRecord(Class raw) { try { return (boolean) isRecord.invoke(raw); } catch (ReflectiveOperationException e) { throw createExceptionForRecordReflectionException(e); } } @Override String[] getRecordComponentNames(Class raw) { try { Object[] recordComponents = (Object[]) getRecordComponents.invoke(raw); String[] componentNames = new String[recordComponents.length]; for (int i = 0; i < recordComponents.length; i++) { componentNames[i] = (String) getName.invoke(recordComponents[i]); } return componentNames; } catch (ReflectiveOperationException e) { throw createExceptionForRecordReflectionException(e); } } @Override public Constructor getCanonicalRecordConstructor(Class raw) { try { Object[] recordComponents = (Object[]) getRecordComponents.invoke(raw); Class[] recordComponentTypes = new Class[recordComponents.length]; for (int i = 0; i < recordComponents.length; i++) { recordComponentTypes[i] = (Class) getType.invoke(recordComponents[i]); } // Uses getDeclaredConstructor because implicit constructor has same visibility as record // and might therefore not be public return raw.getDeclaredConstructor(recordComponentTypes); } catch (ReflectiveOperationException e) { throw createExceptionForRecordReflectionException(e); } } @Override public Method getAccessor(Class raw, Field field) { try { // Records consists of record components, each with a unique name, a corresponding field and // accessor method with the same name. Ref.: // https://docs.oracle.com/javase/specs/jls/se17/html/jls-8.html#jls-8.10.3 return raw.getMethod(field.getName()); } catch (ReflectiveOperationException e) { throw createExceptionForRecordReflectionException(e); } } } /** Instance used when records are not supported */ private static class RecordNotSupportedHelper extends RecordHelper { @Override boolean isRecord(Class clazz) { return false; } @Override String[] getRecordComponentNames(Class clazz) { throw new UnsupportedOperationException( "Records are not supported on this JVM, this method should not be called"); } @Override Constructor getCanonicalRecordConstructor(Class raw) { throw new UnsupportedOperationException( "Records are not supported on this JVM, this method should not be called"); } @Override public Method getAccessor(Class raw, Field field) { throw new UnsupportedOperationException( "Records are not supported on this JVM, this method should not be called"); } } } ================================================ FILE: gson/src/main/java/com/google/gson/internal/sql/SqlDateTypeAdapter.java ================================================ /* * 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; import java.util.TimeZone; /** * 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. */ @SuppressWarnings("JavaUtilDate") final class SqlDateTypeAdapter extends TypeAdapter { static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() { @SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal @Override public TypeAdapter create(Gson gson, TypeToken typeToken) { return typeToken.getRawType() == java.sql.Date.class ? (TypeAdapter) 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(); synchronized (this) { TimeZone originalTimeZone = format.getTimeZone(); // Save the original time zone try { Date 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); } finally { format.setTimeZone(originalTimeZone); // Restore the original time zone after parsing } } } @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); } } ================================================ FILE: gson/src/main/java/com/google/gson/internal/sql/SqlTimeTypeAdapter.java ================================================ /* * 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; import java.util.TimeZone; /** * 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. */ @SuppressWarnings("JavaUtilDate") final class SqlTimeTypeAdapter extends TypeAdapter

If {@link #SUPPORTS_SQL_TYPES} is {@code true}, all other constants of this class will be * non-{@code null} and {@link #SQL_TYPE_FACTORIES} will contain the SQL type adapter factories. * However, if it is {@code false} all other constants will be {@code null} and {@link * #SQL_TYPE_FACTORIES} will be an empty list, and there will be no support for {@code java.sql} * types. */ @SuppressWarnings("JavaUtilDate") 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 DATE_DATE_TYPE; public static final DateType TIMESTAMP_DATE_TYPE; public static final TypeAdapterFactory DATE_FACTORY; public static final TypeAdapterFactory TIME_FACTORY; public static final TypeAdapterFactory TIMESTAMP_FACTORY; public static final List SQL_TYPE_FACTORIES; 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.class) { @Override protected java.sql.Date deserialize(Date date) { return new java.sql.Date(date.getTime()); } }; TIMESTAMP_DATE_TYPE = new DateType(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; SQL_TYPE_FACTORIES = Collections.unmodifiableList( Arrays.asList(TIME_FACTORY, DATE_FACTORY, TIMESTAMP_FACTORY)); } else { DATE_DATE_TYPE = null; TIMESTAMP_DATE_TYPE = null; DATE_FACTORY = null; TIME_FACTORY = null; TIMESTAMP_FACTORY = null; SQL_TYPE_FACTORIES = Collections.emptyList(); } } private SqlTypesSupport() {} } ================================================ FILE: gson/src/main/java/com/google/gson/package-info.java ================================================ /* * 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. */ /** * This package provides the {@link com.google.gson.Gson} class to convert Json to Java and * vice-versa. * *

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). * * @author Inderjeet Singh, Joel Leitch */ @com.google.errorprone.annotations.CheckReturnValue package com.google.gson; ================================================ FILE: gson/src/main/java/com/google/gson/reflect/TypeToken.java ================================================ /* * 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.GsonTypes; import com.google.gson.internal.TroubleshootingGuide; import java.lang.reflect.GenericArrayType; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.util.HashMap; import java.util.Map; import java.util.Objects; /** * 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. * *

For example, to create a type literal for {@code List}, you can create an empty * anonymous class: * *

{@code TypeToken> list = new TypeToken>() {};} * *

Capturing a type variable as type argument of an anonymous {@code TypeToken} subclass is not * allowed, for example {@code TypeToken>}. 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. This would give a false sense of type-safety at compile time and could lead to an * unexpected {@code ClassCastException} at runtime. * *

If the type arguments of the parameterized type are only available at runtime, for example * when you want to create a {@code List} based on a {@code Class} representing the element * type, the method {@link #getParameterized(Type, Type...)} can be used. * * @author Bob Lee * @author Sven Mawson * @author Jesse Wilson */ public class TypeToken { private final Class rawType; private final Type type; private final int hashCode; /** * Constructs a new type literal. Derives represented class from type parameter. * *

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, for * example: * *

{@code new TypeToken>() {}} * * @throws IllegalArgumentException If the anonymous {@code TypeToken} subclass captures a type * variable, for example {@code TypeToken>}. See the {@code TypeToken} class * documentation for more details. */ @SuppressWarnings("unchecked") protected TypeToken() { this.type = getTypeTokenTypeArgument(); this.rawType = (Class) GsonTypes.getRawType(type); this.hashCode = type.hashCode(); } /** Unsafe. Constructs a type literal manually. */ @SuppressWarnings("unchecked") private TypeToken(Type type) { this.type = GsonTypes.canonicalize(Objects.requireNonNull(type)); this.rawType = (Class) GsonTypes.getRawType(this.type); this.hashCode = this.type.hashCode(); } private static boolean isCapturingTypeVariablesForbidden() { return !Objects.equals(System.getProperty("gson.allowCapturingTypeVariables"), "true"); } /** * Verifies that {@code this} is an instance of a direct subclass of TypeToken and returns the * type argument for {@code T} in {@link GsonTypes#canonicalize canonical form}. */ private Type getTypeTokenTypeArgument() { Type superclass = getClass().getGenericSuperclass(); if (superclass instanceof ParameterizedType) { ParameterizedType parameterized = (ParameterizedType) superclass; if (parameterized.getRawType() == TypeToken.class) { Type typeArgument = GsonTypes.canonicalize(parameterized.getActualTypeArguments()[0]); if (isCapturingTypeVariablesForbidden()) { verifyNoTypeVariable(typeArgument); } return typeArgument; } } // 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." + "\nSee " + TroubleshootingGuide.createUrl("type-token-raw")); } // User created subclass of subclass of TypeToken throw new IllegalStateException("Must only create direct subclasses of TypeToken"); } private static void verifyNoTypeVariable(Type type) { if (type instanceof TypeVariable) { TypeVariable typeVariable = (TypeVariable) type; throw new IllegalArgumentException( "TypeToken type argument must not contain a type variable; captured type variable " + typeVariable.getName() + " declared by " + typeVariable.getGenericDeclaration() + "\nSee " + TroubleshootingGuide.createUrl("typetoken-type-variable")); } else if (type instanceof GenericArrayType) { verifyNoTypeVariable(((GenericArrayType) type).getGenericComponentType()); } else if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; Type ownerType = parameterizedType.getOwnerType(); if (ownerType != null) { verifyNoTypeVariable(ownerType); } for (Type typeArgument : parameterizedType.getActualTypeArguments()) { verifyNoTypeVariable(typeArgument); } } else if (type instanceof WildcardType) { WildcardType wildcardType = (WildcardType) type; for (Type bound : wildcardType.getLowerBounds()) { verifyNoTypeVariable(bound); } for (Type bound : wildcardType.getUpperBounds()) { verifyNoTypeVariable(bound); } } else if (type == null) { // Occurs in Eclipse IDE and certain Java versions (e.g. Java 11.0.18) when capturing type // variable declared by method of local class, see // https://github.com/eclipse-jdt/eclipse.jdt.core/issues/975 throw new IllegalArgumentException( "TypeToken captured `null` as type argument; probably a compiler / runtime bug"); } } /** Returns the raw (non-generic) type for this type. */ public final Class 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(GsonTypes.getRawType(from)); } else if (type instanceof ParameterizedType) { return isAssignableFrom(from, (ParameterizedType) type, new HashMap()); } else if (type instanceof GenericArrayType) { return rawType.isAssignableFrom(GsonTypes.getRawType(from)) && isAssignableFrom(from, (GenericArrayType) type); } else { throw buildUnsupportedTypeException( 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()); } // 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 typeVarMap) { if (from == null) { return false; } if (to.equals(from)) { return true; } // First figure out the class and any type information. Class clazz = GsonTypes.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 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 IllegalArgumentException buildUnsupportedTypeException( Type token, Class... expected) { // Build exception message StringBuilder exceptionMessage = new StringBuilder("Unsupported type, expected one of: "); for (Class clazz : expected) { exceptionMessage.append(clazz.getName()).append(", "); } exceptionMessage .append("but got: ") .append(token.getClass().getName()) .append(", for type token: ") .append(token.toString()); return new IllegalArgumentException(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 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 && GsonTypes.equals(type, ((TypeToken) o).type); } @Override public final String toString() { return GsonTypes.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 TypeToken get(Class type) { return new TypeToken<>(type); } /** * Gets a type literal for the parameterized type represented by applying {@code typeArguments} to * {@code rawType}. This is mainly intended for situations where the type arguments are not * available at compile time. The following example shows how a type token for {@code Map} * can be created: * *

{@code
   * Class keyClass = ...;
   * Class valueClass = ...;
   * TypeToken mapTypeToken = TypeToken.getParameterized(Map.class, keyClass, valueClass);
   * }
* * As seen here the result is a {@code TypeToken}; this method cannot provide any type-safety, * and care must be taken to pass in the correct number of type arguments. * *

If {@code rawType} is a non-generic class and no type arguments are provided, this method * simply delegates to {@link #get(Class)} and creates a {@code TypeToken(Class)}. * * @throws IllegalArgumentException If {@code rawType} is not of type {@code Class}, or if the * type arguments are invalid for the raw type */ public static TypeToken getParameterized(Type rawType, Type... typeArguments) { Objects.requireNonNull(rawType); Objects.requireNonNull(typeArguments); // Perform basic validation here because this is the only public API where users // can create malformed parameterized types if (!(rawType instanceof Class)) { // See also https://bugs.openjdk.org/browse/JDK-8250659 throw new IllegalArgumentException("rawType must be of type Class, but was " + rawType); } Class rawClass = (Class) rawType; TypeVariable[] typeVariables = rawClass.getTypeParameters(); int expectedArgsCount = typeVariables.length; int actualArgsCount = typeArguments.length; if (actualArgsCount != expectedArgsCount) { throw new IllegalArgumentException( rawClass.getName() + " requires " + expectedArgsCount + " type arguments, but got " + actualArgsCount); } // For legacy reasons create a TypeToken(Class) if the type is not generic if (typeArguments.length == 0) { return get(rawClass); } // Check for this here to avoid misleading exception thrown by ParameterizedTypeImpl if (GsonTypes.requiresOwnerType(rawType)) { throw new IllegalArgumentException( "Raw type " + rawClass.getName() + " is not supported because it requires specifying an owner type"); } for (int i = 0; i < expectedArgsCount; i++) { Type typeArgument = Objects.requireNonNull(typeArguments[i], "Type argument must not be null"); Class rawTypeArgument = GsonTypes.getRawType(typeArgument); TypeVariable typeVariable = typeVariables[i]; for (Type bound : typeVariable.getBounds()) { Class rawBound = GsonTypes.getRawType(bound); if (!rawBound.isAssignableFrom(rawTypeArgument)) { throw new IllegalArgumentException( "Type argument " + typeArgument + " does not satisfy bounds for type variable " + typeVariable + " declared by " + rawType); } } } return new TypeToken<>(GsonTypes.newParameterizedTypeWithOwner(null, rawClass, 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<>(GsonTypes.arrayOf(componentType)); } } ================================================ FILE: gson/src/main/java/com/google/gson/reflect/package-info.java ================================================ /* * 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. */ /** * This package provides utility classes for finding type information for generic types. * * @author Inderjeet Singh, Joel Leitch */ @com.google.errorprone.annotations.CheckReturnValue package com.google.gson.reflect; ================================================ FILE: gson/src/main/java/com/google/gson/stream/JsonReader.java ================================================ /* * 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.Strictness; import com.google.gson.internal.JsonReaderInternalAccess; import com.google.gson.internal.TroubleshootingGuide; 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; import java.util.Objects; /** * Reads a JSON (RFC 8259) 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. * *

Parsing JSON

* * To create a recursive descent parser for your own JSON streams, first create an entry point * method that creates a {@code JsonReader}. * *

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. * *

    *
  • Within array handling 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}. *
  • Within object handling 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}. *
* *

When a nested object or array is encountered, delegate to the corresponding handler method. * *

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. * *

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()}. * *

Configuration

* * The behavior of this reader can be customized with the following methods: * *
    *
  • {@link #setStrictness(Strictness)}, the default is {@link Strictness#LEGACY_STRICT} *
  • {@link #setNestingLimit(int)}, the default is {@value #DEFAULT_NESTING_LIMIT} *
* * The default configuration of {@code JsonReader} instances used internally by the {@link * com.google.gson.Gson} class differs, and can be adjusted with the various {@link * com.google.gson.GsonBuilder} methods. * *

Example

* * Suppose we'd like to parse a stream of messages such as the following: * *
{@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
 *     }
 *   }
 * ]
 * }
* * This code implements the parser for the above structure: * *
{@code
 * public List readJsonStream(InputStream in) throws IOException {
 *   JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
 *   try {
 *     return readMessagesArray(reader);
 *   } finally {
 *     reader.close();
 *   }
 * }
 *
 * public List readMessagesArray(JsonReader reader) throws IOException {
 *   List 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 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 readDoublesArray(JsonReader reader) throws IOException {
 *   List 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);
 * }
 * }
* *

Number Handling

* * 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. * *

Non-Execute Prefix

* * Web servers that serve private data using JSON may be vulnerable to Cross-site request * forgery attacks. In such an attack, a malicious site gains access to a private JSON file by * executing it with an HTML {@code "; String result = gson.toJson(target); assertThat(result).isNotEqualTo('"' + target + '"'); gson = new GsonBuilder().disableHtmlEscaping().create(); result = gson.toJson(target); assertThat(result).isEqualTo('"' + target + '"'); } @Test public void testDeserializePrimitiveWrapperAsObjectField() { String json = "{i:10}"; ClassWithIntegerField target = gson.fromJson(json, ClassWithIntegerField.class); assertThat(target.i).isEqualTo(10); } private static class ClassWithIntegerField { Integer i; } @Test public void testPrimitiveClassLiteral() { assertThat(gson.fromJson("1", int.class)).isEqualTo(1); assertThat(gson.fromJson(new StringReader("1"), int.class)).isEqualTo(1); assertThat(gson.fromJson(new JsonPrimitive(1), int.class)).isEqualTo(1); } @Test public void testDeserializeJsonObjectAsLongPrimitive() { assertThrows(JsonSyntaxException.class, () -> gson.fromJson("{'abc':1}", long.class)); } @Test public void testDeserializeJsonArrayAsLongWrapper() { assertThrows(JsonSyntaxException.class, () -> gson.fromJson("[1,2,3]", Long.class)); } @Test public void testDeserializeJsonArrayAsInt() { assertThrows(JsonSyntaxException.class, () -> gson.fromJson("[1, 2, 3, 4]", int.class)); } @Test public void testDeserializeJsonObjectAsInteger() { assertThrows(JsonSyntaxException.class, () -> gson.fromJson("{}", Integer.class)); } @Test public void testDeserializeJsonObjectAsShortPrimitive() { assertThrows(JsonSyntaxException.class, () -> gson.fromJson("{'abc':1}", short.class)); } @Test public void testDeserializeJsonArrayAsShortWrapper() { assertThrows(JsonSyntaxException.class, () -> gson.fromJson("['a','b']", Short.class)); } @Test public void testDeserializeJsonArrayAsDoublePrimitive() { assertThrows(JsonSyntaxException.class, () -> gson.fromJson("[1,2]", double.class)); } @Test public void testDeserializeJsonObjectAsDoubleWrapper() { assertThrows(JsonSyntaxException.class, () -> gson.fromJson("{'abc':1}", Double.class)); } @Test public void testDeserializeJsonObjectAsFloatPrimitive() { assertThrows(JsonSyntaxException.class, () -> gson.fromJson("{'abc':1}", float.class)); } @Test public void testDeserializeJsonArrayAsFloatWrapper() { assertThrows(JsonSyntaxException.class, () -> gson.fromJson("[1,2,3]", Float.class)); } @Test public void testDeserializeJsonObjectAsBytePrimitive() { assertThrows(JsonSyntaxException.class, () -> gson.fromJson("{'abc':1}", byte.class)); } @Test public void testDeserializeJsonArrayAsByteWrapper() { assertThrows(JsonSyntaxException.class, () -> gson.fromJson("[1,2,3,4]", Byte.class)); } @Test public void testDeserializeJsonObjectAsBooleanPrimitive() { assertThrows(JsonSyntaxException.class, () -> gson.fromJson("{'abc':1}", boolean.class)); } @Test public void testDeserializeJsonArrayAsBooleanWrapper() { assertThrows(JsonSyntaxException.class, () -> gson.fromJson("[1,2,3,4]", Boolean.class)); } @Test public void testDeserializeJsonArrayAsBigDecimal() { assertThrows(JsonSyntaxException.class, () -> gson.fromJson("[1,2,3,4]", BigDecimal.class)); } @Test public void testDeserializeJsonObjectAsBigDecimal() { assertThrows(JsonSyntaxException.class, () -> gson.fromJson("{'a':1}", BigDecimal.class)); } @Test public void testDeserializeJsonArrayAsBigInteger() { assertThrows(JsonSyntaxException.class, () -> gson.fromJson("[1,2,3,4]", BigInteger.class)); } @Test public void testDeserializeJsonObjectAsBigInteger() { assertThrows(JsonSyntaxException.class, () -> gson.fromJson("{'c':2}", BigInteger.class)); } @Test public void testDeserializeJsonArrayAsNumber() { assertThrows(JsonSyntaxException.class, () -> gson.fromJson("[1,2,3,4]", Number.class)); } @Test public void testDeserializeJsonObjectAsNumber() { assertThrows(JsonSyntaxException.class, () -> gson.fromJson("{'c':2}", Number.class)); } @Test public void testDeserializingDecimalPointValueZeroSucceeds() { assertThat(gson.fromJson("1.0", Integer.class)).isEqualTo(1); } @Test public void testDeserializingNonZeroDecimalPointValuesAsIntegerFails() { assertThrows(JsonSyntaxException.class, () -> gson.fromJson("1.02", Byte.class)); assertThrows(JsonSyntaxException.class, () -> gson.fromJson("1.02", Short.class)); assertThrows(JsonSyntaxException.class, () -> gson.fromJson("1.02", Integer.class)); assertThrows(JsonSyntaxException.class, () -> gson.fromJson("1.02", Long.class)); } @Test public void testDeserializingBigDecimalAsIntegerFails() { JsonSyntaxException e = assertThrows(JsonSyntaxException.class, () -> gson.fromJson("-122.08e-213", Integer.class)); assertThat(e) .hasCauseThat() .hasMessageThat() .isEqualTo("Expected an int but was -122.08e-213 at line 1 column 13 path $"); } @Test public void testDeserializingBigIntegerAsInteger() { String number = "12121211243123245845384534687435634558945453489543985435"; JsonSyntaxException e = assertThrows(JsonSyntaxException.class, () -> gson.fromJson(number, Integer.class)); assertThat(e) .hasCauseThat() .hasMessageThat() .isEqualTo("Expected an int but was " + number + " at line 1 column 57 path $"); } @Test public void testDeserializingBigIntegerAsLong() { String number = "12121211243123245845384534687435634558945453489543985435"; JsonSyntaxException e = assertThrows(JsonSyntaxException.class, () -> gson.fromJson(number, Long.class)); assertThat(e) .hasCauseThat() .hasMessageThat() .isEqualTo("Expected a long but was " + number + " at line 1 column 57 path $"); } @Test public void testValueVeryCloseToZeroIsZero() { assertThat(gson.fromJson("-122.08e-2132", byte.class)).isEqualTo(0); assertThat(gson.fromJson("-122.08e-2132", short.class)).isEqualTo(0); assertThat(gson.fromJson("-122.08e-2132", int.class)).isEqualTo(0); assertThat(gson.fromJson("-122.08e-2132", long.class)).isEqualTo(0); assertThat(gson.fromJson("-122.08e-2132", float.class)).isEqualTo(-0.0f); assertThat(gson.fromJson("-122.08e-2132", double.class)).isEqualTo(-0.0); assertThat(gson.fromJson("122.08e-2132", float.class)).isEqualTo(0.0f); assertThat(gson.fromJson("122.08e-2132", double.class)).isEqualTo(0.0); } @Test public void testDeserializingBigDecimalAsBigIntegerFails() { assertThrows(JsonSyntaxException.class, () -> gson.fromJson("-122.08e-213", BigInteger.class)); } @Test public void testDeserializingBigIntegerAsBigDecimal() { BigDecimal actual = gson.fromJson("12121211243123245845384534687435634558945453489543985435", BigDecimal.class); assertThat(actual.toPlainString()) .isEqualTo("12121211243123245845384534687435634558945453489543985435"); } @Test public void testStringsAsBooleans() { String json = "['true', 'false', 'TRUE', 'yes', '1']"; List deserialized = gson.fromJson(json, new TypeToken>() {}); assertThat(deserialized).isEqualTo(Arrays.asList(true, false, true, false, false)); } } ================================================ FILE: gson/src/test/java/com/google/gson/functional/PrintFormattingTest.java ================================================ /* * 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 com.google.common.truth.Truth.assertThat; 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 java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; /** * Functional tests for print formatting. * * @author Inderjeet Singh * @author Joel Leitch */ public class PrintFormattingTest { private Gson gson; @Before public void setUp() throws Exception { gson = new Gson(); } @Test 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); } @Test public void testJsonObjectWithNullValues() { JsonObject obj = new JsonObject(); obj.addProperty("field1", "value1"); obj.addProperty("field2", (String) null); String json = gson.toJson(obj); assertThat(json).contains("field1"); assertThat(json).doesNotContain("field2"); } @Test 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); assertThat(json).contains("field1"); assertThat(json).contains("field2"); } @SuppressWarnings("LoopOverCharArray") private static void assertContainsNoWhiteSpace(String str) { for (char c : str.toCharArray()) { assertThat(Character.isWhitespace(c)).isFalse(); } } } ================================================ FILE: gson/src/test/java/com/google/gson/functional/RawSerializationTest.java ================================================ /* * 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 static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.util.Arrays; import java.util.Collection; import org.junit.Before; import org.junit.Test; /** * Unit tests to validate serialization of parameterized types without explicit types * * @author Inderjeet Singh */ public class RawSerializationTest { private Gson gson; @Before public void setUp() throws Exception { gson = new Gson(); } @Test public void testCollectionOfPrimitives() { Collection ints = Arrays.asList(1, 2, 3, 4, 5); String json = gson.toJson(ints); assertThat(json).isEqualTo("[1,2,3,4,5]"); } @Test public void testCollectionOfObjects() { Collection foos = Arrays.asList(new Foo(1), new Foo(2)); String json = gson.toJson(foos); assertThat(json).isEqualTo("[{\"b\":1},{\"b\":2}]"); } @Test public void testParameterizedObject() { Bar 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); assertThat(json).isEqualTo(expectedJson); // Ensure that serialization also works when the type is specified explicitly json = gson.toJson(bar, new TypeToken>() {}.getType()); assertThat(json).isEqualTo(expectedJson); } @Test public void testTwoLevelParameterizedObject() { Bar> 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); assertThat(json).isEqualTo(expectedJson); // Ensure that serialization also works when the type is specified explicitly json = gson.toJson(bar, new TypeToken>>() {}.getType()); assertThat(json).isEqualTo(expectedJson); } @Test public void testThreeLevelParameterizedObject() { Bar>> 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); assertThat(json).isEqualTo(expectedJson); // Ensure that serialization also works when the type is specified explicitly json = gson.toJson(bar, new TypeToken>>>() {}.getType()); assertThat(json).isEqualTo(expectedJson); } private static class Foo { @SuppressWarnings("unused") int b; Foo(int b) { this.b = b; } } private static class Bar { @SuppressWarnings("unused") T t; Bar(T t) { this.t = t; } } } ================================================ FILE: gson/src/test/java/com/google/gson/functional/ReadersWritersTest.java ================================================ /* * 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 com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import com.google.errorprone.annotations.CanIgnoreReturnValue; 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.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; import java.lang.reflect.Type; import java.util.Arrays; import java.util.Map; import org.junit.Before; import org.junit.Test; /** * Functional tests for the support of {@link Reader}s and {@link Writer}s. * * @author Inderjeet Singh * @author Joel Leitch */ public class ReadersWritersTest { private Gson gson; @Before public void setUp() throws Exception { gson = new Gson(); } @Test public void testWriterForSerialization() { Writer writer = new StringWriter(); BagOfPrimitives src = new BagOfPrimitives(); gson.toJson(src, writer); assertThat(writer.toString()).isEqualTo(src.getExpectedJson()); } @Test public void testReaderForDeserialization() { BagOfPrimitives expected = new BagOfPrimitives(); Reader json = new StringReader(expected.getExpectedJson()); BagOfPrimitives actual = gson.fromJson(json, BagOfPrimitives.class); assertThat(actual).isEqualTo(expected); } @Test public void testTopLevelNullObjectSerializationWithWriter() { StringWriter writer = new StringWriter(); gson.toJson(null, writer); assertThat(writer.toString()).isEqualTo("null"); } @Test public void testTopLevelNullObjectDeserializationWithReader() { StringReader reader = new StringReader("null"); Integer nullIntObject = gson.fromJson(reader, Integer.class); assertThat(nullIntObject).isNull(); } @Test public void testTopLevelNullObjectSerializationWithWriterAndSerializeNulls() { Gson gson = new GsonBuilder().serializeNulls().create(); StringWriter writer = new StringWriter(); gson.toJson(null, writer); assertThat(writer.toString()).isEqualTo("null"); } @Test public void testTopLevelNullObjectDeserializationWithReaderAndSerializeNulls() { Gson gson = new GsonBuilder().serializeNulls().create(); StringReader reader = new StringReader("null"); Integer nullIntObject = gson.fromJson(reader, Integer.class); assertThat(nullIntObject).isNull(); } @Test 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); assertThat(actualOne).isEqualTo("one"); String actualTwo = gson.fromJson(parser.next(), String.class); assertThat(actualTwo).isEqualTo("two"); } @Test 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); assertThat(actualOne.stringValue).isEqualTo("one"); BagOfPrimitives actualTwo = gson.fromJson(parser.next(), BagOfPrimitives.class); assertThat(actualTwo.stringValue).isEqualTo("two"); assertThat(parser.hasNext()).isFalse(); } @Test public void testTypeMismatchThrowsJsonSyntaxExceptionForStrings() { Type type = new TypeToken>() {}.getType(); var e = assertThrows(JsonSyntaxException.class, () -> gson.fromJson("true", type)); assertThat(e) .hasCauseThat() .hasMessageThat() .startsWith("Expected BEGIN_OBJECT but was BOOLEAN"); } @Test public void testTypeMismatchThrowsJsonSyntaxExceptionForReaders() { Type type = new TypeToken>() {}.getType(); var e = assertThrows( JsonSyntaxException.class, () -> gson.fromJson(new StringReader("true"), type)); assertThat(e) .hasCauseThat() .hasMessageThat() .startsWith("Expected BEGIN_OBJECT but was BOOLEAN"); } /** * Verifies that passing an {@link Appendable} which is not an instance of {@link Writer} to * {@code Gson.toJson} works correctly. */ @Test public void testToJsonAppendable() { class CustomAppendable implements Appendable { final StringBuilder stringBuilder = new StringBuilder(); int toStringCallCount = 0; @CanIgnoreReturnValue @Override public Appendable append(char c) throws IOException { stringBuilder.append(c); return this; } @CanIgnoreReturnValue @Override public Appendable append(CharSequence csq) throws IOException { if (csq == null) { csq = "null"; // Requirement by Writer.append } append(csq, 0, csq.length()); return this; } @CanIgnoreReturnValue @Override public Appendable append(CharSequence csq, int start, int end) throws IOException { if (csq == null) { csq = "null"; // Requirement by Writer.append } // According to doc, toString() must return string representation String s = csq.toString(); toStringCallCount++; stringBuilder.append(s, start, end); return this; } } CustomAppendable appendable = new CustomAppendable(); gson.toJson(Arrays.asList("test", 123, true), appendable); // Make sure CharSequence.toString() was called at least two times to verify that // CurrentWrite.cachedString is properly overwritten when char array changes assertThat(appendable.toStringCallCount).isAtLeast(2); assertThat(appendable.stringBuilder.toString()).isEqualTo("[\"test\",123,true]"); } } ================================================ FILE: gson/src/test/java/com/google/gson/functional/ReflectionAccessFilterTest.java ================================================ /* * Copyright (C) 2022 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.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; 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.io.File; import java.io.IOException; import java.io.Reader; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import org.junit.AssumptionViolatedException; 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 // Note: This test is rather brittle and depends on the JDK implementation var e = assertThrows( "Expected exception; test needs to be run with Java >= 9", JsonIOException.class, () -> gson.toJson(new File("a"))); assertThat(e) .hasMessageThat() .isEqualTo( "Field 'java.io.File#path' is not accessible and ReflectionAccessFilter does not" + " permit making it accessible. Register a TypeAdapter for the declaring type," + " adjust the access filter or increase the visibility of the element and its" + " declaring type."); } @Test public void testDontBlockAccessibleJava() throws ReflectiveOperationException { Gson gson = new GsonBuilder() .addReflectionAccessFilter(ReflectionAccessFilter.BLOCK_INACCESSIBLE_JAVA) .create(); // Serialization should succeed for classes with only public fields. // Not many JDK classes have mutable public fields, thank goodness, but java.awt.Point does. Class pointClass; try { pointClass = Class.forName("java.awt.Point"); } catch (ClassNotFoundException e) { // If not found then we don't have AWT and the rest of the test can be skipped. throw new AssumptionViolatedException("java.awt.Point not present", e); } Constructor pointConstructor = pointClass.getConstructor(int.class, int.class); Object point = pointConstructor.newInstance(1, 2); String json = gson.toJson(point); assertThat(json).isEqualTo("{\"x\":1,\"y\":2}"); } @Test public void testBlockInaccessibleJavaExtendingJdkClass() { Gson gson = new GsonBuilder() .addReflectionAccessFilter(ReflectionAccessFilter.BLOCK_INACCESSIBLE_JAVA) .create(); var e = assertThrows( "Expected exception; test needs to be run with Java >= 9", JsonIOException.class, () -> gson.toJson(new ClassExtendingJdkClass())); assertThat(e) .hasMessageThat() .isEqualTo( "Field 'java.io.Reader#lock' is not accessible and ReflectionAccessFilter does not" + " permit making it accessible. Register a TypeAdapter for the declaring type," + " adjust the access filter or increase the visibility of the element and its" + " declaring type."); } @Test public void testBlockAllJava() { Gson gson = new GsonBuilder().addReflectionAccessFilter(ReflectionAccessFilter.BLOCK_ALL_JAVA).create(); // Serialization should fail for any Java class without custom adapter var e = assertThrows(JsonIOException.class, () -> gson.toJson(Thread.currentThread())); assertThat(e) .hasMessageThat() .isEqualTo( "ReflectionAccessFilter does not permit using reflection for class java.lang.Thread." + " Register a TypeAdapter for this type or adjust the access filter."); } @Test public void testBlockAllJavaExtendingJdkClass() { Gson gson = new GsonBuilder().addReflectionAccessFilter(ReflectionAccessFilter.BLOCK_ALL_JAVA).create(); var e = assertThrows(JsonIOException.class, () -> gson.toJson(new ClassExtendingJdkClass())); assertThat(e) .hasMessageThat() .isEqualTo( "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."); } private static class ClassWithStaticField { @SuppressWarnings({"unused", "NonFinalStaticField"}) 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(); var e = assertThrows( "Expected exception; test needs to be run with Java >= 9", JsonIOException.class, () -> gson.toJson(new ClassWithStaticField())); assertThat(e) .hasMessageThat() .isEqualTo( "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, adjust the access" + " filter or increase the visibility of the element and its declaring type."); } private static class SuperTestClass {} private static class SubTestClass extends SuperTestClass { @SuppressWarnings("unused") int i = 1; } private static class OtherClass { @SuppressWarnings("unused") 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 var e = assertThrows(JsonIOException.class, () -> gson.toJson(new SuperTestClass())); assertThat(e) .hasMessageThat() .isEqualTo( "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."); // But registration order is reversed, so filter for SubTestClass allows reflection String json = gson.toJson(new SubTestClass()); assertThat(json).isEqualTo("{\"i\":1}"); // And unrelated class should not be affected json = gson.toJson(new OtherClass()); assertThat(json).isEqualTo("{\"i\":2}"); } 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 var e = assertThrows( "Expected exception; test needs to be run with Java >= 9", JsonIOException.class, () -> gson.toJson(new ExtendingClassWithPrivateField())); assertThat(e) .hasMessageThat() .isEqualTo( "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, adjust the access" + " filter or increase the visibility of the element and its declaring type."); Gson gson2 = 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 = gson2.toJson(new ExtendingClassWithPrivateField()); assertThat(json).isEqualTo("{\"i\":1}"); } 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(); var e = assertThrows( "Expected exception; test needs to be run with Java >= 9", JsonIOException.class, () -> gson.fromJson("{}", ClassWithPrivateNoArgsConstructor.class)); assertThat(e) .hasMessageThat() .isEqualTo( "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."); } private static class ClassWithoutNoArgsConstructor { String s; 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(); var e = assertThrows( JsonIOException.class, () -> gson.fromJson("{}", ClassWithoutNoArgsConstructor.class)); assertThat(e) .hasMessageThat() .isEqualTo( "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."); // But should not fail when custom TypeAdapter is specified Gson gson2 = gson.newBuilder() .registerTypeAdapter( ClassWithoutNoArgsConstructor.class, new TypeAdapter() { @Override public ClassWithoutNoArgsConstructor read(JsonReader in) throws IOException { in.skipValue(); return new ClassWithoutNoArgsConstructor("TypeAdapter"); } @Override public void write(JsonWriter out, ClassWithoutNoArgsConstructor value) { throw new AssertionError("Not needed for test"); } }) .create(); ClassWithoutNoArgsConstructor deserialized = gson2.fromJson("{}", ClassWithoutNoArgsConstructor.class); assertThat(deserialized.s).isEqualTo("TypeAdapter"); // But should not fail when custom InstanceCreator is specified gson2 = gsonBuilder .registerTypeAdapter( ClassWithoutNoArgsConstructor.class, new InstanceCreator() { @Override public ClassWithoutNoArgsConstructor createInstance(Type type) { return new ClassWithoutNoArgsConstructor("InstanceCreator"); } }) .create(); deserialized = gson2.fromJson("{}", ClassWithoutNoArgsConstructor.class); assertThat(deserialized.s).isEqualTo("InstanceCreator"); } /** * 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() { @Override public JsonElement serialize( OtherClass src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(123); } }) .create(); String json = gson.toJson(new OtherClass()); assertThat(json).isEqualTo("123"); // But deserialization should fail var e = assertThrows(JsonIOException.class, () -> gson.fromJson("{}", OtherClass.class)); assertThat(e) .hasMessageThat() .isEqualTo( "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."); } /** * 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); assertThat(deserialized.get(0)).isEqualTo(1.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); assertThat(deserialized.get(0)).isEqualTo(1.0); } /** * When trying to deserialize interface, an exception for the missing adapter 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(); var e = assertThrows(JsonIOException.class, () -> gson.fromJson("{}", Runnable.class)); assertThat(e) .hasMessageThat() .isEqualTo( "Interfaces can't be instantiated! Register an InstanceCreator or a TypeAdapter for" + " this type. Interface name: java.lang.Runnable"); } /** * Verifies that the predefined filter constants have meaningful {@code toString()} output to make * debugging easier. */ @Test public void testConstantsToString() throws Exception { List constantFields = new ArrayList<>(); for (Field f : ReflectionAccessFilter.class.getFields()) { // Only include ReflectionAccessFilter constants (in case any other fields are added in the // future) if (f.getType() == ReflectionAccessFilter.class) { constantFields.add(f); } } assertThat(constantFields).isNotEmpty(); for (Field f : constantFields) { Object constant = f.get(null); assertThat(constant.toString()).isEqualTo("ReflectionAccessFilter#" + f.getName()); } } } ================================================ FILE: gson/src/test/java/com/google/gson/functional/ReflectionAccessTest.java ================================================ /* * 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 static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import static org.junit.Assume.assumeTrue; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonIOException; import com.google.gson.JsonSyntaxException; 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()); } @SuppressWarnings("removal") // java.lang.SecurityManager deprecation in Java 17 @Test public void testRestrictiveSecurityManager() throws Exception { // Skip for newer Java versions where `System.setSecurityManager` is unsupported assumeTrue(Runtime.version().feature() <= 17); // Must use separate class loader, otherwise permission is not checked, see // Class.getDeclaredFields() Class clazz = loadClassWithDifferentClassLoader(ClassWithPrivateMembers.class); Permission accessDeclaredMembers = new RuntimePermission("accessDeclaredMembers"); 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(); // Getting reflection based adapter should fail var e = assertThrows(SecurityException.class, () -> gson.getAdapter(clazz)); assertThat(e).hasMessageThat().isEqualTo("Gson: no-member-access"); AtomicBoolean wasReadCalled = new AtomicBoolean(false); Gson gson2 = new GsonBuilder() .registerTypeAdapter( clazz, new TypeAdapter() { @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(); assertThat(gson2.toJson(null, clazz)).isEqualTo("\"custom-write\""); assertThat(gson2.fromJson("{}", clazz)).isNull(); assertThat(wasReadCalled.get()).isTrue(); } finally { System.setSecurityManager(original); } } private static JsonIOException assertInaccessibleException(String json, Class toDeserialize) { Gson gson = new Gson(); try { Object unused = gson.fromJson(json, toDeserialize); throw new AssertionError( "Missing exception; test has to be run with `--illegal-access=deny`"); } catch (JsonSyntaxException e) { throw new AssertionError( "Unexpected exception; test has to be run with `--illegal-access=deny`", e); } catch (JsonIOException expected) { assertThat(expected) .hasMessageThat() .endsWith( "\n" + "See https://github.com/google/gson/blob/main/Troubleshooting.md#reflection-inaccessible"); // Return exception for further assertions return expected; } } /** * Test serializing an instance of a non-accessible internal class, but where Gson supports * serializing one of its superinterfaces. * *

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. * *

See https://github.com/google/gson/issues/1875 */ @Test public void testSerializeInternalImplementationObject() { Gson gson = new Gson(); String json = gson.toJson(Collections.emptyList()); assertThat(json).isEqualTo("[]"); // But deserialization should fail Class internalClass = Collections.emptyList().getClass(); JsonIOException exception = assertInaccessibleException("[]", internalClass); // Don't check exact class name because it is a JDK implementation detail assertThat(exception).hasMessageThat().startsWith("Failed making constructor '"); assertThat(exception) .hasMessageThat() .contains( "' accessible; either increase its visibility or" + " write a custom InstanceCreator or TypeAdapter for its declaring type: "); } @Test public void testInaccessibleField() { JsonIOException exception = assertInaccessibleException("{}", Throwable.class); // Don't check exact field name because it is a JDK implementation detail assertThat(exception).hasMessageThat().startsWith("Failed making field 'java.lang.Throwable#"); assertThat(exception) .hasMessageThat() .contains( "' accessible; either increase its visibility or" + " write a custom TypeAdapter for its declaring type."); } } ================================================ FILE: gson/src/test/java/com/google/gson/functional/ReusedTypeVariablesFullyResolveTest.java ================================================ /* * Copyright (C) 2018 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.common.truth.Truth.assertThat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.Collection; import java.util.Iterator; import java.util.Set; import org.junit.Before; import org.junit.Test; /** * 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(); } // The instances were being unmarshaled as Strings instead of TestEnums @SuppressWarnings("ConstantConditions") @Test public void testGenericsPreservation() { TestEnumSetCollection withSet = gson.fromJson("{\"collection\":[\"ONE\",\"THREE\"]}", TestEnumSetCollection.class); Iterator iterator = withSet.collection.iterator(); assertThat(withSet).isNotNull(); assertThat(withSet.collection).isNotNull(); assertThat(withSet.collection).hasSize(2); TestEnum first = iterator.next(); TestEnum second = iterator.next(); assertThat(first).isInstanceOf(TestEnum.class); assertThat(second).isInstanceOf(TestEnum.class); } enum TestEnum { ONE, TWO, THREE } private static class TestEnumSetCollection extends SetCollection {} private static class SetCollection extends BaseCollection> {} private static class BaseCollection> { C collection; } } ================================================ FILE: gson/src/test/java/com/google/gson/functional/RuntimeTypeAdapterFactoryFunctionalTest.java ================================================ /* * 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 com.google.common.truth.Truth.assertThat; import com.google.errorprone.annotations.CanIgnoreReturnValue; 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; import java.io.IOException; import java.util.LinkedHashMap; import java.util.Map; import org.junit.Test; /** Functional tests for the RuntimeTypeAdapterFactory feature in extras. */ public final class RuntimeTypeAdapterFactoryFunctionalTest { 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)}. */ @Test public void testSubclassesAutomaticallySerialized() { Shape shape = new Circle(25); String json = gson.toJson(shape); shape = gson.fromJson(json, Shape.class); assertThat(((Circle) shape).radius).isEqualTo(25); shape = new Square(15); json = gson.toJson(shape); shape = gson.fromJson(json, Shape.class); assertThat(((Square) shape).side).isEqualTo(15); assertThat(shape.type).isEqualTo(ShapeType.SQUARE); } @JsonAdapter(Shape.JsonAdapterFactory.class) static class Shape { final ShapeType type; Shape(ShapeType type) { this.type = type; } private static final class JsonAdapterFactory extends RuntimeTypeAdapterFactory { 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 implements TypeAdapterFactory { private final Class baseType; private final String typeFieldName; private final Map> labelToSubtype = new LinkedHashMap<>(); private final Map, 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 for {@code baseType} using {@code typeFieldName} as the * type field name. Type field names are case sensitive. */ public static RuntimeTypeAdapterFactory of(Class 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 RuntimeTypeAdapterFactory of(Class 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. */ @CanIgnoreReturnValue public RuntimeTypeAdapterFactory registerSubtype(Class 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. */ @CanIgnoreReturnValue public RuntimeTypeAdapterFactory registerSubtype(Class type) { return registerSubtype(type, type.getSimpleName()); } @Override public TypeAdapter create(Gson gson, TypeToken type) { if (type.getRawType() != baseType) { return null; } Map> labelToDelegate = new LinkedHashMap<>(); Map, TypeAdapter> subtypeToDelegate = new LinkedHashMap<>(); for (Map.Entry> 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<>() { @Override public R read(JsonReader in) { 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 delegate = (TypeAdapter) 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 delegate = (TypeAdapter) 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 e : jsonObject.entrySet()) { clone.add(e.getKey(), e.getValue()); } jsonObject = clone; } Streams.write(jsonObject, out); } }; } } } ================================================ FILE: gson/src/test/java/com/google/gson/functional/SecurityTest.java ================================================ /* * 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 com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.common.TestTypes.BagOfPrimitives; import org.junit.Before; import org.junit.Test; /** * Tests for security-related aspects of Gson * * @author Inderjeet Singh */ public class SecurityTest { /** Keep this in sync with Gson.JSON_NON_EXECUTABLE_PREFIX */ private static final String JSON_NON_EXECUTABLE_PREFIX = ")]}'\n"; private GsonBuilder gsonBuilder; @Before public void setUp() throws Exception { gsonBuilder = new GsonBuilder(); } @Test public void testNonExecutableJsonSerialization() { Gson gson = gsonBuilder.generateNonExecutableJson().create(); String json = gson.toJson(new BagOfPrimitives()); assertThat(json) .isEqualTo( JSON_NON_EXECUTABLE_PREFIX + "{\"longValue\":0,\"intValue\":0,\"booleanValue\":false,\"stringValue\":\"\"}"); } @Test public void testNonExecutableJsonDeserialization() { String json = JSON_NON_EXECUTABLE_PREFIX + "{longValue:1}"; Gson gson = gsonBuilder.create(); BagOfPrimitives target = gson.fromJson(json, BagOfPrimitives.class); assertThat(target.longValue).isEqualTo(1); } @Test public void testJsonWithNonExectuableTokenSerialization() { Gson gson = gsonBuilder.generateNonExecutableJson().create(); String json = gson.toJson(JSON_NON_EXECUTABLE_PREFIX); assertThat(json).isEqualTo(JSON_NON_EXECUTABLE_PREFIX + "\")]}\\u0027\\n\""); } /** * Gson should be able to deserialize a stream with non-exectuable token even if it is created * without {@link GsonBuilder#generateNonExecutableJson()}. */ @Test public void testJsonWithNonExectuableTokenWithRegularGsonDeserialization() { Gson gson = gsonBuilder.create(); // Note: Embedding non-executable prefix literally is only possible because Gson is lenient by // default String json = JSON_NON_EXECUTABLE_PREFIX + "{stringValue:\"" + JSON_NON_EXECUTABLE_PREFIX + "\"}"; BagOfPrimitives target = gson.fromJson(json, BagOfPrimitives.class); assertThat(target.stringValue).isEqualTo(JSON_NON_EXECUTABLE_PREFIX); } /** * Gson should be able to deserialize a stream with non-exectuable token if it is created with * {@link GsonBuilder#generateNonExecutableJson()}. */ @Test 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(); // Note: Embedding non-executable prefix literally is only possible because Gson is lenient by // default String json = JSON_NON_EXECUTABLE_PREFIX + "{intValue:2,stringValue:\"" + JSON_NON_EXECUTABLE_PREFIX + "\"}"; BagOfPrimitives target = gson.fromJson(json, BagOfPrimitives.class); assertThat(target.stringValue).isEqualTo(JSON_NON_EXECUTABLE_PREFIX); assertThat(target.intValue).isEqualTo(2); } } ================================================ FILE: gson/src/test/java/com/google/gson/functional/SerializedNameTest.java ================================================ /* * 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 static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; import org.junit.Test; public final class SerializedNameTest { private final Gson gson = new Gson(); @Test public void testFirstNameIsChosenForSerialization() { MyClass target = new MyClass("v1", "v2"); // Ensure name1 occurs exactly once, and name2 and name3 don't appear assertThat(gson.toJson(target)).isEqualTo("{\"name\":\"v1\",\"name1\":\"v2\"}"); } @Test public void testMultipleNamesDeserializedCorrectly() { assertThat(gson.fromJson("{'name':'v1'}", MyClass.class).a).isEqualTo("v1"); // Both name1 and name2 gets deserialized to b assertThat(gson.fromJson("{'name1':'v11'}", MyClass.class).b).isEqualTo("v11"); assertThat(gson.fromJson("{'name2':'v2'}", MyClass.class).b).isEqualTo("v2"); assertThat(gson.fromJson("{'name3':'v3'}", MyClass.class).b).isEqualTo("v3"); } @Test public void testMultipleNamesInTheSameString() { // The last value takes precedence assertThat(gson.fromJson("{'name1':'v1','name2':'v2','name3':'v3'}", MyClass.class).b) .isEqualTo("v3"); } 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; } } } ================================================ FILE: gson/src/test/java/com/google/gson/functional/StreamingTypeAdaptersTest.java ================================================ /* * 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.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import com.google.common.base.Splitter; 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 org.junit.Test; public final class StreamingTypeAdaptersTest { private Gson miniGson = new GsonBuilder().create(); private TypeAdapter truckAdapter = miniGson.getAdapter(Truck.class); private TypeAdapter> mapAdapter = miniGson.getAdapter(new TypeToken>() {}); @Test public void testSerialize() { Truck truck = new Truck(); truck.passengers = Arrays.asList(new Person("Jesse", 29), new Person("Jodie", 29)); truck.horsePower = 300; assertThat(truckAdapter.toJson(truck).replace('\"', '\'')) .isEqualTo( "{'horsePower':300.0," + "'passengers':[{'age':29,'name':'Jesse'},{'age':29,'name':'Jodie'}]}"); } @Test 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('\'', '\"')); assertThat(truck.horsePower).isEqualTo(300.0); assertThat(truck.passengers) .isEqualTo(Arrays.asList(new Person("Jesse", 29), new Person("Jodie", 29))); } @Test public void testSerializeNullField() { Truck truck = new Truck(); truck.passengers = null; assertThat(truckAdapter.toJson(truck).replace('\"', '\'')) .isEqualTo("{'horsePower':0.0,'passengers':null}"); } @Test public void testDeserializeNullField() throws IOException { Truck truck = truckAdapter.fromJson("{'horsePower':0.0,'passengers':null}".replace('\'', '\"')); assertThat(truck.passengers).isNull(); } @Test public void testSerializeNullObject() { Truck truck = new Truck(); truck.passengers = Arrays.asList((Person) null); assertThat(truckAdapter.toJson(truck).replace('\"', '\'')) .isEqualTo("{'horsePower':0.0,'passengers':[null]}"); } @Test public void testDeserializeNullObject() throws IOException { Truck truck = truckAdapter.fromJson("{'horsePower':0.0,'passengers':[null]}".replace('\'', '\"')); assertThat(truck.passengers).isEqualTo(Arrays.asList((Person) null)); } @Test public void testSerializeWithCustomTypeAdapter() { usePersonNameAdapter(); Truck truck = new Truck(); truck.passengers = Arrays.asList(new Person("Jesse", 29), new Person("Jodie", 29)); assertThat(truckAdapter.toJson(truck).replace('\"', '\'')) .isEqualTo("{'horsePower':0.0,'passengers':['Jesse','Jodie']}"); } @Test public void testDeserializeWithCustomTypeAdapter() throws IOException { usePersonNameAdapter(); Truck truck = truckAdapter.fromJson( "{'horsePower':0.0,'passengers':['Jesse','Jodie']}".replace('\'', '\"')); assertThat(truck.passengers) .isEqualTo(Arrays.asList(new Person("Jesse", -1), new Person("Jodie", -1))); } private void usePersonNameAdapter() { TypeAdapter personNameAdapter = new TypeAdapter<>() { @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); } @Test public void testSerializeMap() { Map map = new LinkedHashMap<>(); map.put("a", 5.0); map.put("b", 10.0); assertThat(mapAdapter.toJson(map).replace('"', '\'')).isEqualTo("{'a':5.0,'b':10.0}"); } @Test public void testDeserializeMap() throws IOException { Map map = new LinkedHashMap<>(); map.put("a", 5.0); map.put("b", 10.0); assertThat(mapAdapter.fromJson("{'a':5.0,'b':10.0}".replace('\'', '\"'))).isEqualTo(map); } @Test public void testSerialize1dArray() { TypeAdapter arrayAdapter = miniGson.getAdapter(new TypeToken() {}); assertThat(arrayAdapter.toJson(new double[] {1.0, 2.0, 3.0})).isEqualTo("[1.0,2.0,3.0]"); } @Test public void testDeserialize1dArray() throws IOException { TypeAdapter arrayAdapter = miniGson.getAdapter(new TypeToken() {}); double[] array = arrayAdapter.fromJson("[1.0,2.0,3.0]"); assertThat(array).isEqualTo(new double[] {1.0, 2.0, 3.0}); } @Test public void testSerialize2dArray() { TypeAdapter arrayAdapter = miniGson.getAdapter(new TypeToken() {}); double[][] array = {{1.0, 2.0}, {3.0}}; assertThat(arrayAdapter.toJson(array)).isEqualTo("[[1.0,2.0],[3.0]]"); } @Test public void testDeserialize2dArray() throws IOException { TypeAdapter arrayAdapter = miniGson.getAdapter(new TypeToken() {}); double[][] array = arrayAdapter.fromJson("[[1.0,2.0],[3.0]]"); double[][] expected = {{1.0, 2.0}, {3.0}}; assertThat(array).isEqualTo(expected); } @Test public void testNullSafe() { TypeAdapter typeAdapter = new TypeAdapter<>() { @Override public Person read(JsonReader in) throws IOException { List values = Splitter.on(',').splitToList(in.nextString()); return new Person(values.get(0), Integer.parseInt(values.get(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)); assertThrows(NullPointerException.class, () -> gson.toJson(truck, Truck.class)); String json = "{horsePower:1.0,passengers:[null,'jesse,30']}"; var e = assertThrows(JsonSyntaxException.class, () -> gson.fromJson(json, Truck.class)); assertThat(e) .hasMessageThat() .isEqualTo( "java.lang.IllegalStateException: Expected a string but was NULL at line 1 column 33" + " path $.passengers[0]\n" + "See https://github.com/google/gson/blob/main/Troubleshooting.md#adapter-not-null-safe"); Gson gson2 = new GsonBuilder().registerTypeAdapter(Person.class, typeAdapter.nullSafe()).create(); assertThat(gson2.toJson(truck, Truck.class)) .isEqualTo("{\"horsePower\":1.0,\"passengers\":[null,\"jesse,30\"]}"); Truck deserialized = gson2.fromJson(json, Truck.class); assertThat(deserialized.horsePower).isEqualTo(1.0D); assertThat(deserialized.passengers.get(0)).isNull(); assertThat(deserialized.passengers.get(1).name).isEqualTo("jesse"); } @Test public void testSerializeRecursive() { TypeAdapter nodeAdapter = miniGson.getAdapter(Node.class); Node root = new Node("root"); root.left = new Node("left"); root.right = new Node("right"); assertThat(nodeAdapter.toJson(root).replace('"', '\'')) .isEqualTo( "{'label':'root'," + "'left':{'label':'left','left':null,'right':null}," + "'right':{'label':'right','left':null,'right':null}}"); } @Test 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); assertThat(truck.horsePower).isEqualTo(300.0); assertThat(truck.passengers).isEqualTo(Arrays.asList(new Person("Jesse", 30))); } static class Truck { double horsePower; List 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; } } } ================================================ FILE: gson/src/test/java/com/google/gson/functional/StringTest.java ================================================ /* * 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 com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import org.junit.Before; import org.junit.Test; /** * Functional tests for Json serialization and deserialization of strings. * * @author Inderjeet Singh * @author Joel Leitch */ public class StringTest { private Gson gson; @Before public void setUp() throws Exception { gson = new Gson(); } @Test public void testStringValueSerialization() { String value = "someRandomStringValue"; assertThat(gson.toJson(value)).isEqualTo('"' + value + '"'); } @Test public void testStringValueDeserialization() { String value = "someRandomStringValue"; String actual = gson.fromJson("\"" + value + "\"", String.class); assertThat(actual).isEqualTo(value); } @Test public void testSingleQuoteInStringSerialization() { String valueWithQuotes = "beforeQuote'afterQuote"; String jsonRepresentation = gson.toJson(valueWithQuotes); assertThat(gson.fromJson(jsonRepresentation, String.class)).isEqualTo(valueWithQuotes); } @Test public void testEscapedCtrlNInStringSerialization() { String value = "a\nb"; String json = gson.toJson(value); assertThat(json).isEqualTo("\"a\\nb\""); } @Test public void testEscapedCtrlNInStringDeserialization() { String json = "'a\\nb'"; String actual = gson.fromJson(json, String.class); assertThat(actual).isEqualTo("a\nb"); } @Test public void testEscapedCtrlRInStringSerialization() { String value = "a\rb"; String json = gson.toJson(value); assertThat(json).isEqualTo("\"a\\rb\""); } @Test public void testEscapedCtrlRInStringDeserialization() { String json = "'a\\rb'"; String actual = gson.fromJson(json, String.class); assertThat(actual).isEqualTo("a\rb"); } @Test public void testEscapedBackslashInStringSerialization() { String value = "a\\b"; String json = gson.toJson(value); assertThat(json).isEqualTo("\"a\\\\b\""); } @Test public void testEscapedBackslashInStringDeserialization() { String actual = gson.fromJson("'a\\\\b'", String.class); assertThat(actual).isEqualTo("a\\b"); } @Test public void testSingleQuoteInStringDeserialization() { String value = "beforeQuote'afterQuote"; String actual = gson.fromJson("\"" + value + "\"", String.class); assertThat(actual).isEqualTo(value); } @Test public void testEscapingQuotesInStringSerialization() { String valueWithQuotes = "beforeQuote\"afterQuote"; String jsonRepresentation = gson.toJson(valueWithQuotes); String target = gson.fromJson(jsonRepresentation, String.class); assertThat(target).isEqualTo(valueWithQuotes); } @Test public void testEscapingQuotesInStringDeserialization() { String value = "beforeQuote\\\"afterQuote"; String actual = gson.fromJson("\"" + value + "\"", String.class); String expected = "beforeQuote\"afterQuote"; assertThat(actual).isEqualTo(expected); } @Test public void testStringValueAsSingleElementArraySerialization() { String[] target = {"abc"}; assertThat(gson.toJson(target)).isEqualTo("[\"abc\"]"); assertThat(gson.toJson(target, String[].class)).isEqualTo("[\"abc\"]"); } @Test public void testStringWithEscapedSlashDeserialization() { String value = "/"; String json = "'\\/'"; String actual = gson.fromJson(json, String.class); assertThat(actual).isEqualTo(value); } /** * Created in response to * http://groups.google.com/group/google-gson/browse_thread/thread/2431d4a3d0d6cb23 */ @Test public void testAssignmentCharSerialization() { String value = "abc="; String json = gson.toJson(value); assertThat(json).isEqualTo("\"abc\\u003d\""); } /** * Created in response to * http://groups.google.com/group/google-gson/browse_thread/thread/2431d4a3d0d6cb23 */ @Test public void testAssignmentCharDeserialization() { String json = "\"abc=\""; String value = gson.fromJson(json, String.class); assertThat(value).isEqualTo("abc="); json = "'abc\\u003d'"; value = gson.fromJson(json, String.class); assertThat(value).isEqualTo("abc="); } @Test public void testJavascriptKeywordsInStringSerialization() { String value = "null true false function"; String json = gson.toJson(value); assertThat(json).isEqualTo("\"" + value + "\""); } @Test public void testJavascriptKeywordsInStringDeserialization() { String json = "'null true false function'"; String value = gson.fromJson(json, String.class); assertThat(json.substring(1, json.length() - 1)).isEqualTo(value); } } ================================================ FILE: gson/src/test/java/com/google/gson/functional/ToNumberPolicyFunctionalTest.java ================================================ /* * 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 static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; 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 java.lang.reflect.Type; import java.math.BigDecimal; import java.util.Collection; import java.util.List; import org.junit.Test; public class ToNumberPolicyFunctionalTest { @Test public void testDefault() { Gson gson = new Gson(); assertThat(gson.fromJson("null", Object.class)).isNull(); assertThat(gson.fromJson("10", Object.class)).isEqualTo(10D); assertThat(gson.fromJson("null", Number.class)).isNull(); assertThat(gson.fromJson("10", Number.class)).isEqualTo(new LazilyParsedNumber("10")); } @Test public void testAsDoubles() { Gson gson = new GsonBuilder() .setObjectToNumberStrategy(ToNumberPolicy.DOUBLE) .setNumberToNumberStrategy(ToNumberPolicy.DOUBLE) .create(); assertThat(gson.fromJson("null", Object.class)).isNull(); assertThat(gson.fromJson("10", Object.class)).isEqualTo(10.0); assertThat(gson.fromJson("null", Number.class)).isNull(); assertThat(gson.fromJson("10", Number.class)).isEqualTo(10.0); } @Test public void testAsLazilyParsedNumbers() { Gson gson = new GsonBuilder() .setObjectToNumberStrategy(ToNumberPolicy.LAZILY_PARSED_NUMBER) .setNumberToNumberStrategy(ToNumberPolicy.LAZILY_PARSED_NUMBER) .create(); assertThat(gson.fromJson("null", Object.class)).isNull(); assertThat(gson.fromJson("10", Object.class)).isEqualTo(new LazilyParsedNumber("10")); assertThat(gson.fromJson("null", Number.class)).isNull(); assertThat(gson.fromJson("10", Number.class)).isEqualTo(new LazilyParsedNumber("10")); } @Test public void testAsLongsOrDoubles() { Gson gson = new GsonBuilder() .setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE) .setNumberToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE) .create(); assertThat(gson.fromJson("null", Object.class)).isNull(); assertThat(gson.fromJson("10", Object.class)).isEqualTo(10L); assertThat(gson.fromJson("10.0", Object.class)).isEqualTo(10.0); assertThat(gson.fromJson("null", Number.class)).isNull(); assertThat(gson.fromJson("10", Number.class)).isEqualTo(10L); assertThat(gson.fromJson("10.0", Number.class)).isEqualTo(10.0); } @Test public void testAsBigDecimals() { Gson gson = new GsonBuilder() .setObjectToNumberStrategy(ToNumberPolicy.BIG_DECIMAL) .setNumberToNumberStrategy(ToNumberPolicy.BIG_DECIMAL) .create(); assertThat(gson.fromJson("null", Object.class)).isNull(); assertThat(gson.fromJson("10", Object.class)).isEqualTo(new BigDecimal("10")); assertThat(gson.fromJson("10.0", Object.class)).isEqualTo(new BigDecimal("10.0")); assertThat(gson.fromJson("null", Number.class)).isNull(); assertThat(gson.fromJson("10", Number.class)).isEqualTo(new BigDecimal("10")); assertThat(gson.fromJson("10.0", Number.class)).isEqualTo(new BigDecimal("10.0")); assertThat(gson.fromJson("3.141592653589793238462643383279", BigDecimal.class)) .isEqualTo(new BigDecimal("3.141592653589793238462643383279")); assertThat(gson.fromJson("1e400", BigDecimal.class)).isEqualTo(new BigDecimal("1e400")); } @Test public void testAsListOfLongsOrDoubles() { Gson gson = new GsonBuilder() .setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE) .setNumberToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE) .create(); Type objectCollectionType = new TypeToken>() {}.getType(); Collection objects = gson.fromJson("[null,10,10.0]", objectCollectionType); assertThat(objects).containsExactly(null, 10L, 10.0).inOrder(); Type numberCollectionType = new TypeToken>() {}.getType(); Collection numbers = gson.fromJson("[null,10,10.0]", numberCollectionType); assertThat(numbers).containsExactly(null, 10L, 10.0).inOrder(); } @Test public void testCustomStrategiesCannotAffectConcreteDeclaredNumbers() { UnsupportedOperationException customException = new UnsupportedOperationException("test-exception"); ToNumberStrategy fail = new ToNumberStrategy() { @Override public Byte readNumber(JsonReader in) { throw customException; } }; Gson gson = new GsonBuilder().setObjectToNumberStrategy(fail).setNumberToNumberStrategy(fail).create(); List numbers = gson.fromJson("[null, 10, 20, 30]", new TypeToken>() {}.getType()); assertThat(numbers).containsExactly(null, (byte) 10, (byte) 20, (byte) 30).inOrder(); var e = assertThrows( UnsupportedOperationException.class, () -> gson.fromJson("[null, 10, 20, 30]", new TypeToken>() {}.getType())); assertThat(e).isSameInstanceAs(customException); e = assertThrows( UnsupportedOperationException.class, () -> gson.fromJson("[null, 10, 20, 30]", new TypeToken>() {}.getType())); assertThat(e).isSameInstanceAs(customException); } } ================================================ FILE: gson/src/test/java/com/google/gson/functional/TreeTypeAdaptersTest.java ================================================ /* * 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.common.truth.Truth.assertThat; 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; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.Before; import org.junit.Test; /** Collection of functional tests for DOM tree based type adapters. */ public class TreeTypeAdaptersTest { private static final Id STUDENT1_ID = new Id<>("5", Student.class); private static final Id 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>() {}.getType(); private static final Id> COURSE_ID = new Id<>("10", TYPE_COURSE_HISTORY); private Gson gson; private Course course; @Before public void setUp() { gson = new GsonBuilder().registerTypeAdapter(Id.class, new IdTreeTypeAdapter()).create(); course = new Course<>( COURSE_ID, 4, new Assignment(null, null), Arrays.asList(STUDENT1, STUDENT2)); } @Test public void testSerializeId() { String json = gson.toJson(course, TYPE_COURSE_HISTORY); assertThat(json).contains(String.valueOf(COURSE_ID.getValue())); assertThat(json).contains(String.valueOf(STUDENT1_ID.getValue())); assertThat(json).contains(String.valueOf(STUDENT2_ID.getValue())); } @Test public void testDeserializeId() { String json = "{courseId:1,students:[{id:1,name:'first'},{id:6,name:'second'}]," + "numAssignments:4,assignment:{}}"; Course target = gson.fromJson(json, TYPE_COURSE_HISTORY); assertThat(target.getStudents().get(0).id.getValue()).isEqualTo("1"); assertThat(target.getStudents().get(1).id.getValue()).isEqualTo("6"); assertThat(target.getId().getValue()).isEqualTo("1"); } @SuppressWarnings("UnusedTypeParameter") private static final class Id { final String value; @SuppressWarnings("unused") final Type typeOfId; private Id(String value, Type typeOfId) { this.value = value; this.typeOfId = typeOfId; } String getValue() { return value; } } private static final class IdTreeTypeAdapter implements JsonSerializer>, JsonDeserializer> { @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 id; String name; private Student() { this(null, null); } Student(Id id, String name) { this.id = id; this.name = name; } } @SuppressWarnings("unused") private static class Course { final List students; private final Id> courseId; private final int numAssignments; private final Assignment assignment; private Course() { this(null, 0, null, new ArrayList<>()); } Course( Id> courseId, int numAssignments, Assignment assignment, List players) { this.courseId = courseId; this.numAssignments = numAssignments; this.assignment = assignment; this.students = players; } Id> getId() { return courseId; } List getStudents() { return students; } } @SuppressWarnings("unused") private static class Assignment { private final Id> id; private final T data; private Assignment() { this(null, null); } Assignment(Id> id, T data) { this.id = id; this.data = data; } } @SuppressWarnings("unused") private static class HistoryCourse { int numClasses; } } ================================================ FILE: gson/src/test/java/com/google/gson/functional/TypeAdapterPrecedenceTest.java ================================================ /* * 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.common.truth.Truth.assertThat; 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 org.junit.Test; public final class TypeAdapterPrecedenceTest { @Test 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(); assertThat(gson.toJson(new Foo("foo"))).isEqualTo("\"foo via serializer 2\""); assertThat(gson.fromJson("foo", Foo.class).name).isEqualTo("foo via deserializer 2"); } @Test public void testStreamingFollowedByStreaming() { Gson gson = new GsonBuilder() .registerTypeAdapter(Foo.class, newTypeAdapter("type adapter 1")) .registerTypeAdapter(Foo.class, newTypeAdapter("type adapter 2")) .create(); assertThat(gson.toJson(new Foo("foo"))).isEqualTo("\"foo via type adapter 2\""); assertThat(gson.fromJson("foo", Foo.class).name).isEqualTo("foo via type adapter 2"); } @Test public void testSerializeNonstreamingTypeAdapterFollowedByStreamingTypeAdapter() { Gson gson = new GsonBuilder() .registerTypeAdapter(Foo.class, newSerializer("serializer")) .registerTypeAdapter(Foo.class, newDeserializer("deserializer")) .registerTypeAdapter(Foo.class, newTypeAdapter("type adapter")) .create(); assertThat(gson.toJson(new Foo("foo"))).isEqualTo("\"foo via type adapter\""); assertThat(gson.fromJson("foo", Foo.class).name).isEqualTo("foo via type adapter"); } @Test public void testStreamingFollowedByNonstreaming() { Gson gson = new GsonBuilder() .registerTypeAdapter(Foo.class, newTypeAdapter("type adapter")) .registerTypeAdapter(Foo.class, newSerializer("serializer")) .registerTypeAdapter(Foo.class, newDeserializer("deserializer")) .create(); assertThat(gson.toJson(new Foo("foo"))).isEqualTo("\"foo via serializer\""); assertThat(gson.fromJson("foo", Foo.class).name).isEqualTo("foo via deserializer"); } @Test public void testStreamingHierarchicalFollowedByNonstreaming() { Gson gson = new GsonBuilder() .registerTypeHierarchyAdapter(Foo.class, newTypeAdapter("type adapter")) .registerTypeAdapter(Foo.class, newSerializer("serializer")) .registerTypeAdapter(Foo.class, newDeserializer("deserializer")) .create(); assertThat(gson.toJson(new Foo("foo"))).isEqualTo("\"foo via serializer\""); assertThat(gson.fromJson("foo", Foo.class).name).isEqualTo("foo via deserializer"); } @Test public void testStreamingFollowedByNonstreamingHierarchical() { Gson gson = new GsonBuilder() .registerTypeAdapter(Foo.class, newTypeAdapter("type adapter")) .registerTypeHierarchyAdapter(Foo.class, newSerializer("serializer")) .registerTypeHierarchyAdapter(Foo.class, newDeserializer("deserializer")) .create(); assertThat(gson.toJson(new Foo("foo"))).isEqualTo("\"foo via type adapter\""); assertThat(gson.fromJson("foo", Foo.class).name).isEqualTo("foo via type adapter"); } @Test public void testStreamingHierarchicalFollowedByNonstreamingHierarchical() { Gson gson = new GsonBuilder() .registerTypeHierarchyAdapter(Foo.class, newSerializer("serializer")) .registerTypeHierarchyAdapter(Foo.class, newDeserializer("deserializer")) .registerTypeHierarchyAdapter(Foo.class, newTypeAdapter("type adapter")) .create(); assertThat(gson.toJson(new Foo("foo"))).isEqualTo("\"foo via type adapter\""); assertThat(gson.fromJson("foo", Foo.class).name).isEqualTo("foo via type adapter"); } @Test 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(); assertThat(gson.toJson(new Foo("foo"))).isEqualTo("\"foo via non hierarchical\""); assertThat(gson.fromJson("foo", Foo.class).name).isEqualTo("foo via non hierarchical"); } private static class Foo { final String name; private Foo(String name) { this.name = name; } } private static JsonSerializer newSerializer(String name) { return new JsonSerializer<>() { @Override public JsonElement serialize(Foo src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(src.name + " via " + name); } }; } private static JsonDeserializer newDeserializer(String name) { return new JsonDeserializer<>() { @Override public Foo deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) { return new Foo(json.getAsString() + " via " + name); } }; } private static TypeAdapter newTypeAdapter(String name) { return new TypeAdapter<>() { @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); } }; } } ================================================ FILE: gson/src/test/java/com/google/gson/functional/TypeAdapterRuntimeTypeWrapperTest.java ================================================ /* * Copyright (C) 2022 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.common.truth.Truth.assertThat; 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.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 org.junit.Test; public class TypeAdapterRuntimeTypeWrapperTest { private static class Base {} private static class Subclass extends Base { @SuppressWarnings("unused") String f = "test"; } private static class Container { @SuppressWarnings("unused") Base b = new Subclass(); } private static class Deserializer implements JsonDeserializer { @Override public Base deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) { throw new AssertionError("not needed for this test"); } } /** * When custom {@link JsonSerializer} is registered for Base should prefer that over reflective * adapter for Subclass for serialization. */ @Test public void testJsonSerializer() { Gson gson = new GsonBuilder() .registerTypeAdapter( Base.class, (JsonSerializer) (src, typeOfSrc, context) -> new JsonPrimitive("serializer")) .create(); String json = gson.toJson(new Container()); assertThat(json).isEqualTo("{\"b\":\"serializer\"}"); } /** * When only {@link JsonDeserializer} is registered for Base, then on serialization should prefer * reflective adapter for Subclass since Base would use reflective adapter as delegate. */ @Test public void testJsonDeserializer_ReflectiveSerializerDelegate() { Gson gson = new GsonBuilder().registerTypeAdapter(Base.class, new Deserializer()).create(); String json = gson.toJson(new Container()); assertThat(json).isEqualTo("{\"b\":{\"f\":\"test\"}}"); } /** * When {@link JsonDeserializer} with custom adapter as delegate is registered for Base, then on * serialization should prefer custom adapter delegate for Base over reflective adapter for * Subclass. */ @Test public void testJsonDeserializer_CustomSerializerDelegate() { Gson gson = new GsonBuilder() // Register custom delegate .registerTypeAdapter( Base.class, new TypeAdapter() { @Override public Base read(JsonReader in) throws IOException { throw new UnsupportedOperationException(); } @Override public void write(JsonWriter out, Base value) throws IOException { out.value("custom delegate"); } }) .registerTypeAdapter(Base.class, new Deserializer()) .create(); String json = gson.toJson(new Container()); assertThat(json).isEqualTo("{\"b\":\"custom delegate\"}"); } /** * When two (or more) {@link JsonDeserializer}s are registered for Base which eventually fall back * to reflective adapter as delegate, then on serialization should prefer reflective adapter for * Subclass. */ @Test public void testJsonDeserializer_ReflectiveTreeSerializerDelegate() { Gson gson = new GsonBuilder() // Register delegate which itself falls back to reflective serialization .registerTypeAdapter(Base.class, new Deserializer()) .registerTypeAdapter(Base.class, new Deserializer()) .create(); String json = gson.toJson(new Container()); assertThat(json).isEqualTo("{\"b\":{\"f\":\"test\"}}"); } /** * When {@link JsonDeserializer} with {@link JsonSerializer} as delegate is registered for Base, * then on serialization should prefer {@code JsonSerializer} over reflective adapter for * Subclass. */ @Test public void testJsonDeserializer_JsonSerializerDelegate() { Gson gson = new GsonBuilder() // Register JsonSerializer as delegate .registerTypeAdapter( Base.class, (JsonSerializer) (src, typeOfSrc, context) -> new JsonPrimitive("custom delegate")) .registerTypeAdapter(Base.class, new Deserializer()) .create(); String json = gson.toJson(new Container()); assertThat(json).isEqualTo("{\"b\":\"custom delegate\"}"); } /** * When a {@link JsonDeserializer} is registered for Subclass, and a custom {@link JsonSerializer} * is registered for Base, then Gson should prefer the reflective adapter for Subclass for * backward compatibility (see https://github.com/google/gson/pull/1787#issuecomment-1222175189) * even though normally TypeAdapterRuntimeTypeWrapper should prefer the custom serializer for * Base. */ @Test public void testJsonDeserializer_SubclassBackwardCompatibility() { Gson gson = new GsonBuilder() .registerTypeAdapter( Subclass.class, (JsonDeserializer) (json, typeOfT, context) -> { throw new AssertionError("not needed for this test"); }) .registerTypeAdapter( Base.class, (JsonSerializer) (src, typeOfSrc, context) -> new JsonPrimitive("base")) .create(); String json = gson.toJson(new Container()); assertThat(json).isEqualTo("{\"b\":{\"f\":\"test\"}}"); } private static class CyclicBase { @SuppressWarnings("unused") CyclicBase f; } private static class CyclicSub extends CyclicBase { @SuppressWarnings("unused") int i; CyclicSub(int i) { this.i = i; } } /** * Tests behavior when the type of a field refers to a type whose adapter is currently in the * process of being created. For these cases {@link Gson} uses a future adapter for the type. That * adapter later uses the actual adapter as delegate. */ @Test public void testGsonFutureAdapter() { CyclicBase b = new CyclicBase(); b.f = new CyclicSub(2); String json = new Gson().toJson(b); assertThat(json).isEqualTo("{\"f\":{\"i\":2}}"); } } ================================================ FILE: gson/src/test/java/com/google/gson/functional/TypeHierarchyAdapterTest.java ================================================ /* * 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.common.truth.Truth.assertThat; 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 org.junit.Test; /** Test that the hierarchy adapter works when subtypes are used. */ public final class TypeHierarchyAdapterTest { @Test 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); assertThat(json) .isEqualTo( "{\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" + "}"); Company copied = gson.fromJson(json, Company.class); assertThat(gson.toJson(copied, Company.class)).isEqualTo(json); assertThat(company.ceo.userid).isEqualTo(copied.ceo.userid); assertThat(company.ceo.assistant.userid).isEqualTo(copied.ceo.assistant.userid); assertThat(company.ceo.minions[0].userid).isEqualTo(copied.ceo.minions[0].userid); assertThat(company.ceo.minions[1].userid).isEqualTo(copied.ceo.minions[1].userid); assertThat(company.ceo.minions[2].userid).isEqualTo(copied.ceo.minions[2].userid); assertThat(((Manager) company.ceo.minions[2]).minions[0].userid) .isEqualTo(((Manager) copied.ceo.minions[2]).minions[0].userid); assertThat(((Manager) company.ceo.minions[2]).minions[1].userid) .isEqualTo(((Manager) copied.ceo.minions[2]).minions[1].userid); } @Test 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); assertThat(json).isEqualTo("\"inder\""); Manager copied = gson.fromJson(json, Manager.class); assertThat(copied.userid).isEqualTo(manager.userid); } /** This behaviour changed in Gson 2.1; it used to throw. */ @Test public void testRegisterSubTypeFirstAllowed() { Gson unused = new GsonBuilder() .registerTypeHierarchyAdapter(Manager.class, new ManagerAdapter()) .registerTypeHierarchyAdapter(Employee.class, new EmployeeAdapter()) .create(); } static class ManagerAdapter implements JsonSerializer, JsonDeserializer { @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, JsonDeserializer { @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.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; } @SuppressWarnings("MemberName") static class CEO extends Manager { Employee assistant; } static class Company { CEO ceo; } } ================================================ FILE: gson/src/test/java/com/google/gson/functional/TypeVariableTest.java ================================================ /* * 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 static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Test; /** * Functional test for Gson serialization and deserialization of classes with type variables. * * @author Joel Leitch */ public class TypeVariableTest { @Test public void testAdvancedTypeVariables() { Gson gson = new Gson(); Bar bar1 = new Bar("someString", 1, true); ArrayList arrayList = new ArrayList<>(); arrayList.add(1); arrayList.add(2); arrayList.add(3); bar1.map.put("key1", arrayList); bar1.map.put("key2", new ArrayList<>()); String json = gson.toJson(bar1); Bar bar2 = gson.fromJson(json, Bar.class); assertThat(bar2).isEqualTo(bar1); } @Test public void testTypeVariablesViaTypeParameter() { Gson gson = new Gson(); Foo original = new Foo<>("e", 5, false); original.map.put("f", Arrays.asList(6, 7)); Type type = new TypeToken>() {}.getType(); String json = gson.toJson(original, type); assertThat(json) .isEqualTo( "{\"someSField\":\"e\",\"someTField\":5,\"map\":{\"f\":[6,7]},\"redField\":false}"); assertThat(gson.>fromJson(json, type)).isEqualTo(original); } @Test public void testBasicTypeVariables() { Gson gson = new Gson(); Blue blue1 = new Blue(true); String json = gson.toJson(blue1); Blue blue2 = gson.fromJson(json, Blue.class); assertThat(blue2).isEqualTo(blue1); } // for missing hashCode() override @SuppressWarnings({"overrides", "EqualsHashCode"}) public static class Blue extends Red { public Blue() { super(false); } public Blue(boolean value) { super(value); } @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 { protected S redField; public Red() {} public Red(S redField) { this.redField = redField; } } @SuppressWarnings({"overrides", "EqualsHashCode"}) // for missing hashCode() override public static class Foo extends Red { private S someSField; private T someTField; public final Map> map = new HashMap<>(); public Foo() {} public Foo(S sValue, T tValue, Boolean redField) { super(redField); this.someSField = sValue; this.someTField = tValue; } @Override @SuppressWarnings("unchecked") public boolean equals(Object o) { if (!(o instanceof Foo)) { return false; } Foo realFoo = (Foo) o; return redField.equals(realFoo.redField) && someTField.equals(realFoo.someTField) && someSField.equals(realFoo.someSField) && map.equals(realFoo.map); } } public static class Bar extends Foo { public Bar() { this("", 0, false); } public Bar(String s, Integer i, boolean b) { super(s, i, b); } } } ================================================ FILE: gson/src/test/java/com/google/gson/functional/UncategorizedTest.java ================================================ /* * 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 com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; 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.lang.reflect.Type; import java.util.List; import org.junit.Before; import org.junit.Test; /** * Functional tests that do not fall neatly into any of the existing classification. * * @author Inderjeet Singh * @author Joel Leitch */ public class UncategorizedTest { private Gson gson = null; @Before public void setUp() throws Exception { gson = new Gson(); } @Test public void testInvalidJsonDeserializationFails() throws Exception { assertThrows( JsonParseException.class, () -> gson.fromJson("adfasdf1112,,,\":", BagOfPrimitives.class)); assertThrows( JsonParseException.class, () -> gson.fromJson("{adfasdf1112,,,\":}", BagOfPrimitives.class)); } @Test public void testObjectEqualButNotSameSerialization() { ClassOverridingEquals objA = new ClassOverridingEquals(); ClassOverridingEquals objB = new ClassOverridingEquals(); objB.ref = objA; String json = gson.toJson(objB); assertThat(json).isEqualTo(objB.getExpectedJson()); } @Test public void testStaticFieldsAreNotSerialized() { BagOfPrimitives target = new BagOfPrimitives(); assertThat(gson.toJson(target)).doesNotContain("DEFAULT_VALUE"); } @Test public void testGsonInstanceReusableForSerializationAndDeserialization() { BagOfPrimitives bag = new BagOfPrimitives(); String json = gson.toJson(bag); BagOfPrimitives deserialized = gson.fromJson(json, BagOfPrimitives.class); assertThat(deserialized).isEqualTo(bag); } /** * 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 */ @Test public void testReturningDerivedClassesDuringDeserialization() { Gson gson = new GsonBuilder().registerTypeAdapter(Base.class, new BaseTypeAdapter()).create(); String json = "{\"opType\":\"OP1\"}"; Base base = gson.fromJson(json, Base.class); assertThat(base).isInstanceOf(Derived1.class); assertThat(base.opType).isEqualTo(OperationType.OP1); json = "{\"opType\":\"OP2\"}"; base = gson.fromJson(json, Base.class); assertThat(base).isInstanceOf(Derived2.class); assertThat(base.opType).isEqualTo(OperationType.OP2); } /** * Test that trailing whitespace is ignored. * http://code.google.com/p/google-gson/issues/detail?id=302 */ @Test public void testTrailingWhitespace() throws Exception { List integers = gson.fromJson("[1,2,3] \n\n ", new TypeToken>() {}.getType()); assertThat(integers).containsExactly(1, 2, 3).inOrder(); } 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 { @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); } } } ================================================ FILE: gson/src/test/java/com/google/gson/functional/VersioningTest.java ================================================ /* * 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 com.google.common.truth.Truth.assertThat; 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 org.junit.Test; /** * Functional tests for versioning support in Gson. * * @author Inderjeet Singh * @author Joel Leitch */ public class VersioningTest { 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 static Gson gsonWithVersion(double version) { return new GsonBuilder().setVersion(version).create(); } @Test public void testVersionedUntilSerialization() { Version1 target = new Version1(); Gson gson = gsonWithVersion(1.29); String json = gson.toJson(target); assertThat(json).contains("\"a\":" + A); gson = gsonWithVersion(1.3); json = gson.toJson(target); assertThat(json).doesNotContain("\"a\":" + A); gson = gsonWithVersion(1.31); json = gson.toJson(target); assertThat(json).doesNotContain("\"a\":" + A); } @Test public void testVersionedUntilDeserialization() { String json = "{\"a\":3,\"b\":4,\"c\":5}"; Gson gson = gsonWithVersion(1.29); Version1 version1 = gson.fromJson(json, Version1.class); assertThat(version1.a).isEqualTo(3); gson = gsonWithVersion(1.3); version1 = gson.fromJson(json, Version1.class); assertThat(version1.a).isEqualTo(A); gson = gsonWithVersion(1.31); version1 = gson.fromJson(json, Version1.class); assertThat(version1.a).isEqualTo(A); } @Test public void testVersionedClassesSerialization() { Gson gson = gsonWithVersion(1.0); String json1 = gson.toJson(new Version1()); String json2 = gson.toJson(new Version1_1()); assertThat(json2).isEqualTo(json1); } @Test public void testVersionedClassesDeserialization() { Gson gson = gsonWithVersion(1.0); String json = "{\"a\":3,\"b\":4,\"c\":5}"; Version1 version1 = gson.fromJson(json, Version1.class); assertThat(version1.a).isEqualTo(3); assertThat(version1.b).isEqualTo(4); @SuppressWarnings("MemberName") Version1_1 version1_1 = gson.fromJson(json, Version1_1.class); assertThat(version1_1.a).isEqualTo(3); assertThat(version1_1.b).isEqualTo(4); assertThat(version1_1.c).isEqualTo(C); } @Test public void testIgnoreLaterVersionClassSerialization() { Gson gson = gsonWithVersion(1.0); assertThat(gson.toJson(new Version1_2())).isEqualTo("null"); } @Test public void testIgnoreLaterVersionClassDeserialization() { Gson gson = gsonWithVersion(1.0); String json = "{\"a\":3,\"b\":4,\"c\":5,\"d\":6}"; @SuppressWarnings("MemberName") 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 assertThat(version1_2).isNull(); } @Test public void testVersionedGsonWithUnversionedClassesSerialization() { Gson gson = gsonWithVersion(1.0); BagOfPrimitives target = new BagOfPrimitives(10, 20, false, "stringValue"); assertThat(gson.toJson(target)).isEqualTo(target.getExpectedJson()); } @Test public void testVersionedGsonWithUnversionedClassesDeserialization() { Gson gson = gsonWithVersion(1.0); 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); assertThat(actual).isEqualTo(expected); } @Test public void testVersionedGsonMixingSinceAndUntilSerialization() { Gson gson = gsonWithVersion(1.0); SinceUntilMixing target = new SinceUntilMixing(); String json = gson.toJson(target); assertThat(json).doesNotContain("\"b\":" + B); gson = gsonWithVersion(1.2); json = gson.toJson(target); assertThat(json).contains("\"b\":" + B); gson = gsonWithVersion(1.3); json = gson.toJson(target); assertThat(json).doesNotContain("\"b\":" + B); gson = gsonWithVersion(1.4); json = gson.toJson(target); assertThat(json).doesNotContain("\"b\":" + B); } @Test public void testVersionedGsonMixingSinceAndUntilDeserialization() { String json = "{\"a\":5,\"b\":6}"; Gson gson = gsonWithVersion(1.0); SinceUntilMixing result = gson.fromJson(json, SinceUntilMixing.class); assertThat(result.a).isEqualTo(5); assertThat(result.b).isEqualTo(B); gson = gsonWithVersion(1.2); result = gson.fromJson(json, SinceUntilMixing.class); assertThat(result.a).isEqualTo(5); assertThat(result.b).isEqualTo(6); gson = gsonWithVersion(1.3); result = gson.fromJson(json, SinceUntilMixing.class); assertThat(result.a).isEqualTo(5); assertThat(result.b).isEqualTo(B); gson = gsonWithVersion(1.4); result = gson.fromJson(json, SinceUntilMixing.class); assertThat(result.a).isEqualTo(5); assertThat(result.b).isEqualTo(B); } private static class Version1 { @Until(1.3) int a = A; @Since(1.0) int b = B; } @SuppressWarnings("MemberName") private static class Version1_1 extends Version1 { @Since(1.1) int c = C; } @SuppressWarnings("MemberName") @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; } } ================================================ FILE: gson/src/test/java/com/google/gson/integration/OSGiManifestIT.java ================================================ /* * Copyright (C) 2024 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.integration; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; import static org.junit.Assert.fail; import com.google.common.base.Splitter; import com.google.gson.internal.GsonBuildConfig; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.jar.Attributes; import java.util.jar.Manifest; import java.util.stream.Collectors; import org.junit.Before; import org.junit.Test; /** * Performs assertions on the generated OSGi manifest attributes. This is an integration test * ({@code *IT.java}) intended to be run against the final JAR. * *

Note: These tests must be run on the command line with {@code mvn clean verify}, running them * in the IDE will not work because it won't use the generated JAR, and additionally the * bnd-maven-plugin seems to behave differently in the IDE (at least Eclipse), adding unexpected * {@code Import-Package} entries for JDK classes (bnd-maven-plugin bug. */ @SuppressWarnings("MemberName") // class name must end with 'IT' for Maven Failsafe Plugin public class OSGiManifestIT { private static class ManifestData { final URL url; final Manifest manifest; ManifestData(URL url, Manifest manifest) { this.url = url; this.manifest = manifest; } } private static final String GSON_VERSION = GsonBuildConfig.VERSION; private Attributes manifestAttributes; @Before public void getGsonManifestAttributes() throws Exception { ManifestData manifestData = findManifest("com.google.gson"); // Make sure manifest was loaded from final Gson JAR (and not intermediate manifest is used) assertWithMessage( "Should load manifest from Gson JAR file; run this test with `mvn clean verify` on" + " command line and not from IDE") .that(manifestData.url.toString()) .endsWith(".jar!/META-INF/MANIFEST.MF"); manifestAttributes = manifestData.manifest.getMainAttributes(); } private String getAttribute(String name) { return manifestAttributes.getValue(name); } @Test public void testBundleInformation() { assertThat(getAttribute("Bundle-SymbolicName")).isEqualTo("com.google.gson"); assertThat(getAttribute("Bundle-Name")).isEqualTo("Gson"); assertThat(getAttribute("Bundle-License")) .isEqualTo("\"Apache-2.0\";link=\"https://www.apache.org/licenses/LICENSE-2.0.txt\""); assertThat(getAttribute("Bundle-Version")) .isEqualTo(GSON_VERSION.replace("-SNAPSHOT", ".SNAPSHOT")); } @Test public void testImports() throws Exception { // Keep only 'major.minor', drop the 'patch' version String errorProneVersion = shortenVersionNumber( findManifest("com.google.errorprone.annotations") .manifest .getMainAttributes() .getValue("Bundle-Version"), 1); String nextMajorErrorProneVersion = increaseVersionNumber(errorProneVersion, 0); String errorProneVersionRange = "[" + errorProneVersion + "," + nextMajorErrorProneVersion + ")"; List imports = splitPackages(getAttribute("Import-Package")); // If imports contains `java.*`, then either user started from IDE, or IDE rebuilt project while // Maven build was running, see https://github.com/bndtools/bnd/issues/6258 if (imports.stream().anyMatch(i -> i.startsWith("java."))) { fail( "Test must be run from command line with `mvn clean verify`; additionally make sure your" + " IDE did not rebuild the project in the meantime"); } assertThat(imports) .containsExactly( // Dependency on JDK's sun.misc.Unsafe should be optional "sun.misc;resolution:=optional", // Dependency on error prone should be optional "com.google.errorprone.annotations;resolution:=optional;version=\"" + errorProneVersionRange + "\""); // Should not contain any import for Gson's own packages, see // https://github.com/google/gson/pull/2735#issuecomment-2330047410 for (String importedPackage : imports) { assertThat(importedPackage).doesNotContain("com.google.gson"); } } @Test public void testExports() { String gsonVersion = GSON_VERSION.replace("-SNAPSHOT", ""); // Sometimes the `uses` and `exports` clauses can end up in the opposite order, so we use a // quick substitution to canonicalize them. List exports = splitPackages(getAttribute("Export-Package")).stream() .map(line -> line.replaceAll("(;version=\".*\")(;uses:=\".*\")", "$2$1")) .collect(Collectors.toList()); // When not running `mvn clean` the exports might differ slightly, see // https://github.com/bndtools/bnd/issues/6221 assertWithMessage("Unexpected exports; make sure you are running `mvn clean ...`") .that(exports) // Note: This just represents the currently generated exports; especially the `uses` can be // adjusted if necessary when Gson's implementation changes .containsExactly( "com.google.gson;uses:=\"com.google.gson.reflect,com.google.gson.stream\";version=\"" + gsonVersion + "\"", "com.google.gson.annotations;version=\"" + gsonVersion + "\"", "com.google.gson.reflect;version=\"" + gsonVersion + "\"", "com.google.gson.stream;uses:=\"com.google.gson\";version=\"" + gsonVersion + "\""); } @Test public void testRequireCapability() { String expectedJavaVersion = "1.8"; // Defines the minimum required Java version assertThat(getAttribute("Require-Capability")) .isEqualTo("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=" + expectedJavaVersion + "))\""); // Should not define deprecated "Bundle-RequiredExecutionEnvironment" assertThat(getAttribute("Bundle-RequiredExecutionEnvironment")).isNull(); } private ManifestData findManifest(String bundleName) throws IOException { List manifestResources = Collections.list(getClass().getClassLoader().getResources("META-INF/MANIFEST.MF")); for (URL manifestResource : manifestResources) { Manifest manifest; try (InputStream is = manifestResource.openStream()) { manifest = new Manifest(is); } if (bundleName.equals(manifest.getMainAttributes().getValue("Bundle-SymbolicName"))) { return new ManifestData(manifestResource, manifest); } } fail( "Cannot find " + bundleName + " OSGi bundle manifest among: " + manifestResources + "\nRun this test with `mvn clean verify` on command line and not from the IDE."); return null; } /** Splits a list of packages separated by {@code ','}. */ private List splitPackages(String packagesString) { List splitPackages = new ArrayList<>(); int nextSplitStart = 0; boolean isInQuotes = false; for (int i = 0; i < packagesString.length(); i++) { char c = packagesString.charAt(i); // Ignore ',' inside quotes if (c == '"') { isInQuotes = !isInQuotes; } else if (c == ',' && !isInQuotes) { splitPackages.add(packagesString.substring(nextSplitStart, i)); nextSplitStart = i + 1; // skip past the ',' } } // Add package behind last ',' splitPackages.add(packagesString.substring(nextSplitStart)); return splitPackages; } /** * Shortens a version number by dropping lower parts. For example {@code 1.2.3 -> 1.2} (when * {@code keepPosition = 1}). * * @param versionString e.g. "1.2.3" * @param keepPosition position of the version to keep: 0 = major, 1 = minor, ... * @return shortened version number */ private String shortenVersionNumber(String versionString, int keepPosition) { return Splitter.on('.') .splitToStream(versionString) .limit(keepPosition + 1) .collect(Collectors.joining(".")); } /** * Increases part of a version number (and drops lower parts). For example {@code 1.2.3 -> 1.3} * (when {@code position = 1}). * * @param versionString e.g. "1.2.3" * @param position position of the version to increase: 0 = major, 1 = minor, ... * @return increased version number */ private String increaseVersionNumber(String versionString, int position) { List splitVersion = new ArrayList<>(); for (String versionPiece : Splitter.on('.').split(versionString)) { splitVersion.add(Integer.valueOf(versionPiece)); } // Drop lower version parts splitVersion = splitVersion.subList(0, position + 1); // Increase version number splitVersion.set(position, splitVersion.get(position) + 1); return splitVersion.stream().map(i -> i.toString()).collect(Collectors.joining(".")); } } ================================================ FILE: gson/src/test/java/com/google/gson/internal/ConstructorConstructorTest.java ================================================ /* * Copyright (C) 2022 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 static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; import static org.junit.Assert.assertThrows; import com.google.gson.reflect.TypeToken; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.EnumMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.LinkedBlockingDeque; import org.junit.Test; public class ConstructorConstructorTest { private ConstructorConstructor constructorConstructor = new ConstructorConstructor(Collections.emptyMap(), true, Collections.emptyList()); private abstract static class AbstractClass { @SuppressWarnings("unused") AbstractClass() {} } private interface Interface {} /** * Verify that ConstructorConstructor does not try to invoke no-args constructor of abstract * class. */ @Test public void testGet_AbstractClassNoArgConstructor() { ObjectConstructor constructor = constructorConstructor.get(TypeToken.get(AbstractClass.class)); var e = assertThrows(RuntimeException.class, () -> constructor.construct()); assertThat(e) .hasMessageThat() .isEqualTo( "Abstract classes can't be instantiated! Adjust the R8 configuration or register an" + " InstanceCreator or a TypeAdapter for this type. Class name:" + " com.google.gson.internal.ConstructorConstructorTest$AbstractClass\n" + "See https://github.com/google/gson/blob/main/Troubleshooting.md#r8-abstract-class"); } @Test public void testGet_Interface() { ObjectConstructor constructor = constructorConstructor.get(TypeToken.get(Interface.class)); var e = assertThrows(RuntimeException.class, () -> constructor.construct()); assertThat(e) .hasMessageThat() .isEqualTo( "Interfaces can't be instantiated! Register an InstanceCreator or a TypeAdapter for" + " this type. Interface name:" + " com.google.gson.internal.ConstructorConstructorTest$Interface"); } @SuppressWarnings("serial") private static class CustomSortedSet extends TreeSet { // Removes default no-args constructor @SuppressWarnings("unused") CustomSortedSet(Void v) {} } @SuppressWarnings("serial") private static class CustomSet extends HashSet { // Removes default no-args constructor @SuppressWarnings("unused") CustomSet(Void v) {} } @SuppressWarnings("serial") private static class CustomQueue extends LinkedBlockingDeque { // Removes default no-args constructor @SuppressWarnings("unused") CustomQueue(Void v) {} } @SuppressWarnings("serial") private static class CustomList extends ArrayList { // Removes default no-args constructor @SuppressWarnings("unused") CustomList(Void v) {} } /** * Tests that creation of custom {@code Collection} subclasses without no-args constructor should * not use default JDK types (which would cause {@link ClassCastException}). * *

Currently this test is rather contrived because the instances created using Unsafe are not * usable because their fields are not properly initialized, but assume that user has custom * classes which would be functional. */ @Test public void testCustomCollectionCreation() { Class[] collectionTypes = { CustomSortedSet.class, CustomSet.class, CustomQueue.class, CustomList.class, }; for (Class collectionType : collectionTypes) { Object actual = constructorConstructor .get(TypeToken.getParameterized(collectionType, Integer.class)) .construct(); assertWithMessage("Failed for %s; created instance of %s", collectionType, actual.getClass()) .that(actual) .isInstanceOf(collectionType); } } private static interface CustomCollectionInterface extends Collection {} private static interface CustomSetInterface extends Set {} private static interface CustomListInterface extends List {} @Test public void testCustomCollectionInterfaceCreation() { Class[] interfaces = { CustomCollectionInterface.class, CustomSetInterface.class, CustomListInterface.class, }; for (Class interfaceType : interfaces) { var objectConstructor = constructorConstructor.get(TypeToken.get(interfaceType)); var exception = assertThrows(RuntimeException.class, () -> objectConstructor.construct()); assertThat(exception) .hasMessageThat() .isEqualTo( "Interfaces can't be instantiated! Register an InstanceCreator or a TypeAdapter" + " for this type. Interface name: " + interfaceType.getName()); } } @Test public void testStringMapCreation() { // When creating raw Map should use Gson's LinkedTreeMap, assuming keys could be String Object actual = constructorConstructor.get(TypeToken.get(Map.class)).construct(); assertThat(actual).isInstanceOf(LinkedTreeMap.class); // When creating a `Map` should use Gson's LinkedTreeMap actual = constructorConstructor.get(new TypeToken>() {}).construct(); assertThat(actual).isInstanceOf(LinkedTreeMap.class); // But when explicitly requesting a JDK `LinkedHashMap` should use LinkedHashMap actual = constructorConstructor.get(new TypeToken>() {}).construct(); assertThat(actual).isInstanceOf(LinkedHashMap.class); // For all Map types with non-String key, should use JDK LinkedHashMap by default // This is also done to avoid ClassCastException later, because Gson's LinkedTreeMap requires // that keys are Comparable Class[] nonStringTypes = {Integer.class, CharSequence.class, Object.class}; for (Class keyType : nonStringTypes) { actual = constructorConstructor .get(TypeToken.getParameterized(Map.class, keyType, Integer.class)) .construct(); assertWithMessage( "Failed for key type %s; created instance of %s", keyType, actual.getClass()) .that(actual) .isInstanceOf(LinkedHashMap.class); } } private enum MyEnum {} @SuppressWarnings("serial") private static class CustomEnumMap extends EnumMap { @SuppressWarnings("unused") CustomEnumMap(Void v) { super(MyEnum.class); } } @SuppressWarnings("serial") private static class CustomConcurrentNavigableMap extends ConcurrentSkipListMap { // Removes default no-args constructor @SuppressWarnings("unused") CustomConcurrentNavigableMap(Void v) {} } @SuppressWarnings("serial") private static class CustomConcurrentMap extends ConcurrentHashMap { // Removes default no-args constructor @SuppressWarnings("unused") CustomConcurrentMap(Void v) {} } @SuppressWarnings("serial") private static class CustomSortedMap extends TreeMap { // Removes default no-args constructor @SuppressWarnings("unused") CustomSortedMap(Void v) {} } @SuppressWarnings("serial") private static class CustomLinkedHashMap extends LinkedHashMap { // Removes default no-args constructor @SuppressWarnings("unused") CustomLinkedHashMap(Void v) {} } /** * Tests that creation of custom {@code Map} subclasses without no-args constructor should not use * default JDK types (which would cause {@link ClassCastException}). * *

Currently this test is rather contrived because the instances created using Unsafe are not * usable because their fields are not properly initialized, but assume that user has custom * classes which would be functional. */ @Test public void testCustomMapCreation() { Class[] mapTypes = { CustomEnumMap.class, CustomConcurrentNavigableMap.class, CustomConcurrentMap.class, CustomSortedMap.class, CustomLinkedHashMap.class, }; for (Class mapType : mapTypes) { Object actual = constructorConstructor .get(TypeToken.getParameterized(mapType, String.class, Integer.class)) .construct(); assertWithMessage("Failed for %s; created instance of %s", mapType, actual.getClass()) .that(actual) .isInstanceOf(mapType); } } private static interface CustomMapInterface extends Map {} @Test public void testCustomMapInterfaceCreation() { var objectConstructor = constructorConstructor.get(TypeToken.get(CustomMapInterface.class)); var exception = assertThrows(RuntimeException.class, () -> objectConstructor.construct()); assertThat(exception) .hasMessageThat() .isEqualTo( "Interfaces can't be instantiated! Register an InstanceCreator or a TypeAdapter" + " for this type. Interface name: " + CustomMapInterface.class.getName()); } } ================================================ FILE: gson/src/test/java/com/google/gson/internal/GsonBuildConfigTest.java ================================================ /* * 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 com.google.common.truth.Truth.assertThat; import org.junit.Test; /** * Unit tests for {@code GsonBuildConfig} * * @author Inderjeet Singh */ public class GsonBuildConfigTest { @Test public void testEnsureGsonBuildConfigGetsUpdatedToMavenVersion() { assertThat("${project.version}").isNotEqualTo(GsonBuildConfig.VERSION); } } ================================================ FILE: gson/src/test/java/com/google/gson/internal/GsonTypesTest.java ================================================ /* * 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 static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.List; import java.util.Properties; import org.junit.Test; @SuppressWarnings("ClassNamedLikeTypeParameter") // for dummy classes A, B, ... public final class GsonTypesTest { @Test public void testWildcardBoundsInvalid() { String expectedMessage = "Primitive type is not allowed"; IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> GsonTypes.subtypeOf(int.class)); assertThat(e).hasMessageThat().isEqualTo(expectedMessage); e = assertThrows(IllegalArgumentException.class, () -> GsonTypes.supertypeOf(int.class)); assertThat(e).hasMessageThat().isEqualTo(expectedMessage); } @Test public void testNewParameterizedTypeWithoutOwner() throws Exception { // List. List is a top-level class ParameterizedType type = GsonTypes.newParameterizedTypeWithOwner(null, List.class, A.class); assertThat(type.getOwnerType()).isNull(); assertThat(type.getRawType()).isEqualTo(List.class); assertThat(type.getActualTypeArguments()).asList().containsExactly(A.class); // A. A is a static inner class. type = GsonTypes.newParameterizedTypeWithOwner(null, A.class, B.class); assertThat(getFirstTypeArgument(type)).isEqualTo(B.class); IllegalArgumentException e = assertThrows( IllegalArgumentException.class, // NonStaticInner is not allowed without owner () -> GsonTypes.newParameterizedTypeWithOwner(null, NonStaticInner.class, A.class)); assertThat(e).hasMessageThat().isEqualTo("Must specify owner type for " + NonStaticInner.class); type = GsonTypes.newParameterizedTypeWithOwner(GsonTypesTest.class, NonStaticInner.class, A.class); assertThat(type.getOwnerType()).isEqualTo(GsonTypesTest.class); assertThat(type.getRawType()).isEqualTo(NonStaticInner.class); assertThat(type.getActualTypeArguments()).asList().containsExactly(A.class); final class D {} // D is allowed since D has no owner type type = GsonTypes.newParameterizedTypeWithOwner(null, D.class, A.class); assertThat(type.getOwnerType()).isNull(); assertThat(type.getRawType()).isEqualTo(D.class); assertThat(type.getActualTypeArguments()).asList().containsExactly(A.class); // A is allowed. type = GsonTypes.newParameterizedTypeWithOwner(null, A.class, D.class); assertThat(getFirstTypeArgument(type)).isEqualTo(D.class); } @Test public void testGetFirstTypeArgument() throws Exception { assertThat(getFirstTypeArgument(A.class)).isNull(); Type type = GsonTypes.newParameterizedTypeWithOwner(null, A.class, B.class, C.class); assertThat(getFirstTypeArgument(type)).isEqualTo(B.class); } private static final class A {} private static final class B {} private static final class C {} @SuppressWarnings({"ClassCanBeStatic", "UnusedTypeParameter"}) private final class NonStaticInner {} /** * Given a parameterized type {@code A}, 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 GsonTypes.canonicalize(actualTypeArguments[0]); } @Test public void testEqualsOnMethodTypeVariables() throws Exception { Method m1 = TypeVariableTest.class.getDeclaredMethod("method"); Method m2 = TypeVariableTest.class.getDeclaredMethod("method"); Type rt1 = m1.getGenericReturnType(); Type rt2 = m2.getGenericReturnType(); assertThat(GsonTypes.equals(rt1, rt2)).isTrue(); } @Test public void testEqualsOnConstructorParameterTypeVariables() throws Exception { Constructor c1 = TypeVariableTest.class.getDeclaredConstructor(Object.class); Constructor c2 = TypeVariableTest.class.getDeclaredConstructor(Object.class); Type rt1 = c1.getGenericParameterTypes()[0]; Type rt2 = c2.getGenericParameterTypes()[0]; assertThat(GsonTypes.equals(rt1, rt2)).isTrue(); } private static final class TypeVariableTest { @SuppressWarnings("unused") TypeVariableTest(T parameter) {} @SuppressWarnings({"unused", "TypeParameterUnusedInFormals"}) T method() { return null; } } @Test public void testGetMapKeyAndValueTypesForPropertiesSubclass() throws Exception { class CustomProperties extends Properties { private static final long serialVersionUID = 4112578634029874840L; } Type[] types = GsonTypes.getMapKeyAndValueTypes(CustomProperties.class, CustomProperties.class); assertThat(types[0]).isEqualTo(String.class); assertThat(types[1]).isEqualTo(String.class); } } ================================================ FILE: gson/src/test/java/com/google/gson/internal/JavaVersionTest.java ================================================ /* * 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 com.google.common.truth.Truth.assertThat; 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() { // Gson currently requires at least Java 8 assertThat(JavaVersion.getMajorJavaVersion()).isAtLeast(8); } @Test public void testJava6() { // http://www.oracle.com/technetwork/java/javase/version-6-141920.html assertThat(JavaVersion.parseMajorJavaVersion("1.6.0")).isEqualTo(6); } @Test public void testJava7() { // http://www.oracle.com/technetwork/java/javase/jdk7-naming-418744.html assertThat(JavaVersion.parseMajorJavaVersion("1.7.0")).isEqualTo(7); } @Test public void testJava8() { assertThat(JavaVersion.parseMajorJavaVersion("1.8")).isEqualTo(8); assertThat(JavaVersion.parseMajorJavaVersion("1.8.0")).isEqualTo(8); assertThat(JavaVersion.parseMajorJavaVersion("1.8.0_131")).isEqualTo(8); assertThat(JavaVersion.parseMajorJavaVersion("1.8.0_60-ea")).isEqualTo(8); assertThat(JavaVersion.parseMajorJavaVersion("1.8.0_111-internal")).isEqualTo(8); // openjdk8 per https://github.com/AdoptOpenJDK/openjdk-build/issues/93 assertThat(JavaVersion.parseMajorJavaVersion("1.8.0-internal")).isEqualTo(8); assertThat(JavaVersion.parseMajorJavaVersion("1.8.0_131-adoptopenjdk")).isEqualTo(8); } @Test public void testJava9() { // Legacy style assertThat(JavaVersion.parseMajorJavaVersion("9.0.4")).isEqualTo(9); // Oracle JDK 9 // Debian as reported in https://github.com/google/gson/issues/1310 assertThat(JavaVersion.parseMajorJavaVersion("9-Debian")).isEqualTo(9); // New style assertThat(JavaVersion.parseMajorJavaVersion("9-ea+19")).isEqualTo(9); assertThat(JavaVersion.parseMajorJavaVersion("9+100")).isEqualTo(9); assertThat(JavaVersion.parseMajorJavaVersion("9.0.1+20")).isEqualTo(9); assertThat(JavaVersion.parseMajorJavaVersion("9.1.1+20")).isEqualTo(9); } @Test public void testJava10() { assertThat(JavaVersion.parseMajorJavaVersion("10.0.1")).isEqualTo(10); // Oracle JDK 10.0.1 } @Test public void testUnknownVersionFormat() { assertThat(JavaVersion.parseMajorJavaVersion("Java9")).isEqualTo(6); // unknown format } } ================================================ FILE: gson/src/test/java/com/google/gson/internal/LazilyParsedNumberTest.java ================================================ /* * 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 static com.google.common.truth.Truth.assertThat; 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 org.junit.Test; public class LazilyParsedNumberTest { @Test public void testHashCode() { LazilyParsedNumber n1 = new LazilyParsedNumber("1"); LazilyParsedNumber n1Another = new LazilyParsedNumber("1"); assertThat(n1Another.hashCode()).isEqualTo(n1.hashCode()); } @Test public void testEquals() { LazilyParsedNumber n1 = new LazilyParsedNumber("1"); LazilyParsedNumber n1Another = new LazilyParsedNumber("1"); assertThat(n1.equals(n1Another)).isTrue(); } @Test 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(); assertThat(deserialized).isEqualTo(new BigDecimal("123")); } } ================================================ FILE: gson/src/test/java/com/google/gson/internal/LinkedTreeMapSuiteTest.java ================================================ package com.google.gson.internal; import com.google.common.collect.testing.MapTestSuiteBuilder; import com.google.common.collect.testing.TestStringMapGenerator; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.Feature; import com.google.common.collect.testing.features.MapFeature; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Map.Entry; import junit.framework.Test; import junit.framework.TestSuite; import org.junit.runner.RunWith; import org.junit.runners.AllTests; /** * Dynamic {@link MapTestSuiteBuilder Map test suite} for {@link LinkedTreeMap}. This complements * {@link LinkedTreeMapTest}. */ @RunWith(AllTests.class) public class LinkedTreeMapSuiteTest { private static class MapGenerator extends TestStringMapGenerator { private final boolean allowNullValues; MapGenerator(boolean allowNullValues) { this.allowNullValues = allowNullValues; } @Override protected Map create(Entry[] entries) { // This is not completely accurate: Because LinkedTreeMap has no constructor which accepts // existing entries, this has to add the entries individually with `Map#put` var map = new LinkedTreeMap(allowNullValues); for (var entry : entries) { map.put(entry.getKey(), entry.getValue()); } return map; } } private static Feature[] createFeatures(Feature... additionalFeatures) { // Don't specify CollectionFeature.SERIALIZABLE because Guava testlib seems to assume // deserialized Map has same properties as original map (e.g. disallowing null keys), but this // is not the case for LinkedTreeMap which is serialized as JDK LinkedHashMap var features = new ArrayList>( List.of( CollectionSize.ANY, MapFeature.ALLOWS_ANY_NULL_QUERIES, MapFeature.RESTRICTS_KEYS, // Map only allows comparable keys MapFeature.SUPPORTS_PUT, MapFeature.SUPPORTS_REMOVE, // Affects keySet, values and entrySet (?) CollectionFeature.KNOWN_ORDER, // Map preserves insertion order CollectionFeature.SUPPORTS_ITERATOR_REMOVE)); features.addAll(Arrays.asList(additionalFeatures)); return features.toArray(Feature[]::new); } // Special method recognized by JUnit's `AllTests` runner public static Test suite() { var nullValuesSuite = MapTestSuiteBuilder.using(new MapGenerator(true)) .withFeatures(createFeatures(MapFeature.ALLOWS_NULL_VALUES)) .named("nullValues=true") .createTestSuite(); var nonNullValuesSuite = MapTestSuiteBuilder.using(new MapGenerator(false)) .withFeatures(createFeatures()) .named("nullValues=false") .createTestSuite(); // Use qualified class name to make it easier to find this test class in the IDE TestSuite testSuite = new TestSuite(LinkedTreeMapSuiteTest.class.getName()); testSuite.addTest(nullValuesSuite); testSuite.addTest(nonNullValuesSuite); return testSuite; } } ================================================ FILE: gson/src/test/java/com/google/gson/internal/LinkedTreeMapTest.java ================================================ /* * 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 static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import com.google.gson.common.MoreAsserts; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Collections; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import org.junit.Test; public final class LinkedTreeMapTest { @Test public void testIterationOrder() { LinkedTreeMap map = new LinkedTreeMap<>(); map.put("a", "android"); map.put("c", "cola"); map.put("b", "bbq"); assertThat(map.keySet()).containsExactly("a", "c", "b").inOrder(); assertThat(map.values()).containsExactly("android", "cola", "bbq").inOrder(); } @Test public void testRemoveRootDoesNotDoubleUnlink() { LinkedTreeMap map = new LinkedTreeMap<>(); map.put("a", "android"); map.put("c", "cola"); map.put("b", "bbq"); Iterator> it = map.entrySet().iterator(); it.next(); it.next(); it.next(); it.remove(); assertThat(map.keySet()).containsExactly("a", "c").inOrder(); } @Test @SuppressWarnings("ModifiedButNotUsed") public void testPutNullKeyFails() { LinkedTreeMap map = new LinkedTreeMap<>(); var e = assertThrows(NullPointerException.class, () -> map.put(null, "android")); assertThat(e).hasMessageThat().isEqualTo("key == null"); } @Test @SuppressWarnings("ModifiedButNotUsed") public void testPutNonComparableKeyFails() { LinkedTreeMap map = new LinkedTreeMap<>(); assertThrows(ClassCastException.class, () -> map.put(new Object(), "android")); } @Test public void testPutNullValue() { LinkedTreeMap map = new LinkedTreeMap<>(); map.put("a", null); assertThat(map).hasSize(1); assertThat(map.containsKey("a")).isTrue(); assertThat(map.containsValue(null)).isTrue(); assertThat(map.get("a")).isNull(); } @Test public void testPutNullValue_Forbidden() { LinkedTreeMap map = new LinkedTreeMap<>(false); var e = assertThrows(NullPointerException.class, () -> map.put("a", null)); assertThat(e).hasMessageThat().isEqualTo("value == null"); assertThat(map).hasSize(0); assertThat(map).doesNotContainKey("a"); assertThat(map.containsValue(null)).isFalse(); } @Test public void testEntrySetValueNull() { LinkedTreeMap map = new LinkedTreeMap<>(); map.put("a", "1"); assertThat(map.get("a")).isEqualTo("1"); Entry entry = map.entrySet().iterator().next(); assertThat(entry.getKey()).isEqualTo("a"); assertThat(entry.getValue()).isEqualTo("1"); entry.setValue(null); assertThat(entry.getValue()).isNull(); assertThat(map.containsKey("a")).isTrue(); assertThat(map.containsValue(null)).isTrue(); assertThat(map.get("a")).isNull(); } @Test public void testEntrySetValueNull_Forbidden() { LinkedTreeMap map = new LinkedTreeMap<>(false); map.put("a", "1"); Entry entry = map.entrySet().iterator().next(); var e = assertThrows(NullPointerException.class, () -> entry.setValue(null)); assertThat(e).hasMessageThat().isEqualTo("value == null"); assertThat(entry.getValue()).isEqualTo("1"); assertThat(map.get("a")).isEqualTo("1"); assertThat(map.containsValue(null)).isFalse(); } @Test public void testContainsNonComparableKeyReturnsFalse() { LinkedTreeMap map = new LinkedTreeMap<>(); map.put("a", "android"); assertThat(map).doesNotContainKey(new Object()); } @Test public void testContainsNullKeyIsAlwaysFalse() { LinkedTreeMap map = new LinkedTreeMap<>(); assertThat(map.containsKey(null)).isFalse(); map.put("a", "android"); assertThat(map.containsKey(null)).isFalse(); } @Test public void testPutOverrides() throws Exception { LinkedTreeMap map = new LinkedTreeMap<>(); assertThat(map.put("d", "donut")).isNull(); assertThat(map.put("e", "eclair")).isNull(); assertThat(map.put("f", "froyo")).isNull(); assertThat(map).hasSize(3); assertThat(map.get("d")).isEqualTo("donut"); assertThat(map.put("d", "done")).isEqualTo("donut"); assertThat(map).hasSize(3); } @Test public void testEmptyStringValues() { LinkedTreeMap map = new LinkedTreeMap<>(); map.put("a", ""); assertThat(map.containsKey("a")).isTrue(); assertThat(map.get("a")).isEqualTo(""); } @Test public void testLargeSetOfRandomKeys() { Random random = new Random(1367593214724L); LinkedTreeMap map = new LinkedTreeMap<>(); String[] keys = new String[1000]; for (int i = 0; i < keys.length; i++) { keys[i] = Integer.toString(random.nextInt(), 36) + "-" + i; map.put(keys[i], "" + i); } for (int i = 0; i < keys.length; i++) { String key = keys[i]; assertThat(map.containsKey(key)).isTrue(); assertThat(map.get(key)).isEqualTo("" + i); } } @Test public void testClear() { LinkedTreeMap map = new LinkedTreeMap<>(); map.put("a", "android"); map.put("c", "cola"); map.put("b", "bbq"); map.clear(); assertThat(map.keySet()).isEmpty(); assertThat(map).isEmpty(); } @Test public void testEqualsAndHashCode() throws Exception { LinkedTreeMap map1 = new LinkedTreeMap<>(); map1.put("A", 1); map1.put("B", 2); map1.put("C", 3); map1.put("D", 4); LinkedTreeMap map2 = new LinkedTreeMap<>(); map2.put("C", 3); map2.put("B", 2); map2.put("D", 4); map2.put("A", 1); MoreAsserts.assertEqualsAndHashCode(map1, map2); } @Test public void testJavaSerialization() throws IOException, ClassNotFoundException { ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream objOut = new ObjectOutputStream(out); Map map = new LinkedTreeMap<>(); map.put("a", 1); objOut.writeObject(map); objOut.close(); ObjectInputStream objIn = new ObjectInputStream(new ByteArrayInputStream(out.toByteArray())); @SuppressWarnings("unchecked") Map deserialized = (Map) objIn.readObject(); assertThat(deserialized).isEqualTo(Collections.singletonMap("a", 1)); } @Test public void testClearInvalidatesExistingIterator() { LinkedTreeMap map = new LinkedTreeMap<>(); map.put("key1", "value1"); map.put("key2", "value2"); map.put("key3", "value3"); Iterator> iterator = map.entrySet().iterator(); assertThat(iterator.hasNext()).isTrue(); map.clear(); assertThrows(ConcurrentModificationException.class, iterator::next); } @Test public void testClearInvalidatesExistingKeySetIterator() { LinkedTreeMap map = new LinkedTreeMap<>(); map.put("key1", "value1"); map.put("key2", "value2"); map.put("key3", "value3"); Iterator iterator = map.keySet().iterator(); assertThat(iterator.hasNext()).isTrue(); map.clear(); assertThrows(ConcurrentModificationException.class, iterator::next); } } ================================================ FILE: gson/src/test/java/com/google/gson/internal/StreamsTest.java ================================================ /* * Copyright (C) 2022 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 static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import java.io.Closeable; import java.io.Flushable; import java.io.IOException; import java.io.Writer; import org.junit.Test; public class StreamsTest { private static class TestAppendable implements Appendable, Flushable, Closeable { boolean closed = false; int flushCount = 0; Appendable append; TestAppendable(Appendable append) { this.append = append; } @Override public void close() { closed = true; } @Override public void flush() { flushCount++; } @Override public TestAppendable append(CharSequence csq) throws IOException { append.append(csq); return this; } @Override public TestAppendable append(CharSequence csq, int start, int end) throws IOException { append.append(csq, start, end); return this; } @Override public TestAppendable append(char c) throws IOException { append.append(c); return this; } } @Test public void testWriterForAppendable() throws IOException { StringBuilder stringBuilder = new StringBuilder(); TestAppendable appendable = new TestAppendable(stringBuilder); Writer writer = Streams.writerForAppendable(appendable); assertThat(appendable.closed).isFalse(); assertThat(appendable.flushCount).isEqualTo(0); writer.append('a'); writer.append('\u1234'); writer.append("test"); writer.append(null); // test custom null handling mandated by `append` writer.append("abcdef", 2, 4); writer.append(null, 1, 3); // test custom null handling mandated by `append` writer.append(','); writer.write('a'); writer.write('\u1234'); // Should only consider the 16 low-order bits writer.write(0x4321_1234); writer.append(','); writer.write("chars".toCharArray()); assertThrows(NullPointerException.class, () -> writer.write((char[]) null)); writer.write("chars".toCharArray(), 1, 2); assertThrows(NullPointerException.class, () -> writer.write((char[]) null, 1, 2)); writer.append(','); writer.write("string"); assertThrows(NullPointerException.class, () -> writer.write((String) null)); writer.write("string", 1, 2); assertThrows(NullPointerException.class, () -> writer.write((String) null, 1, 2)); String actualOutput = stringBuilder.toString(); assertThat(actualOutput).isEqualTo("a\u1234testnullcdul,a\u1234\u1234,charsha,stringtr"); writer.flush(); writer.close(); assertThat(appendable.closed).isTrue(); assertThat(appendable.flushCount).isEqualTo(1); assertThat(stringBuilder.toString()).isEqualTo(actualOutput); } } ================================================ FILE: gson/src/test/java/com/google/gson/internal/UnsafeAllocatorInstantiationTest.java ================================================ /* * 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 static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import org.junit.Test; /** * Test unsafe allocator instantiation * * @author Ugljesa Jovanovic */ public final class UnsafeAllocatorInstantiationTest { public interface Interface {} public abstract static class AbstractClass {} public static class ConcreteClass {} /** Ensure that an {@link AssertionError} is thrown when trying to instantiate an interface */ @Test public void testInterfaceInstantiation() { AssertionError e = assertThrows( AssertionError.class, () -> UnsafeAllocator.INSTANCE.newInstance(Interface.class)); assertThat(e).hasMessageThat().startsWith("UnsafeAllocator is used for non-instantiable type"); } /** * Ensure that an {@link AssertionError} is thrown when trying to instantiate an abstract class */ @Test public void testAbstractClassInstantiation() { AssertionError e = assertThrows( AssertionError.class, () -> UnsafeAllocator.INSTANCE.newInstance(AbstractClass.class)); assertThat(e).hasMessageThat().startsWith("UnsafeAllocator is used for non-instantiable type"); } /** Ensure that no exception is thrown when trying to instantiate a concrete class */ @Test public void testConcreteClassInstantiation() throws Exception { ConcreteClass instance = UnsafeAllocator.INSTANCE.newInstance(ConcreteClass.class); assertThat(instance).isNotNull(); } } ================================================ FILE: gson/src/test/java/com/google/gson/internal/bind/DefaultDateTypeAdapterTest.java ================================================ /* * 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 static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; import static org.junit.Assert.assertThrows; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.internal.bind.DefaultDateTypeAdapter.DateType; import com.google.gson.reflect.TypeToken; 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 org.junit.Test; /** * A simple unit test for the {@link DefaultDateTypeAdapter} class. * * @author Joel Leitch */ @SuppressWarnings("JavaUtilDate") public class DefaultDateTypeAdapterTest { @Test public void testFormattingInEnUs() { assertFormattingAlwaysEmitsUsLocale(Locale.US); } @Test public void testFormattingInFr() { assertFormattingAlwaysEmitsUsLocale(Locale.FRANCE); } private static void assertFormattingAlwaysEmitsUsLocale(Locale locale) { TimeZone defaultTimeZone = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("UTC")); Locale defaultLocale = Locale.getDefault(); Locale.setDefault(locale); try { // The patterns here attempt to accommodate minor date-time formatting differences between JDK // versions. Ideally Gson would serialize in a way that is independent of the JDK version. // Note: \h means "horizontal space", because some JDK versions use Narrow No Break Space // (U+202F) before the AM or PM indication. String utcFull = "(Coordinated Universal Time|UTC)"; assertFormatted("Jan 1, 1970,? 12:00:00\\hAM", DefaultDateTypeAdapter.DEFAULT_STYLE_FACTORY); assertFormatted( "1/1/70,? 12:00\\hAM", DateType.DATE.createAdapterFactory(DateFormat.SHORT, DateFormat.SHORT)); assertFormatted( "Jan 1, 1970,? 12:00:00\\hAM", DateType.DATE.createAdapterFactory(DateFormat.MEDIUM, DateFormat.MEDIUM)); assertFormatted( "January 1, 1970(,| at)? 12:00:00\\hAM UTC", DateType.DATE.createAdapterFactory(DateFormat.LONG, DateFormat.LONG)); assertFormatted( "Thursday, January 1, 1970(,| at)? 12:00:00\\hAM " + utcFull, DateType.DATE.createAdapterFactory(DateFormat.FULL, DateFormat.FULL)); } finally { TimeZone.setDefault(defaultTimeZone); Locale.setDefault(defaultLocale); } } @Test public void testParsingDatesFormattedWithSystemLocale() throws Exception { TimeZone defaultTimeZone = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("UTC")); Locale defaultLocale = Locale.getDefault(); Locale.setDefault(Locale.FRANCE); try { Date date = new Date(0); assertParsed( DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM).format(date), DefaultDateTypeAdapter.DEFAULT_STYLE_FACTORY); assertParsed( DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(date), DateType.DATE.createAdapterFactory(DateFormat.SHORT, DateFormat.SHORT)); assertParsed( DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM).format(date), DateType.DATE.createAdapterFactory(DateFormat.MEDIUM, DateFormat.MEDIUM)); assertParsed( DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG).format(date), DateType.DATE.createAdapterFactory(DateFormat.LONG, DateFormat.LONG)); assertParsed( DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(date), DateType.DATE.createAdapterFactory(DateFormat.FULL, DateFormat.FULL)); } finally { TimeZone.setDefault(defaultTimeZone); Locale.setDefault(defaultLocale); } } @Test 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", DefaultDateTypeAdapter.DEFAULT_STYLE_FACTORY); 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); } } @Test 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 { assertFormatted("Dec 31, 1969,? 4:00:00\\hPM", DefaultDateTypeAdapter.DEFAULT_STYLE_FACTORY); assertParsed("Dec 31, 1969 4:00:00 PM", DefaultDateTypeAdapter.DEFAULT_STYLE_FACTORY); } finally { TimeZone.setDefault(defaultTimeZone); Locale.setDefault(defaultLocale); } } @Test public void testDateDeserializationISO8601() throws Exception { TypeAdapterFactory adapterFactory = DefaultDateTypeAdapter.DEFAULT_STYLE_FACTORY; 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); } @Test public void testDatePattern() { String pattern = "yyyy-MM-dd"; TypeAdapter dateTypeAdapter = dateAdapter(DateType.DATE.createAdapterFactory(pattern)); DateFormat formatter = new SimpleDateFormat(pattern); Date currentDate = new Date(); String dateString = dateTypeAdapter.toJson(currentDate); assertThat(dateString).isEqualTo(toLiteral(formatter.format(currentDate))); } @Test public void testInvalidDatePattern() { assertThrows( IllegalArgumentException.class, () -> DateType.DATE.createAdapterFactory("I am a bad Date pattern....")); } @Test public void testNullValue() throws Exception { TypeAdapter adapter = dateAdapter(DefaultDateTypeAdapter.DEFAULT_STYLE_FACTORY); assertThat(adapter.fromJson("null")).isNull(); assertThat(adapter.toJson(null)).isEqualTo("null"); } @Test public void testUnexpectedToken() throws Exception { TypeAdapter adapter = dateAdapter(DefaultDateTypeAdapter.DEFAULT_STYLE_FACTORY); IllegalStateException e = assertThrows(IllegalStateException.class, () -> adapter.fromJson("{}")); assertThat(e).hasMessageThat().startsWith("Expected a string but was BEGIN_OBJECT"); } @Test public void testGsonDateFormat() { TimeZone originalTimeZone = TimeZone.getDefault(); // Set the default timezone to UTC TimeZone.setDefault(TimeZone.getTimeZone("UTC")); try { Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm z").create(); Date originalDate = new Date(0); // Serialize the date object String json = gson.toJson(originalDate); assertThat(json).isEqualTo("\"1970-01-01 00:00 UTC\""); // Deserialize a date string with the PST timezone Date deserializedDate = gson.fromJson("\"1970-01-01 00:00 PST\"", Date.class); // Assert that the deserialized date's time is correct assertThat(deserializedDate.getTime()).isEqualTo(new Date(28800000).getTime()); // Serialize the deserialized date object again String jsonAfterDeserialization = gson.toJson(deserializedDate); // The expectation is that the date, after deserialization, when serialized again should still // be in the UTC timezone assertThat(jsonAfterDeserialization).isEqualTo("\"1970-01-01 08:00 UTC\""); } finally { TimeZone.setDefault(originalTimeZone); } } private static TypeAdapter dateAdapter(TypeAdapterFactory adapterFactory) { TypeAdapter adapter = adapterFactory.create(new Gson(), TypeToken.get(Date.class)); assertThat(adapter).isNotNull(); return adapter; } private static void assertFormatted(String formattedPattern, TypeAdapterFactory adapterFactory) { TypeAdapter adapter = dateAdapter(adapterFactory); String json = adapter.toJson(new Date(0)); assertThat(json).matches(toLiteral(formattedPattern)); } @SuppressWarnings("UndefinedEquals") private static void assertParsed(String date, TypeAdapterFactory adapterFactory) throws IOException { TypeAdapter adapter = dateAdapter(adapterFactory); assertWithMessage(date).that(adapter.fromJson(toLiteral(date))).isEqualTo(new Date(0)); assertWithMessage("ISO 8601") .that(adapter.fromJson(toLiteral("1970-01-01T00:00:00Z"))) .isEqualTo(new Date(0)); } private static String toLiteral(String s) { return '"' + s + '"'; } } ================================================ FILE: gson/src/test/java/com/google/gson/internal/bind/Java17ReflectiveTypeAdapterFactoryTest.java ================================================ /* * Copyright (C) 2022 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 static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.TypeAdapter; import com.google.gson.internal.reflect.Java17ReflectionHelperTest; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.nio.file.attribute.GroupPrincipal; import java.nio.file.attribute.UserPrincipal; import java.security.Principal; import org.junit.Before; import org.junit.Test; public class Java17ReflectiveTypeAdapterFactoryTest { // The class jdk.net.UnixDomainPrincipal is one of the few Record types that are included in the // JDK. // We use this to test serialization and deserialization of Record classes, so we do not need to // have record support at the language level for these tests. This class was added in JDK 16. Class unixDomainPrincipalClass; @Before public void setUp() throws Exception { unixDomainPrincipalClass = Class.forName("jdk.net.UnixDomainPrincipal"); } // Class for which the normal reflection based adapter is used private static class DummyClass { @SuppressWarnings("unused") String s; } @Test public void testCustomAdapterForRecords() { Gson gson = new Gson(); TypeAdapter recordAdapter = gson.getAdapter(unixDomainPrincipalClass); TypeAdapter defaultReflectionAdapter = gson.getAdapter(DummyClass.class); assertThat(defaultReflectionAdapter.getClass()).isNotEqualTo(recordAdapter.getClass()); } @Test public void testSerializeRecords() throws ReflectiveOperationException { Gson gson = new GsonBuilder() .registerTypeAdapter(UserPrincipal.class, new PrincipalTypeAdapter<>()) .registerTypeAdapter(GroupPrincipal.class, new PrincipalTypeAdapter<>()) .create(); UserPrincipal userPrincipal = gson.fromJson("\"user\"", UserPrincipal.class); GroupPrincipal groupPrincipal = gson.fromJson("\"group\"", GroupPrincipal.class); Object recordInstance = unixDomainPrincipalClass .getDeclaredConstructor(UserPrincipal.class, GroupPrincipal.class) .newInstance(userPrincipal, groupPrincipal); String serialized = gson.toJson(recordInstance); Object deserializedRecordInstance = gson.fromJson(serialized, unixDomainPrincipalClass); assertThat(deserializedRecordInstance).isEqualTo(recordInstance); assertThat(serialized).isEqualTo("{\"user\":\"user\",\"group\":\"group\"}"); } private static class PrincipalTypeAdapter extends TypeAdapter { @Override public void write(JsonWriter out, T principal) throws IOException { out.value(principal.getName()); } @Override public T read(JsonReader in) throws IOException { String name = in.nextString(); // This type adapter is only used for Group and User Principal, both of which are implemented // by PrincipalImpl. @SuppressWarnings("unchecked") T principal = (T) new Java17ReflectionHelperTest.PrincipalImpl(name); return principal; } } } ================================================ FILE: gson/src/test/java/com/google/gson/internal/bind/JsonElementReaderTest.java ================================================ /* * 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 static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.google.gson.JsonPrimitive; import com.google.gson.Strictness; import com.google.gson.stream.JsonToken; import com.google.gson.stream.MalformedJsonException; import java.io.IOException; import org.junit.Test; @SuppressWarnings("resource") public final class JsonElementReaderTest { @Test public void testNumbers() throws IOException { JsonElement element = JsonParser.parseString("[1, 2, 3]"); JsonTreeReader reader = new JsonTreeReader(element); reader.beginArray(); assertThat(reader.nextInt()).isEqualTo(1); assertThat(reader.nextLong()).isEqualTo(2L); assertThat(reader.nextDouble()).isEqualTo(3.0); reader.endArray(); } @Test public void testLenientNansAndInfinities() throws IOException { JsonElement element = JsonParser.parseString("[NaN, -Infinity, Infinity]"); JsonTreeReader reader = new JsonTreeReader(element); reader.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.nextDouble()).isNaN(); assertThat(reader.nextDouble()).isEqualTo(Double.NEGATIVE_INFINITY); assertThat(reader.nextDouble()).isEqualTo(Double.POSITIVE_INFINITY); reader.endArray(); } @Test public void testStrictNansAndInfinities() throws IOException { JsonElement element = JsonParser.parseString("[NaN, -Infinity, Infinity]"); JsonTreeReader reader = new JsonTreeReader(element); reader.setStrictness(Strictness.LEGACY_STRICT); reader.beginArray(); var e = assertThrows(MalformedJsonException.class, () -> reader.nextDouble()); assertThat(e).hasMessageThat().isEqualTo("JSON forbids NaN and infinities: NaN"); assertThat(reader.nextString()).isEqualTo("NaN"); e = assertThrows(MalformedJsonException.class, () -> reader.nextDouble()); assertThat(e).hasMessageThat().isEqualTo("JSON forbids NaN and infinities: -Infinity"); assertThat(reader.nextString()).isEqualTo("-Infinity"); e = assertThrows(MalformedJsonException.class, () -> reader.nextDouble()); assertThat(e).hasMessageThat().isEqualTo("JSON forbids NaN and infinities: Infinity"); assertThat(reader.nextString()).isEqualTo("Infinity"); reader.endArray(); } @Test public void testNumbersFromStrings() throws IOException { JsonElement element = JsonParser.parseString("[\"1\", \"2\", \"3\"]"); JsonTreeReader reader = new JsonTreeReader(element); reader.beginArray(); assertThat(reader.nextInt()).isEqualTo(1); assertThat(reader.nextLong()).isEqualTo(2L); assertThat(reader.nextDouble()).isEqualTo(3.0); reader.endArray(); } @Test public void testStringsFromNumbers() throws IOException { JsonElement element = JsonParser.parseString("[1]"); JsonTreeReader reader = new JsonTreeReader(element); reader.beginArray(); assertThat(reader.nextString()).isEqualTo("1"); reader.endArray(); } @Test public void testBooleans() throws IOException { JsonElement element = JsonParser.parseString("[true, false]"); JsonTreeReader reader = new JsonTreeReader(element); reader.beginArray(); assertThat(reader.nextBoolean()).isEqualTo(true); assertThat(reader.nextBoolean()).isEqualTo(false); reader.endArray(); } @Test public void testNulls() throws IOException { JsonElement element = JsonParser.parseString("[null,null]"); JsonTreeReader reader = new JsonTreeReader(element); reader.beginArray(); reader.nextNull(); reader.nextNull(); reader.endArray(); } @Test public void testStrings() throws IOException { JsonElement element = JsonParser.parseString("[\"A\",\"B\"]"); JsonTreeReader reader = new JsonTreeReader(element); reader.beginArray(); assertThat(reader.nextString()).isEqualTo("A"); assertThat(reader.nextString()).isEqualTo("B"); reader.endArray(); } @Test public void testArray() throws IOException { JsonElement element = JsonParser.parseString("[1, 2, 3]"); JsonTreeReader reader = new JsonTreeReader(element); assertThat(reader.peek()).isEqualTo(JsonToken.BEGIN_ARRAY); reader.beginArray(); assertThat(reader.peek()).isEqualTo(JsonToken.NUMBER); assertThat(reader.nextInt()).isEqualTo(1); assertThat(reader.peek()).isEqualTo(JsonToken.NUMBER); assertThat(reader.nextInt()).isEqualTo(2); assertThat(reader.peek()).isEqualTo(JsonToken.NUMBER); assertThat(reader.nextInt()).isEqualTo(3); assertThat(reader.peek()).isEqualTo(JsonToken.END_ARRAY); reader.endArray(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test public void testObject() throws IOException { JsonElement element = JsonParser.parseString("{\"A\": 1, \"B\": 2}"); JsonTreeReader reader = new JsonTreeReader(element); assertThat(reader.peek()).isEqualTo(JsonToken.BEGIN_OBJECT); reader.beginObject(); assertThat(reader.peek()).isEqualTo(JsonToken.NAME); assertThat(reader.nextName()).isEqualTo("A"); assertThat(reader.peek()).isEqualTo(JsonToken.NUMBER); assertThat(reader.nextInt()).isEqualTo(1); assertThat(reader.peek()).isEqualTo(JsonToken.NAME); assertThat(reader.nextName()).isEqualTo("B"); assertThat(reader.peek()).isEqualTo(JsonToken.NUMBER); assertThat(reader.nextInt()).isEqualTo(2); assertThat(reader.peek()).isEqualTo(JsonToken.END_OBJECT); reader.endObject(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test public void testEmptyArray() throws IOException { JsonElement element = JsonParser.parseString("[]"); JsonTreeReader reader = new JsonTreeReader(element); reader.beginArray(); reader.endArray(); } @Test 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(); } @Test public void testNestedObjects() throws IOException { JsonElement element = JsonParser.parseString("{\"A\":{},\"B\":{\"C\":{}}}"); JsonTreeReader reader = new JsonTreeReader(element); reader.beginObject(); assertThat(reader.nextName()).isEqualTo("A"); reader.beginObject(); reader.endObject(); assertThat(reader.nextName()).isEqualTo("B"); reader.beginObject(); assertThat(reader.nextName()).isEqualTo("C"); reader.beginObject(); reader.endObject(); reader.endObject(); reader.endObject(); } @Test public void testEmptyObject() throws IOException { JsonElement element = JsonParser.parseString("{}"); JsonTreeReader reader = new JsonTreeReader(element); reader.beginObject(); reader.endObject(); } @Test public void testSkipValue() throws IOException { JsonElement element = JsonParser.parseString("[\"A\",{\"B\":[[]]},\"C\",[[]],\"D\",null]"); JsonTreeReader reader = new JsonTreeReader(element); reader.beginArray(); assertThat(reader.nextString()).isEqualTo("A"); reader.skipValue(); assertThat(reader.nextString()).isEqualTo("C"); reader.skipValue(); assertThat(reader.nextString()).isEqualTo("D"); reader.skipValue(); reader.endArray(); } @Test public void testWrongType() throws IOException { JsonElement element = JsonParser.parseString("[[],\"A\"]"); JsonTreeReader reader = new JsonTreeReader(element); reader.beginArray(); assertThrows(IllegalStateException.class, () -> reader.nextBoolean()); assertThrows(IllegalStateException.class, () -> reader.nextNull()); assertThrows(IllegalStateException.class, () -> reader.nextString()); assertThrows(IllegalStateException.class, () -> reader.nextInt()); assertThrows(IllegalStateException.class, () -> reader.nextLong()); assertThrows(IllegalStateException.class, () -> reader.nextDouble()); assertThrows(IllegalStateException.class, () -> reader.nextName()); assertThrows(IllegalStateException.class, () -> reader.beginObject()); assertThrows(IllegalStateException.class, () -> reader.endArray()); assertThrows(IllegalStateException.class, () -> reader.endObject()); reader.beginArray(); reader.endArray(); assertThrows(IllegalStateException.class, () -> reader.nextBoolean()); assertThrows(IllegalStateException.class, () -> reader.nextNull()); assertThrows(NumberFormatException.class, () -> reader.nextInt()); assertThrows(NumberFormatException.class, () -> reader.nextLong()); assertThrows(NumberFormatException.class, () -> reader.nextDouble()); assertThrows(IllegalStateException.class, () -> reader.nextName()); assertThat(reader.nextString()).isEqualTo("A"); reader.endArray(); } @Test public void testNextJsonElement() throws IOException { JsonElement element = JsonParser.parseString("{\"A\": 1, \"B\" : {}, \"C\" : []}"); JsonTreeReader reader = new JsonTreeReader(element); reader.beginObject(); var e = assertThrows(IllegalStateException.class, () -> reader.nextJsonElement()); assertThat(e).hasMessageThat().isEqualTo("Unexpected NAME when reading a JsonElement."); assertThat(reader.nextName()).isEqualTo("A"); assertThat(reader.nextJsonElement()).isEqualTo(new JsonPrimitive(1)); assertThat(reader.nextName()).isEqualTo("B"); reader.beginObject(); assertThrows(IllegalStateException.class, () -> reader.nextJsonElement()); reader.endObject(); assertThat(reader.nextName()).isEqualTo("C"); reader.beginArray(); assertThrows(IllegalStateException.class, () -> reader.nextJsonElement()); reader.endArray(); reader.endObject(); assertThrows(IllegalStateException.class, () -> reader.nextJsonElement()); } @Test public void testEarlyClose() throws IOException { JsonElement element = JsonParser.parseString("[1, 2, 3]"); JsonTreeReader reader = new JsonTreeReader(element); reader.beginArray(); reader.close(); var e = assertThrows(IllegalStateException.class, () -> reader.peek()); assertThat(e).hasMessageThat().isEqualTo("JsonReader is closed"); } } ================================================ FILE: gson/src/test/java/com/google/gson/internal/bind/JsonTreeReaderTest.java ================================================ /* * 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 static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonNull; import com.google.gson.JsonObject; import com.google.gson.common.MoreAsserts; 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.util.Arrays; import java.util.List; import org.junit.Test; @SuppressWarnings("resource") public class JsonTreeReaderTest { @Test public void testSkipValue_emptyJsonObject() throws IOException { JsonTreeReader in = new JsonTreeReader(new JsonObject()); in.skipValue(); assertThat(in.peek()).isEqualTo(JsonToken.END_DOCUMENT); assertThat(in.getPath()).isEqualTo("$"); } @Test 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(); assertThat(in.peek()).isEqualTo(JsonToken.END_DOCUMENT); assertThat(in.getPath()).isEqualTo("$"); } @Test public void testSkipValue_name() throws IOException { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("a", "value"); JsonTreeReader in = new JsonTreeReader(jsonObject); in.beginObject(); in.skipValue(); assertThat(in.peek()).isEqualTo(JsonToken.STRING); assertThat(in.getPath()).isEqualTo("$."); assertThat(in.nextString()).isEqualTo("value"); } @Test public void testSkipValue_afterEndOfDocument() throws IOException { JsonTreeReader reader = new JsonTreeReader(new JsonObject()); reader.beginObject(); reader.endObject(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); assertThat(reader.getPath()).isEqualTo("$"); reader.skipValue(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); assertThat(reader.getPath()).isEqualTo("$"); } @Test public void testSkipValue_atArrayEnd() throws IOException { JsonTreeReader reader = new JsonTreeReader(new JsonArray()); reader.beginArray(); reader.skipValue(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); assertThat(reader.getPath()).isEqualTo("$"); } @Test public void testSkipValue_atObjectEnd() throws IOException { JsonTreeReader reader = new JsonTreeReader(new JsonObject()); reader.beginObject(); reader.skipValue(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); assertThat(reader.getPath()).isEqualTo("$"); } @Test public void testHasNext_endOfDocument() throws IOException { JsonTreeReader reader = new JsonTreeReader(new JsonObject()); reader.beginObject(); reader.endObject(); assertThat(reader.hasNext()).isFalse(); } @Test public void testCustomJsonElementSubclass() throws IOException { @SuppressWarnings("deprecation") // superclass constructor class CustomSubclass extends JsonElement { @Override public JsonElement deepCopy() { return this; } } JsonArray array = new JsonArray(); array.add(new CustomSubclass()); JsonTreeReader reader = new JsonTreeReader(array); reader.beginArray(); // Should fail due to custom JsonElement subclass var e = assertThrows(MalformedJsonException.class, () -> reader.peek()); assertThat(e) .hasMessageThat() .isEqualTo( "Custom JsonElement subclass " + CustomSubclass.class.getName() + " is not supported"); } /** * {@link JsonTreeReader} ignores nesting limit because: * *

*/ @Test public void testNestingLimitIgnored() throws IOException { int limit = 10; JsonArray json = new JsonArray(); JsonArray current = json; // This adds additional `limit` nested arrays, so in total there are `limit + 1` arrays for (int i = 0; i < limit; i++) { JsonArray nested = new JsonArray(); current.add(nested); current = nested; } JsonTreeReader reader = new JsonTreeReader(json); reader.setNestingLimit(limit); assertThat(reader.getNestingLimit()).isEqualTo(limit); for (int i = 0; i < limit; i++) { reader.beginArray(); } // Does not throw exception; limit is ignored reader.beginArray(); reader.endArray(); for (int i = 0; i < limit; i++) { reader.endArray(); } assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); reader.close(); } /** * {@link JsonTreeReader} effectively replaces the complete reading logic of {@link JsonReader} to * read from a {@link JsonElement} instead of a {@link Reader}. Therefore all relevant methods of * {@code JsonReader} must be overridden. */ @Test public void testOverrides() { List ignoredMethods = Arrays.asList( "setLenient(boolean)", "isLenient()", "setStrictness(com.google.gson.Strictness)", "getStrictness()", "setNestingLimit(int)", "getNestingLimit()"); MoreAsserts.assertOverridesMethods(JsonReader.class, JsonTreeReader.class, ignoredMethods); } } ================================================ FILE: gson/src/test/java/com/google/gson/internal/bind/JsonTreeWriterTest.java ================================================ /* * 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 static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import com.google.gson.JsonElement; import com.google.gson.JsonNull; import com.google.gson.Strictness; import com.google.gson.common.MoreAsserts; import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.io.Writer; import java.util.Arrays; import java.util.List; import org.junit.Test; @SuppressWarnings("resource") public final class JsonTreeWriterTest { @Test public void testArray() throws IOException { JsonTreeWriter writer = new JsonTreeWriter(); writer.beginArray(); writer.value(1); writer.value(2); writer.value(3); writer.endArray(); assertThat(writer.get().toString()).isEqualTo("[1,2,3]"); } @Test 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(); assertThat(writer.get().toString()).isEqualTo("[[],[[]]]"); } @Test public void testObject() throws IOException { JsonTreeWriter writer = new JsonTreeWriter(); writer.beginObject(); writer.name("A").value(1); writer.name("B").value(2); writer.endObject(); assertThat(writer.get().toString()).isEqualTo("{\"A\":1,\"B\":2}"); } @Test 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(); assertThat(writer.get().toString()).isEqualTo("{\"A\":{\"B\":{}},\"C\":{}}"); } @Test public void testWriteAfterClose() throws Exception { JsonTreeWriter writer = new JsonTreeWriter(); writer.setStrictness(Strictness.LENIENT); writer.beginArray(); writer.value("A"); writer.endArray(); writer.close(); assertThrows(IllegalStateException.class, () -> writer.beginArray()); } @Test public void testPrematureClose() throws Exception { JsonTreeWriter writer = new JsonTreeWriter(); writer.setStrictness(Strictness.LENIENT); writer.beginArray(); var e = assertThrows(IOException.class, () -> writer.close()); assertThat(e).hasMessageThat().isEqualTo("Incomplete document"); } @Test public void testNameAsTopLevelValue() throws IOException { JsonTreeWriter writer = new JsonTreeWriter(); IllegalStateException e = assertThrows(IllegalStateException.class, () -> writer.name("hello")); assertThat(e).hasMessageThat().isEqualTo("Did not expect a name"); writer.value(12); writer.close(); e = assertThrows(IllegalStateException.class, () -> writer.name("hello")); assertThat(e).hasMessageThat().isEqualTo("Please begin an object before writing a name."); } @Test public void testNameInArray() throws IOException { JsonTreeWriter writer = new JsonTreeWriter(); writer.beginArray(); IllegalStateException e = assertThrows(IllegalStateException.class, () -> writer.name("hello")); assertThat(e).hasMessageThat().isEqualTo("Please begin an object before writing a name."); writer.value(12); e = assertThrows(IllegalStateException.class, () -> writer.name("hello")); assertThat(e).hasMessageThat().isEqualTo("Please begin an object before writing a name."); writer.endArray(); assertThat(writer.get().toString()).isEqualTo("[12]"); } @Test public void testTwoNames() throws IOException { JsonTreeWriter writer = new JsonTreeWriter(); writer.beginObject(); writer.name("a"); IllegalStateException e = assertThrows(IllegalStateException.class, () -> writer.name("a")); assertThat(e).hasMessageThat().isEqualTo("Did not expect a name"); } @Test public void testSerializeNullsFalse() throws IOException { JsonTreeWriter writer = new JsonTreeWriter(); writer.setSerializeNulls(false); writer.beginObject(); writer.name("A"); writer.nullValue(); writer.endObject(); assertThat(writer.get().toString()).isEqualTo("{}"); } @Test public void testSerializeNullsTrue() throws IOException { JsonTreeWriter writer = new JsonTreeWriter(); writer.setSerializeNulls(true); writer.beginObject(); writer.name("A"); writer.nullValue(); writer.endObject(); assertThat(writer.get().toString()).isEqualTo("{\"A\":null}"); } @Test public void testEmptyWriter() { JsonTreeWriter writer = new JsonTreeWriter(); assertThat(writer.get()).isEqualTo(JsonNull.INSTANCE); } @Test public void testBeginArray() throws Exception { JsonTreeWriter writer = new JsonTreeWriter(); assertThat(writer.beginArray()).isEqualTo(writer); } @Test public void testBeginObject() throws Exception { JsonTreeWriter writer = new JsonTreeWriter(); assertThat(writer.beginObject()).isEqualTo(writer); } @Test public void testValueString() throws Exception { JsonTreeWriter writer = new JsonTreeWriter(); String n = "as"; assertThat(writer.value(n)).isEqualTo(writer); } @Test public void testBoolValue() throws Exception { JsonTreeWriter writer = new JsonTreeWriter(); boolean bool = true; assertThat(writer.value(bool)).isEqualTo(writer); } @Test public void testBoolMaisValue() throws Exception { JsonTreeWriter writer = new JsonTreeWriter(); Boolean bool = true; assertThat(writer.value(bool)).isEqualTo(writer); } @Test public void testLenientNansAndInfinities() throws IOException { JsonTreeWriter writer = new JsonTreeWriter(); writer.setStrictness(Strictness.LENIENT); 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(); assertThat(writer.get().toString()) .isEqualTo("[NaN,-Infinity,Infinity,NaN,-Infinity,Infinity]"); } @Test public void testStrictNansAndInfinities() throws IOException { JsonTreeWriter writer = new JsonTreeWriter(); writer.setStrictness(Strictness.LEGACY_STRICT); writer.beginArray(); assertThrows(IllegalArgumentException.class, () -> writer.value(Float.NaN)); assertThrows(IllegalArgumentException.class, () -> writer.value(Float.NEGATIVE_INFINITY)); assertThrows(IllegalArgumentException.class, () -> writer.value(Float.POSITIVE_INFINITY)); assertThrows(IllegalArgumentException.class, () -> writer.value(Double.NaN)); assertThrows(IllegalArgumentException.class, () -> writer.value(Double.NEGATIVE_INFINITY)); assertThrows(IllegalArgumentException.class, () -> writer.value(Double.POSITIVE_INFINITY)); } @Test public void testStrictBoxedNansAndInfinities() throws IOException { JsonTreeWriter writer = new JsonTreeWriter(); writer.setStrictness(Strictness.LEGACY_STRICT); writer.beginArray(); assertThrows(IllegalArgumentException.class, () -> writer.value(Float.valueOf(Float.NaN))); assertThrows( IllegalArgumentException.class, () -> writer.value(Float.valueOf(Float.NEGATIVE_INFINITY))); assertThrows( IllegalArgumentException.class, () -> writer.value(Float.valueOf(Float.POSITIVE_INFINITY))); assertThrows(IllegalArgumentException.class, () -> writer.value(Double.valueOf(Double.NaN))); assertThrows( IllegalArgumentException.class, () -> writer.value(Double.valueOf(Double.NEGATIVE_INFINITY))); assertThrows( IllegalArgumentException.class, () -> writer.value(Double.valueOf(Double.POSITIVE_INFINITY))); } @Test public void testJsonValue() throws IOException { JsonTreeWriter writer = new JsonTreeWriter(); writer.beginArray(); assertThrows(UnsupportedOperationException.class, () -> writer.jsonValue("test")); } /** * {@link JsonTreeWriter} effectively replaces the complete writing logic of {@link JsonWriter} to * create a {@link JsonElement} tree instead of writing to a {@link Writer}. Therefore all * relevant methods of {@code JsonWriter} must be overridden. */ @Test public void testOverrides() { List ignoredMethods = Arrays.asList( "setLenient(boolean)", "isLenient()", "setStrictness(com.google.gson.Strictness)", "getStrictness()", "setIndent(java.lang.String)", "setHtmlSafe(boolean)", "isHtmlSafe()", "setFormattingStyle(com.google.gson.FormattingStyle)", "getFormattingStyle()", "setSerializeNulls(boolean)", "getSerializeNulls()"); MoreAsserts.assertOverridesMethods(JsonWriter.class, JsonTreeWriter.class, ignoredMethods); } @Test public void testEndArrayOnEmptyStackThrows() { JsonTreeWriter writer = new JsonTreeWriter(); assertThrows(IllegalStateException.class, () -> writer.endArray()); } @Test public void testEndArrayWithPendingNameThrows() throws IOException { JsonTreeWriter writer = new JsonTreeWriter(); writer.beginObject(); writer.name("test"); assertThrows(IllegalStateException.class, () -> writer.endArray()); } @Test public void testEndArrayWhenStackTopIsNotArrayThrows() throws IOException { JsonTreeWriter writer = new JsonTreeWriter(); writer.beginObject(); assertThrows(IllegalStateException.class, () -> writer.endArray()); } } ================================================ FILE: gson/src/test/java/com/google/gson/internal/bind/RecursiveTypesResolveTest.java ================================================ /* * 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 static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.internal.GsonTypes; import org.junit.Test; /** * Test fixes for infinite recursion on {@link GsonTypes#resolve(java.lang.reflect.Type, Class, * java.lang.reflect.Type)}, described at Issue * #440 and similar issues. * *

These tests originally caused {@link StackOverflowError} because of infinite recursion on * attempts to resolve generics on types, with intermediate types like {@code Foo2} */ public class RecursiveTypesResolveTest { @SuppressWarnings("unused") private static class Foo1 { Foo2 foo2; } @SuppressWarnings("unused") private static class Foo2 { Foo1 foo1; } /** Test simplest case of recursion. */ @Test public void testRecursiveResolveSimple() { @SuppressWarnings("rawtypes") TypeAdapter adapter = new Gson().getAdapter(Foo1.class); assertThat(adapter).isNotNull(); } /** Tests below check the behavior of the methods changed for the fix. */ @Test public void testDoubleSupertype() { assertThat(GsonTypes.supertypeOf(GsonTypes.supertypeOf(Number.class))) .isEqualTo(GsonTypes.supertypeOf(Number.class)); } @Test public void testDoubleSubtype() { assertThat(GsonTypes.subtypeOf(GsonTypes.subtypeOf(Number.class))) .isEqualTo(GsonTypes.subtypeOf(Number.class)); } @Test public void testSuperSubtype() { assertThat(GsonTypes.supertypeOf(GsonTypes.subtypeOf(Number.class))) .isEqualTo(GsonTypes.subtypeOf(Object.class)); } @Test public void testSubSupertype() { assertThat(GsonTypes.subtypeOf(GsonTypes.supertypeOf(Number.class))) .isEqualTo(GsonTypes.subtypeOf(Object.class)); } /** Tests for recursion while resolving type variables. */ @SuppressWarnings("unused") private static class TestType { TestType superType; } @SuppressWarnings("unused") private static class TestType2 { TestType2 superReversedType; } @Test public void testRecursiveTypeVariablesResolve1() { @SuppressWarnings("rawtypes") TypeAdapter adapter = new Gson().getAdapter(TestType.class); assertThat(adapter).isNotNull(); } @Test public void testRecursiveTypeVariablesResolve12() { @SuppressWarnings("rawtypes") TypeAdapter adapter = new Gson().getAdapter(TestType2.class); assertThat(adapter).isNotNull(); } } ================================================ FILE: gson/src/test/java/com/google/gson/internal/bind/util/ISO8601UtilsTest.java ================================================ /* * 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.util; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; 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; @SuppressWarnings("MemberName") // class name 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-25T00:00:00Z"; assertThat(dateStr).isEqualTo(expectedDate); } @Test @SuppressWarnings("JavaUtilDate") 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"; assertThat(dateStr).isEqualTo(expectedDate); } @Test @SuppressWarnings("JavaUtilDate") 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"; assertThat(dateStr).isEqualTo(expectedDate); } @Test @SuppressWarnings("UndefinedEquals") 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(); assertThat(date).isEqualTo(expectedDate); } @Test public void testDateParseInvalidDay() { String dateStr = "2022-12-33"; assertThrows(ParseException.class, () -> ISO8601Utils.parse(dateStr, new ParsePosition(0))); } @Test public void testDateParseInvalidMonth() { String dateStr = "2022-14-30"; assertThrows(ParseException.class, () -> ISO8601Utils.parse(dateStr, new ParsePosition(0))); } @Test @SuppressWarnings("UndefinedEquals") 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(); assertThat(date).isEqualTo(expectedDate); } @Test @SuppressWarnings("UndefinedEquals") 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(); assertThat(date).isEqualTo(expectedDate); } @Test public void testDateParseInvalidTime() { String dateStr = "2018-06-25T61:60:62-03:00"; assertThrows(ParseException.class, () -> ISO8601Utils.parse(dateStr, new ParsePosition(0))); } } ================================================ FILE: gson/src/test/java/com/google/gson/internal/reflect/Java17ReflectionHelperTest.java ================================================ /* * Copyright (C) 2022 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.reflect; import static com.google.common.truth.Truth.assertThat; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.nio.file.attribute.GroupPrincipal; import java.nio.file.attribute.UserPrincipal; import java.util.Objects; import org.junit.Test; public class Java17ReflectionHelperTest { @Test public void testJava17Record() throws ClassNotFoundException { Class unixDomainPrincipalClass = Class.forName("jdk.net.UnixDomainPrincipal"); // UnixDomainPrincipal is a record assertThat(ReflectionHelper.isRecord(unixDomainPrincipalClass)).isTrue(); // with 2 components assertThat(ReflectionHelper.getRecordComponentNames(unixDomainPrincipalClass)) .isEqualTo(new String[] {"user", "group"}); // Check canonical constructor Constructor constructor = ReflectionHelper.getCanonicalRecordConstructor(unixDomainPrincipalClass); assertThat(constructor).isNotNull(); assertThat(constructor.getParameterTypes()) .isEqualTo(new Class[] {UserPrincipal.class, GroupPrincipal.class}); } @Test public void testJava17RecordAccessors() throws ReflectiveOperationException { // Create an instance of UnixDomainPrincipal, using our custom implementation of UserPrincipal, // and GroupPrincipal. Then attempt to access each component of the record using our accessor // methods. Class unixDomainPrincipalClass = Class.forName("jdk.net.UnixDomainPrincipal"); Object unixDomainPrincipal = ReflectionHelper.getCanonicalRecordConstructor(unixDomainPrincipalClass) .newInstance(new PrincipalImpl("user"), new PrincipalImpl("group")); String[] componentNames = ReflectionHelper.getRecordComponentNames(unixDomainPrincipalClass); assertThat(componentNames).isNotEmpty(); for (String componentName : componentNames) { Field componentField = unixDomainPrincipalClass.getDeclaredField(componentName); Method accessor = ReflectionHelper.getAccessor(unixDomainPrincipalClass, componentField); Object principal = accessor.invoke(unixDomainPrincipal); assertThat(principal).isEqualTo(new PrincipalImpl(componentName)); } } /** Implementation of {@link UserPrincipal} and {@link GroupPrincipal} just for record tests. */ public static class PrincipalImpl implements UserPrincipal, GroupPrincipal { private final String name; public PrincipalImpl(String name) { this.name = name; } @Override public String getName() { return name; } @Override public boolean equals(Object o) { if (o instanceof PrincipalImpl) { return Objects.equals(name, ((PrincipalImpl) o).name); } return false; } @Override public int hashCode() { return Objects.hash(name); } } } ================================================ FILE: gson/src/test/java/com/google/gson/internal/sql/SqlTypesGsonTest.java ================================================ /* * 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.sql; import static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.functional.DefaultTypeAdaptersTest; import java.sql.Time; import java.sql.Timestamp; import java.util.Locale; import java.util.TimeZone; import org.junit.After; import org.junit.Before; import org.junit.Test; // Suppression for `java.sql.Date` to make it explicit that this is not `java.util.Date` @SuppressWarnings("UnnecessarilyFullyQualified") public class SqlTypesGsonTest { private Gson gson; private TimeZone oldTimeZone; private Locale oldLocale; @Before public void setUp() throws Exception { this.oldTimeZone = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles")); this.oldLocale = Locale.getDefault(); Locale.setDefault(Locale.US); gson = new Gson(); } @After public void tearDown() throws Exception { TimeZone.setDefault(oldTimeZone); Locale.setDefault(oldLocale); } @Test public void testNullSerializationAndDeserialization() { testNullSerializationAndDeserialization(java.sql.Date.class); testNullSerializationAndDeserialization(Time.class); testNullSerializationAndDeserialization(Timestamp.class); } private void testNullSerializationAndDeserialization(Class c) { DefaultTypeAdaptersTest.testNullSerializationAndDeserialization(gson, c); } @Test public void testDefaultSqlDateSerialization() { java.sql.Date instant = new java.sql.Date(1259875082000L); String json = gson.toJson(instant); assertThat(json).isEqualTo("\"Dec 3, 2009\""); } @Test 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 @Test 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); assertThat(json).isEqualTo("\"1970-01-01\""); assertThat(gson.fromJson("\"1970-01-01\"", java.sql.Date.class).getTime()).isEqualTo(0); } finally { TimeZone.setDefault(defaultTimeZone); Locale.setDefault(defaultLocale); } } @Test public void testDefaultSqlTimeSerialization() { Time now = new Time(1259875082000L); String json = gson.toJson(now); assertThat(json).isEqualTo("\"01:18:02 PM\""); } @Test public void testDefaultSqlTimeDeserialization() { String json = "'1:18:02 PM'"; Time extracted = gson.fromJson(json, Time.class); DefaultTypeAdaptersTest.assertEqualsTime(extracted, 13, 18, 2); } @Test public void testDefaultSqlTimestampSerialization() { Timestamp now = new java.sql.Timestamp(1259875082000L); String json = gson.toJson(now); // The exact format of the serialized date-time string depends on the JDK version. The pattern // here allows for an optional comma after the date, and what might be U+202F (Narrow No-Break // Space) before "PM". assertThat(json).matches("\"Dec 3, 2009,? 1:18:02\\hPM\""); } @Test 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 @Test 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); assertThat(json).isEqualTo("\"1970-01-01\""); assertThat(gson.fromJson("\"1970-01-01\"", Timestamp.class).getTime()).isEqualTo(0); } finally { TimeZone.setDefault(defaultTimeZone); Locale.setDefault(defaultLocale); } } } ================================================ FILE: gson/src/test/java/com/google/gson/internal/sql/SqlTypesSupportTest.java ================================================ /* * 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.sql; import static com.google.common.truth.Truth.assertThat; import org.junit.Test; public class SqlTypesSupportTest { @Test public void testSupported() { assertThat(SqlTypesSupport.SUPPORTS_SQL_TYPES).isTrue(); assertThat(SqlTypesSupport.DATE_DATE_TYPE).isNotNull(); assertThat(SqlTypesSupport.TIMESTAMP_DATE_TYPE).isNotNull(); assertThat(SqlTypesSupport.DATE_FACTORY).isNotNull(); assertThat(SqlTypesSupport.TIME_FACTORY).isNotNull(); assertThat(SqlTypesSupport.TIMESTAMP_FACTORY).isNotNull(); assertThat(SqlTypesSupport.SQL_TYPE_FACTORIES) .containsExactly( SqlTypesSupport.TIME_FACTORY, SqlTypesSupport.DATE_FACTORY, SqlTypesSupport.TIMESTAMP_FACTORY) .inOrder(); } } ================================================ FILE: gson/src/test/java/com/google/gson/metrics/PerformanceTest.java ================================================ /* * 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 static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import com.google.gson.JsonParseException; import com.google.gson.annotations.Expose; import com.google.gson.reflect.TypeToken; 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; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; /** * Tests to measure performance for Gson. All tests in this file will be disabled in code. To run * them remove the {@code @Ignore} annotation from the tests. * * @author Inderjeet Singh * @author Joel Leitch */ @SuppressWarnings("SystemOut") // allow System.out because test is for manual execution anyway public class PerformanceTest { private static final int COLLECTION_SIZE = 5000; private static final int NUM_ITERATIONS = 100; private Gson gson; @Before public void setUp() throws Exception { gson = new Gson(); } @Test public void testDummy() { // This is here to prevent Junit for complaining when we disable all tests. } @Test @Ignore public void 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); assertThat(target.message).contains("Error"); assertThat(target.stackTrace).contains("Yippie"); } private static class ExceptionHolder { final String message; final String stackTrace; // For use by Gson @SuppressWarnings("unused") private ExceptionHolder() { this("", ""); } 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 */ @Test @Ignore public void testLargeCollectionSerialization() { int count = 1400000; List list = new ArrayList<>(count); for (int i = 0; i < count; ++i) { list.add(new CollectionEntry("name" + i, "value" + i)); } String unused = gson.toJson(list); } /** Created in response to http://code.google.com/p/google-gson/issues/detail?id=96 */ @Test @Ignore public void 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>() {}.getType(); List list = gson.fromJson(json, collectionType); assertThat(list).hasSize(count); } /** 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 @Test @Ignore public void testByteArraySerialization() { for (int size = 4145152; true; size += 1036288) { byte[] ba = new byte[size]; for (int i = 0; i < size; ++i) { ba[i] = 0x05; } String unused = 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 @Test @Ignore public void 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 @Test @Ignore public void 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); } @Test @Ignore public void 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); } @Test @Ignore public void testLargeObjectSerializationAndDeserialization() { Map 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(); Map unused = gson.fromJson(json, new TypeToken>() {}.getType()); t2 = System.currentTimeMillis(); System.out.printf("Large object deserialized in: %d ms\n", (t2 - t1)); } @Test @Ignore public void 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); } @Test @Ignore public void 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); } @Test @Ignore public void testLargeGsonMapRoundTrip() throws Exception { Map 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>() {}.getType(); Map unused = gson.fromJson(json, longToLong); } private static 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 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(""); } ClassWithField(String field) { this.field = field; } } @SuppressWarnings("unused") private static final class ClassWithListOfObjects { @Expose final String field; @Expose final List 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; } } } ================================================ FILE: gson/src/test/java/com/google/gson/reflect/TypeTokenTest.java ================================================ /* * 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 static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import java.lang.reflect.GenericArrayType; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.RandomAccess; import java.util.Set; import org.junit.Test; /** * Tests for {@link TypeToken}. * * @author Jesse Wilson */ // Suppress because these classes are only needed for this test, but must be top-level classes // to not have an enclosing type @SuppressWarnings("MultipleTopLevelClasses") public final class TypeTokenTest { // These fields are accessed using reflection by the tests below List listOfInteger = null; List listOfNumber = null; List listOfString = null; List listOfUnknown = null; List> listOfSetOfString = null; List> listOfSetOfUnknown = null; @SuppressWarnings({"deprecation"}) @Test public void testIsAssignableFromRawTypes() { assertThat(TypeToken.get(Object.class).isAssignableFrom(String.class)).isTrue(); assertThat(TypeToken.get(String.class).isAssignableFrom(Object.class)).isFalse(); assertThat(TypeToken.get(RandomAccess.class).isAssignableFrom(ArrayList.class)).isTrue(); assertThat(TypeToken.get(ArrayList.class).isAssignableFrom(RandomAccess.class)).isFalse(); } @SuppressWarnings({"deprecation"}) @Test public void testIsAssignableFromWithTypeParameters() throws Exception { Type a = getClass().getDeclaredField("listOfInteger").getGenericType(); Type b = getClass().getDeclaredField("listOfNumber").getGenericType(); assertThat(TypeToken.get(a).isAssignableFrom(a)).isTrue(); assertThat(TypeToken.get(b).isAssignableFrom(b)).isTrue(); // listOfInteger = listOfNumber; // doesn't compile; must be false assertThat(TypeToken.get(a).isAssignableFrom(b)).isFalse(); // listOfNumber = listOfInteger; // doesn't compile; must be false assertThat(TypeToken.get(b).isAssignableFrom(a)).isFalse(); } @SuppressWarnings({"deprecation"}) @Test public void testIsAssignableFromWithBasicWildcards() throws Exception { Type a = getClass().getDeclaredField("listOfString").getGenericType(); Type b = getClass().getDeclaredField("listOfUnknown").getGenericType(); assertThat(TypeToken.get(a).isAssignableFrom(a)).isTrue(); assertThat(TypeToken.get(b).isAssignableFrom(b)).isTrue(); // listOfString = listOfUnknown // doesn't compile; must be false assertThat(TypeToken.get(a).isAssignableFrom(b)).isFalse(); listOfUnknown = listOfString; // compiles; must be true // The following assertion is too difficult to support reliably, so disabling // assertThat(TypeToken.get(b).isAssignableFrom(a)).isTrue(); WildcardType wildcardType = (WildcardType) ((ParameterizedType) b).getActualTypeArguments()[0]; TypeToken wildcardTypeToken = TypeToken.get(wildcardType); IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> wildcardTypeToken.isAssignableFrom(b)); assertThat(e) .hasMessageThat() .isEqualTo( "Unsupported type, expected one of: java.lang.Class," + " java.lang.reflect.ParameterizedType, java.lang.reflect.GenericArrayType, but" + " got: com.google.gson.internal.GsonTypes$WildcardTypeImpl, for type token: " + wildcardTypeToken); } @SuppressWarnings({"deprecation"}) @Test public void testIsAssignableFromWithNestedWildcards() throws Exception { Type a = getClass().getDeclaredField("listOfSetOfString").getGenericType(); Type b = getClass().getDeclaredField("listOfSetOfUnknown").getGenericType(); assertThat(TypeToken.get(a).isAssignableFrom(a)).isTrue(); assertThat(TypeToken.get(b).isAssignableFrom(b)).isTrue(); // listOfSetOfString = listOfSetOfUnknown; // doesn't compile; must be false assertThat(TypeToken.get(a).isAssignableFrom(b)).isFalse(); // listOfSetOfUnknown = listOfSetOfString; // doesn't compile; must be false assertThat(TypeToken.get(b).isAssignableFrom(a)).isFalse(); } @Test public void testArrayFactory() { TypeToken expectedStringArray = new TypeToken() {}; assertThat(TypeToken.getArray(String.class)).isEqualTo(expectedStringArray); TypeToken expectedListOfStringArray = new TypeToken[]>() {}; Type listOfString = new TypeToken>() {}.getType(); assertThat(TypeToken.getArray(listOfString)).isEqualTo(expectedListOfStringArray); TypeToken expectedIntArray = new TypeToken() {}; assertThat(TypeToken.getArray(int.class)).isEqualTo(expectedIntArray); assertThrows(NullPointerException.class, () -> TypeToken.getArray(null)); } static class NestedGeneric {} @Test public void testParameterizedFactory() { TypeToken expectedListOfString = new TypeToken>() {}; assertThat(TypeToken.getParameterized(List.class, String.class)) .isEqualTo(expectedListOfString); TypeToken expectedMapOfStringToString = new TypeToken>() {}; assertThat(TypeToken.getParameterized(Map.class, String.class, String.class)) .isEqualTo(expectedMapOfStringToString); TypeToken expectedListOfListOfListOfString = new TypeToken>>>() {}; Type listOfString = TypeToken.getParameterized(List.class, String.class).getType(); Type listOfListOfString = TypeToken.getParameterized(List.class, listOfString).getType(); assertThat(TypeToken.getParameterized(List.class, listOfListOfString)) .isEqualTo(expectedListOfListOfListOfString); TypeToken expectedWithExactArg = new TypeToken>() {}; assertThat(TypeToken.getParameterized(GenericWithBound.class, Number.class)) .isEqualTo(expectedWithExactArg); TypeToken expectedWithSubclassArg = new TypeToken>() {}; assertThat(TypeToken.getParameterized(GenericWithBound.class, Integer.class)) .isEqualTo(expectedWithSubclassArg); TypeToken expectedSatisfyingTwoBounds = new TypeToken>() {}; assertThat(TypeToken.getParameterized(GenericWithMultiBound.class, ClassSatisfyingBounds.class)) .isEqualTo(expectedSatisfyingTwoBounds); TypeToken nestedTypeToken = TypeToken.getParameterized(NestedGeneric.class, Integer.class); ParameterizedType nestedParameterizedType = (ParameterizedType) nestedTypeToken.getType(); // TODO: This seems to differ from how Java reflection behaves; when using // TypeToken>, then NestedGeneric does have an owner type assertThat(nestedParameterizedType.getOwnerType()).isNull(); assertThat(nestedParameterizedType.getRawType()).isEqualTo(NestedGeneric.class); assertThat(nestedParameterizedType.getActualTypeArguments()) .asList() .containsExactly(Integer.class); class LocalGenericClass {} TypeToken expectedLocalType = new TypeToken>() {}; assertThat(TypeToken.getParameterized(LocalGenericClass.class, Integer.class)) .isEqualTo(expectedLocalType); // For legacy reasons, if requesting parameterized type for non-generic class, create a // `TypeToken(Class)` assertThat(TypeToken.getParameterized(String.class)).isEqualTo(TypeToken.get(String.class)); } @Test public void testParameterizedFactory_Invalid() { assertThrows(NullPointerException.class, () -> TypeToken.getParameterized(null, new Type[0])); assertThrows( NullPointerException.class, () -> TypeToken.getParameterized(List.class, new Type[] {null})); GenericArrayType arrayType = (GenericArrayType) TypeToken.getArray(String.class).getType(); IllegalArgumentException e = assertThrows( IllegalArgumentException.class, () -> TypeToken.getParameterized(arrayType, new Type[0])); assertThat(e) .hasMessageThat() .isEqualTo("rawType must be of type Class, but was java.lang.String[]"); e = assertThrows( IllegalArgumentException.class, () -> TypeToken.getParameterized(String.class, Number.class)); assertThat(e) .hasMessageThat() .isEqualTo("java.lang.String requires 0 type arguments, but got 1"); e = assertThrows( IllegalArgumentException.class, () -> TypeToken.getParameterized(List.class, new Type[0])); assertThat(e).hasMessageThat().isEqualTo("java.util.List requires 1 type arguments, but got 0"); e = assertThrows( IllegalArgumentException.class, () -> TypeToken.getParameterized(List.class, String.class, String.class)); assertThat(e).hasMessageThat().isEqualTo("java.util.List requires 1 type arguments, but got 2"); // Primitive types must not be used as type argument e = assertThrows( IllegalArgumentException.class, () -> TypeToken.getParameterized(List.class, int.class)); assertThat(e) .hasMessageThat() .isEqualTo( "Type argument int does not satisfy bounds for type variable E declared by " + List.class); e = assertThrows( IllegalArgumentException.class, () -> TypeToken.getParameterized(GenericWithBound.class, String.class)); assertThat(e) .hasMessageThat() .isEqualTo( "Type argument class java.lang.String does not satisfy bounds" + " for type variable T declared by " + GenericWithBound.class); e = assertThrows( IllegalArgumentException.class, () -> TypeToken.getParameterized(GenericWithBound.class, Object.class)); assertThat(e) .hasMessageThat() .isEqualTo( "Type argument class java.lang.Object does not satisfy bounds" + " for type variable T declared by " + GenericWithBound.class); e = assertThrows( IllegalArgumentException.class, () -> TypeToken.getParameterized(GenericWithMultiBound.class, Number.class)); assertThat(e) .hasMessageThat() .isEqualTo( "Type argument class java.lang.Number does not satisfy bounds" + " for type variable T declared by " + GenericWithMultiBound.class); e = assertThrows( IllegalArgumentException.class, () -> TypeToken.getParameterized(GenericWithMultiBound.class, CharSequence.class)); assertThat(e) .hasMessageThat() .isEqualTo( "Type argument interface java.lang.CharSequence does not satisfy bounds" + " for type variable T declared by " + GenericWithMultiBound.class); e = assertThrows( IllegalArgumentException.class, () -> TypeToken.getParameterized(GenericWithMultiBound.class, Object.class)); assertThat(e) .hasMessageThat() .isEqualTo( "Type argument class java.lang.Object does not satisfy bounds" + " for type variable T declared by " + GenericWithMultiBound.class); class Outer { @SuppressWarnings("ClassCanBeStatic") class NonStaticInner {} } e = assertThrows( IllegalArgumentException.class, () -> TypeToken.getParameterized(Outer.NonStaticInner.class, Object.class)); assertThat(e) .hasMessageThat() .isEqualTo( "Raw type " + Outer.NonStaticInner.class.getName() + " is not supported because it requires specifying an owner type"); } private static class CustomTypeToken extends TypeToken {} @Test public void testTypeTokenNonAnonymousSubclass() { TypeToken typeToken = new CustomTypeToken(); assertThat(typeToken.getRawType()).isEqualTo(String.class); assertThat(typeToken.getType()).isEqualTo(String.class); } /** * User must only create direct subclasses of TypeToken, but not subclasses of subclasses (...) of * TypeToken. */ @Test public void testTypeTokenSubSubClass() { class SubTypeToken extends TypeToken {} class SubSubTypeToken1 extends SubTypeToken {} class SubSubTypeToken2 extends SubTypeToken {} IllegalStateException e = assertThrows(IllegalStateException.class, () -> new SubTypeToken() {}); assertThat(e).hasMessageThat().isEqualTo("Must only create direct subclasses of TypeToken"); e = assertThrows(IllegalStateException.class, () -> new SubSubTypeToken1()); assertThat(e).hasMessageThat().isEqualTo("Must only create direct subclasses of TypeToken"); e = assertThrows(IllegalStateException.class, () -> new SubSubTypeToken2()); assertThat(e).hasMessageThat().isEqualTo("Must only create direct subclasses of TypeToken"); } private static void createTypeTokenTypeVariable() { var unused = new TypeToken() {}; } /** * TypeToken type argument must not contain a type variable because, due to type erasure, at * runtime only the bound of the type variable is available which is likely not what the user * wanted. * *

Note that type variables are allowed for the {@code TypeToken} factory methods calling * {@code TypeToken(Type)} because for them the return type is {@code TypeToken} which does not * give a false sense of type-safety. */ @Test public void testTypeTokenTypeVariable() throws Exception { // Put the test code inside generic class to be able to access `T` class Enclosing { @SuppressWarnings("ClassCanBeStatic") class Inner {} void test() { String expectedMessage = "TypeToken type argument must not contain a type variable;" + " captured type variable T declared by " + Enclosing.class + "\n" + "See https://github.com/google/gson/blob/main/Troubleshooting.md#typetoken-type-variable"; IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> new TypeToken() {}); assertThat(e).hasMessageThat().isEqualTo(expectedMessage); e = assertThrows(IllegalArgumentException.class, () -> new TypeToken>>() {}); assertThat(e).hasMessageThat().isEqualTo(expectedMessage); e = assertThrows( IllegalArgumentException.class, () -> new TypeToken>>() {}); assertThat(e).hasMessageThat().isEqualTo(expectedMessage); e = assertThrows( IllegalArgumentException.class, () -> new TypeToken>>() {}); assertThat(e).hasMessageThat().isEqualTo(expectedMessage); e = assertThrows(IllegalArgumentException.class, () -> new TypeToken[]>() {}); assertThat(e).hasMessageThat().isEqualTo(expectedMessage); e = assertThrows( IllegalArgumentException.class, () -> new TypeToken.Inner>() {}); assertThat(e).hasMessageThat().isEqualTo(expectedMessage); String systemProperty = "gson.allowCapturingTypeVariables"; try { // Any value other than 'true' should be ignored System.setProperty(systemProperty, "some-value"); e = assertThrows(IllegalArgumentException.class, () -> new TypeToken() {}); assertThat(e).hasMessageThat().isEqualTo(expectedMessage); } finally { System.clearProperty(systemProperty); } try { System.setProperty(systemProperty, "true"); TypeToken typeToken = new TypeToken() {}; assertThat(typeToken.getType()).isEqualTo(Enclosing.class.getTypeParameters()[0]); } finally { System.clearProperty(systemProperty); } } void testMethodTypeVariable() throws Exception { Method testMethod = Enclosing.class.getDeclaredMethod("testMethodTypeVariable"); IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> new TypeToken() {}); assertThat(e) .hasMessageThat() .isAnyOf( "TypeToken type argument must not contain a type variable;" + " captured type variable M declared by " + testMethod + "\n" + "See https://github.com/google/gson/blob/main/Troubleshooting.md#typetoken-type-variable", // Note: When running this test in Eclipse IDE or with certain Java versions it // seems to capture `null` instead of the type variable, see // https://github.com/eclipse-jdt/eclipse.jdt.core/issues/975 "TypeToken captured `null` as type argument; probably a compiler / runtime bug"); } } new Enclosing<>().test(); new Enclosing<>().testMethodTypeVariable(); Method testMethod = TypeTokenTest.class.getDeclaredMethod("createTypeTokenTypeVariable"); IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> createTypeTokenTypeVariable()); assertThat(e) .hasMessageThat() .isEqualTo( "TypeToken type argument must not contain a type variable;" + " captured type variable M declared by " + testMethod + "\n" + "See https://github.com/google/gson/blob/main/Troubleshooting.md#typetoken-type-variable"); // Using type variable as argument for factory methods should be allowed; this is not a // type-safety problem because the user would have to perform unsafe casts TypeVariable typeVar = Enclosing.class.getTypeParameters()[0]; TypeToken typeToken = TypeToken.get(typeVar); assertThat(typeToken.getType()).isEqualTo(typeVar); TypeToken parameterizedTypeToken = TypeToken.getParameterized(List.class, typeVar); ParameterizedType parameterizedType = (ParameterizedType) parameterizedTypeToken.getType(); assertThat(parameterizedType.getRawType()).isEqualTo(List.class); assertThat(parameterizedType.getActualTypeArguments()).asList().containsExactly(typeVar); } @SuppressWarnings("rawtypes") @Test public void testTypeTokenRaw() { IllegalStateException e = assertThrows(IllegalStateException.class, () -> new TypeToken() {}); assertThat(e) .hasMessageThat() .isEqualTo( "TypeToken must be created with a type argument: new TypeToken<...>() {}; When using" + " code shrinkers (ProGuard, R8, ...) make sure that generic signatures are" + " preserved.\n" + "See https://github.com/google/gson/blob/main/Troubleshooting.md#type-token-raw"); } } // Have to declare these classes here as top-level classes because otherwise tests for // TypeToken.getParameterized fail due to owner type mismatch class GenericWithBound {} class GenericWithMultiBound {} @SuppressWarnings("serial") abstract class ClassSatisfyingBounds extends Number implements CharSequence {} ================================================ FILE: gson/src/test/java/com/google/gson/stream/JsonReaderPathTest.java ================================================ /* * 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 static com.google.common.truth.Truth.assertThat; import static org.junit.Assume.assumeTrue; import com.google.gson.JsonElement; import com.google.gson.Strictness; 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; @SuppressWarnings("resource") @RunWith(Parameterized.class) public class JsonReaderPathTest { @Parameterized.Parameters(name = "{0}") public static List 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]]}"); assertThat(reader.getPreviousPath()).isEqualTo("$"); assertThat(reader.getPath()).isEqualTo("$"); reader.beginObject(); assertThat(reader.getPreviousPath()).isEqualTo("$."); assertThat(reader.getPath()).isEqualTo("$."); String unused1 = reader.nextName(); assertThat(reader.getPreviousPath()).isEqualTo("$.a"); assertThat(reader.getPath()).isEqualTo("$.a"); reader.beginArray(); assertThat(reader.getPreviousPath()).isEqualTo("$.a[0]"); assertThat(reader.getPath()).isEqualTo("$.a[0]"); int unused2 = reader.nextInt(); assertThat(reader.getPreviousPath()).isEqualTo("$.a[0]"); assertThat(reader.getPath()).isEqualTo("$.a[1]"); boolean unused3 = reader.nextBoolean(); assertThat(reader.getPreviousPath()).isEqualTo("$.a[1]"); assertThat(reader.getPath()).isEqualTo("$.a[2]"); boolean unused4 = reader.nextBoolean(); assertThat(reader.getPreviousPath()).isEqualTo("$.a[2]"); assertThat(reader.getPath()).isEqualTo("$.a[3]"); reader.nextNull(); assertThat(reader.getPreviousPath()).isEqualTo("$.a[3]"); assertThat(reader.getPath()).isEqualTo("$.a[4]"); String unused5 = reader.nextString(); assertThat(reader.getPreviousPath()).isEqualTo("$.a[4]"); assertThat(reader.getPath()).isEqualTo("$.a[5]"); reader.beginObject(); assertThat(reader.getPreviousPath()).isEqualTo("$.a[5]."); assertThat(reader.getPath()).isEqualTo("$.a[5]."); String unused6 = reader.nextName(); assertThat(reader.getPreviousPath()).isEqualTo("$.a[5].c"); assertThat(reader.getPath()).isEqualTo("$.a[5].c"); String unused7 = reader.nextString(); assertThat(reader.getPreviousPath()).isEqualTo("$.a[5].c"); assertThat(reader.getPath()).isEqualTo("$.a[5].c"); reader.endObject(); assertThat(reader.getPreviousPath()).isEqualTo("$.a[5]"); assertThat(reader.getPath()).isEqualTo("$.a[6]"); reader.beginArray(); assertThat(reader.getPreviousPath()).isEqualTo("$.a[6][0]"); assertThat(reader.getPath()).isEqualTo("$.a[6][0]"); int unused8 = reader.nextInt(); assertThat(reader.getPreviousPath()).isEqualTo("$.a[6][0]"); assertThat(reader.getPath()).isEqualTo("$.a[6][1]"); reader.endArray(); assertThat(reader.getPreviousPath()).isEqualTo("$.a[6]"); assertThat(reader.getPath()).isEqualTo("$.a[7]"); reader.endArray(); assertThat(reader.getPreviousPath()).isEqualTo("$.a"); assertThat(reader.getPath()).isEqualTo("$.a"); reader.endObject(); assertThat(reader.getPreviousPath()).isEqualTo("$"); assertThat(reader.getPath()).isEqualTo("$"); } @Test public void objectPath() throws IOException { JsonReader reader = factory.create("{\"a\":1,\"b\":2}"); assertThat(reader.getPreviousPath()).isEqualTo("$"); assertThat(reader.getPath()).isEqualTo("$"); JsonToken unused1 = reader.peek(); assertThat(reader.getPreviousPath()).isEqualTo("$"); assertThat(reader.getPath()).isEqualTo("$"); reader.beginObject(); assertThat(reader.getPreviousPath()).isEqualTo("$."); assertThat(reader.getPath()).isEqualTo("$."); JsonToken unused2 = reader.peek(); assertThat(reader.getPreviousPath()).isEqualTo("$."); assertThat(reader.getPath()).isEqualTo("$."); String unused3 = reader.nextName(); assertThat(reader.getPreviousPath()).isEqualTo("$.a"); assertThat(reader.getPath()).isEqualTo("$.a"); JsonToken unused4 = reader.peek(); assertThat(reader.getPreviousPath()).isEqualTo("$.a"); assertThat(reader.getPath()).isEqualTo("$.a"); int unused5 = reader.nextInt(); assertThat(reader.getPreviousPath()).isEqualTo("$.a"); assertThat(reader.getPath()).isEqualTo("$.a"); JsonToken unused6 = reader.peek(); assertThat(reader.getPreviousPath()).isEqualTo("$.a"); assertThat(reader.getPath()).isEqualTo("$.a"); String unused7 = reader.nextName(); assertThat(reader.getPreviousPath()).isEqualTo("$.b"); assertThat(reader.getPath()).isEqualTo("$.b"); JsonToken unused8 = reader.peek(); assertThat(reader.getPreviousPath()).isEqualTo("$.b"); assertThat(reader.getPath()).isEqualTo("$.b"); int unused9 = reader.nextInt(); assertThat(reader.getPreviousPath()).isEqualTo("$.b"); assertThat(reader.getPath()).isEqualTo("$.b"); JsonToken unused10 = reader.peek(); assertThat(reader.getPreviousPath()).isEqualTo("$.b"); assertThat(reader.getPath()).isEqualTo("$.b"); reader.endObject(); assertThat(reader.getPreviousPath()).isEqualTo("$"); assertThat(reader.getPath()).isEqualTo("$"); JsonToken unused11 = reader.peek(); assertThat(reader.getPreviousPath()).isEqualTo("$"); assertThat(reader.getPath()).isEqualTo("$"); reader.close(); assertThat(reader.getPreviousPath()).isEqualTo("$"); assertThat(reader.getPath()).isEqualTo("$"); } @Test public void arrayPath() throws IOException { JsonReader reader = factory.create("[1,2]"); assertThat(reader.getPreviousPath()).isEqualTo("$"); assertThat(reader.getPath()).isEqualTo("$"); JsonToken unused1 = reader.peek(); assertThat(reader.getPreviousPath()).isEqualTo("$"); assertThat(reader.getPath()).isEqualTo("$"); reader.beginArray(); assertThat(reader.getPreviousPath()).isEqualTo("$[0]"); assertThat(reader.getPath()).isEqualTo("$[0]"); JsonToken unused2 = reader.peek(); assertThat(reader.getPreviousPath()).isEqualTo("$[0]"); assertThat(reader.getPath()).isEqualTo("$[0]"); int unused3 = reader.nextInt(); assertThat(reader.getPreviousPath()).isEqualTo("$[0]"); assertThat(reader.getPath()).isEqualTo("$[1]"); JsonToken unused4 = reader.peek(); assertThat(reader.getPreviousPath()).isEqualTo("$[0]"); assertThat(reader.getPath()).isEqualTo("$[1]"); int unused5 = reader.nextInt(); assertThat(reader.getPreviousPath()).isEqualTo("$[1]"); assertThat(reader.getPath()).isEqualTo("$[2]"); JsonToken unused6 = reader.peek(); assertThat(reader.getPreviousPath()).isEqualTo("$[1]"); assertThat(reader.getPath()).isEqualTo("$[2]"); reader.endArray(); assertThat(reader.getPreviousPath()).isEqualTo("$"); assertThat(reader.getPath()).isEqualTo("$"); JsonToken unused7 = reader.peek(); assertThat(reader.getPreviousPath()).isEqualTo("$"); assertThat(reader.getPath()).isEqualTo("$"); reader.close(); assertThat(reader.getPreviousPath()).isEqualTo("$"); assertThat(reader.getPath()).isEqualTo("$"); } @Test public void multipleTopLevelValuesInOneDocument() throws IOException { assumeTrue(factory == Factory.STRING_READER); JsonReader reader = factory.create("[][]"); reader.setStrictness(Strictness.LENIENT); reader.beginArray(); reader.endArray(); assertThat(reader.getPreviousPath()).isEqualTo("$"); assertThat(reader.getPath()).isEqualTo("$"); reader.beginArray(); reader.endArray(); assertThat(reader.getPreviousPath()).isEqualTo("$"); assertThat(reader.getPath()).isEqualTo("$"); } @Test public void skipArrayElements() throws IOException { JsonReader reader = factory.create("[1,2,3]"); reader.beginArray(); reader.skipValue(); reader.skipValue(); assertThat(reader.getPreviousPath()).isEqualTo("$[1]"); assertThat(reader.getPath()).isEqualTo("$[2]"); } @Test public void skipArrayEnd() throws IOException { JsonReader reader = factory.create("[[],1]"); reader.beginArray(); reader.beginArray(); assertThat(reader.getPreviousPath()).isEqualTo("$[0][0]"); assertThat(reader.getPath()).isEqualTo("$[0][0]"); reader.skipValue(); // skip end of array assertThat(reader.getPreviousPath()).isEqualTo("$[0]"); assertThat(reader.getPath()).isEqualTo("$[1]"); } @Test public void skipObjectNames() throws IOException { JsonReader reader = factory.create("{\"a\":[]}"); reader.beginObject(); reader.skipValue(); assertThat(reader.getPreviousPath()).isEqualTo("$."); assertThat(reader.getPath()).isEqualTo("$."); reader.beginArray(); assertThat(reader.getPreviousPath()).isEqualTo("$.[0]"); assertThat(reader.getPath()).isEqualTo("$.[0]"); } @Test public void skipObjectValues() throws IOException { JsonReader reader = factory.create("{\"a\":1,\"b\":2}"); reader.beginObject(); assertThat(reader.getPreviousPath()).isEqualTo("$."); assertThat(reader.getPath()).isEqualTo("$."); String unused1 = reader.nextName(); reader.skipValue(); assertThat(reader.getPreviousPath()).isEqualTo("$.a"); assertThat(reader.getPath()).isEqualTo("$.a"); String unused2 = reader.nextName(); assertThat(reader.getPreviousPath()).isEqualTo("$.b"); assertThat(reader.getPath()).isEqualTo("$.b"); } @Test public void skipObjectEnd() throws IOException { JsonReader reader = factory.create("{\"a\":{},\"b\":2}"); reader.beginObject(); String unused = reader.nextName(); reader.beginObject(); assertThat(reader.getPreviousPath()).isEqualTo("$.a."); assertThat(reader.getPath()).isEqualTo("$.a."); reader.skipValue(); // skip end of object assertThat(reader.getPreviousPath()).isEqualTo("$.a"); assertThat(reader.getPath()).isEqualTo("$.a"); } @Test public void skipNestedStructures() throws IOException { JsonReader reader = factory.create("[[1,2,3],4]"); reader.beginArray(); reader.skipValue(); assertThat(reader.getPreviousPath()).isEqualTo("$[0]"); assertThat(reader.getPath()).isEqualTo("$[1]"); } @Test public void skipEndOfDocument() throws IOException { JsonReader reader = factory.create("[]"); reader.beginArray(); reader.endArray(); assertThat(reader.getPreviousPath()).isEqualTo("$"); assertThat(reader.getPath()).isEqualTo("$"); reader.skipValue(); assertThat(reader.getPreviousPath()).isEqualTo("$"); assertThat(reader.getPath()).isEqualTo("$"); reader.skipValue(); assertThat(reader.getPreviousPath()).isEqualTo("$"); assertThat(reader.getPath()).isEqualTo("$"); } @Test public void arrayOfObjects() throws IOException { JsonReader reader = factory.create("[{},{},{}]"); reader.beginArray(); assertThat(reader.getPreviousPath()).isEqualTo("$[0]"); assertThat(reader.getPath()).isEqualTo("$[0]"); reader.beginObject(); assertThat(reader.getPreviousPath()).isEqualTo("$[0]."); assertThat(reader.getPath()).isEqualTo("$[0]."); reader.endObject(); assertThat(reader.getPreviousPath()).isEqualTo("$[0]"); assertThat(reader.getPath()).isEqualTo("$[1]"); reader.beginObject(); assertThat(reader.getPreviousPath()).isEqualTo("$[1]."); assertThat(reader.getPath()).isEqualTo("$[1]."); reader.endObject(); assertThat(reader.getPreviousPath()).isEqualTo("$[1]"); assertThat(reader.getPath()).isEqualTo("$[2]"); reader.beginObject(); assertThat(reader.getPreviousPath()).isEqualTo("$[2]."); assertThat(reader.getPath()).isEqualTo("$[2]."); reader.endObject(); assertThat(reader.getPreviousPath()).isEqualTo("$[2]"); assertThat(reader.getPath()).isEqualTo("$[3]"); reader.endArray(); assertThat(reader.getPreviousPath()).isEqualTo("$"); assertThat(reader.getPath()).isEqualTo("$"); } @Test public void arrayOfArrays() throws IOException { JsonReader reader = factory.create("[[],[],[]]"); reader.beginArray(); assertThat(reader.getPreviousPath()).isEqualTo("$[0]"); assertThat(reader.getPath()).isEqualTo("$[0]"); reader.beginArray(); assertThat(reader.getPreviousPath()).isEqualTo("$[0][0]"); assertThat(reader.getPath()).isEqualTo("$[0][0]"); reader.endArray(); assertThat(reader.getPreviousPath()).isEqualTo("$[0]"); assertThat(reader.getPath()).isEqualTo("$[1]"); reader.beginArray(); assertThat(reader.getPreviousPath()).isEqualTo("$[1][0]"); assertThat(reader.getPath()).isEqualTo("$[1][0]"); reader.endArray(); assertThat(reader.getPreviousPath()).isEqualTo("$[1]"); assertThat(reader.getPath()).isEqualTo("$[2]"); reader.beginArray(); assertThat(reader.getPreviousPath()).isEqualTo("$[2][0]"); assertThat(reader.getPath()).isEqualTo("$[2][0]"); reader.endArray(); assertThat(reader.getPreviousPath()).isEqualTo("$[2]"); assertThat(reader.getPath()).isEqualTo("$[3]"); reader.endArray(); assertThat(reader.getPreviousPath()).isEqualTo("$"); assertThat(reader.getPath()).isEqualTo("$"); } @Test public void objectOfObjects() throws IOException { JsonReader reader = factory.create("{\"a\":{\"a1\":1,\"a2\":2},\"b\":{\"b1\":1}}"); reader.beginObject(); assertThat(reader.getPreviousPath()).isEqualTo("$."); assertThat(reader.getPath()).isEqualTo("$."); String unused1 = reader.nextName(); assertThat(reader.getPreviousPath()).isEqualTo("$.a"); assertThat(reader.getPath()).isEqualTo("$.a"); reader.beginObject(); assertThat(reader.getPreviousPath()).isEqualTo("$.a."); assertThat(reader.getPath()).isEqualTo("$.a."); String unused2 = reader.nextName(); assertThat(reader.getPreviousPath()).isEqualTo("$.a.a1"); assertThat(reader.getPath()).isEqualTo("$.a.a1"); int unused3 = reader.nextInt(); assertThat(reader.getPreviousPath()).isEqualTo("$.a.a1"); assertThat(reader.getPath()).isEqualTo("$.a.a1"); String unused4 = reader.nextName(); assertThat(reader.getPreviousPath()).isEqualTo("$.a.a2"); assertThat(reader.getPath()).isEqualTo("$.a.a2"); int unused5 = reader.nextInt(); assertThat(reader.getPreviousPath()).isEqualTo("$.a.a2"); assertThat(reader.getPath()).isEqualTo("$.a.a2"); reader.endObject(); assertThat(reader.getPreviousPath()).isEqualTo("$.a"); assertThat(reader.getPath()).isEqualTo("$.a"); String unused6 = reader.nextName(); assertThat(reader.getPreviousPath()).isEqualTo("$.b"); assertThat(reader.getPath()).isEqualTo("$.b"); reader.beginObject(); assertThat(reader.getPreviousPath()).isEqualTo("$.b."); assertThat(reader.getPath()).isEqualTo("$.b."); String unused7 = reader.nextName(); assertThat(reader.getPreviousPath()).isEqualTo("$.b.b1"); assertThat(reader.getPath()).isEqualTo("$.b.b1"); int unused8 = reader.nextInt(); assertThat(reader.getPreviousPath()).isEqualTo("$.b.b1"); assertThat(reader.getPath()).isEqualTo("$.b.b1"); reader.endObject(); assertThat(reader.getPreviousPath()).isEqualTo("$.b"); assertThat(reader.getPath()).isEqualTo("$.b"); reader.endObject(); assertThat(reader.getPreviousPath()).isEqualTo("$"); assertThat(reader.getPath()).isEqualTo("$"); } 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); } } ================================================ FILE: gson/src/test/java/com/google/gson/stream/JsonReaderTest.java ================================================ /* * 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 static com.google.common.truth.Truth.assertThat; 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; import static org.junit.Assert.assertThrows; import com.google.gson.Strictness; import java.io.EOFException; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.Arrays; import org.junit.Ignore; import org.junit.Test; @SuppressWarnings("resource") public final class JsonReaderTest { @Test public void testDefaultStrictness() { JsonReader reader = new JsonReader(reader("{}")); assertThat(reader.getStrictness()).isEqualTo(Strictness.LEGACY_STRICT); } @SuppressWarnings("deprecation") // for JsonReader.setLenient @Test public void testSetLenientTrue() { JsonReader reader = new JsonReader(reader("{}")); reader.setLenient(true); assertThat(reader.getStrictness()).isEqualTo(Strictness.LENIENT); } @SuppressWarnings("deprecation") // for JsonReader.setLenient @Test public void testSetLenientFalse() { JsonReader reader = new JsonReader(reader("{}")); reader.setLenient(false); assertThat(reader.getStrictness()).isEqualTo(Strictness.LEGACY_STRICT); } @Test public void testSetStrictness() { JsonReader reader = new JsonReader(reader("{}")); reader.setStrictness(Strictness.STRICT); assertThat(reader.getStrictness()).isEqualTo(Strictness.STRICT); } @Test public void testSetStrictnessNull() { JsonReader reader = new JsonReader(reader("{}")); assertThrows(NullPointerException.class, () -> reader.setStrictness(null)); } @Test public void testEscapedNewlineNotAllowedInStrictMode() { String json = "\"\\\n\""; JsonReader reader = new JsonReader(reader(json)); reader.setStrictness(Strictness.STRICT); IOException expected = assertThrows(IOException.class, reader::nextString); assertThat(expected) .hasMessageThat() .startsWith("Cannot escape a newline character in strict mode"); } @Test public void testEscapedNewlineAllowedInDefaultMode() throws IOException { String json = "\"\\\n\""; JsonReader reader = new JsonReader(reader(json)); assertThat(reader.nextString()).isEqualTo("\n"); } @Test public void testStrictModeFailsToParseUnescapedControlCharacter() { String json = "\"\0\""; JsonReader reader = new JsonReader(reader(json)); reader.setStrictness(Strictness.STRICT); IOException expected = assertThrows(IOException.class, reader::nextString); assertThat(expected) .hasMessageThat() .startsWith( "Unescaped control characters (\\u0000-\\u001F) are not allowed in strict mode"); json = "\"\t\""; reader = new JsonReader(reader(json)); reader.setStrictness(Strictness.STRICT); expected = assertThrows(IOException.class, reader::nextString); assertThat(expected) .hasMessageThat() .startsWith( "Unescaped control characters (\\u0000-\\u001F) are not allowed in strict mode"); json = "\"\u001F\""; reader = new JsonReader(reader(json)); reader.setStrictness(Strictness.STRICT); expected = assertThrows(IOException.class, reader::nextString); assertThat(expected) .hasMessageThat() .startsWith( "Unescaped control characters (\\u0000-\\u001F) are not allowed in strict mode"); } @Test public void testStrictModeAllowsOtherControlCharacters() throws IOException { // JSON specification only forbids control characters U+0000 - U+001F, other control characters // should be allowed String json = "\"\u007F\u009F\""; JsonReader reader = new JsonReader(reader(json)); reader.setStrictness(Strictness.STRICT); assertThat(reader.nextString()).isEqualTo("\u007F\u009F"); } @Test public void testNonStrictModeParsesUnescapedControlCharacter() throws IOException { String json = "\"\t\""; JsonReader reader = new JsonReader(reader(json)); assertThat(reader.nextString()).isEqualTo("\t"); } @Test public void testCapitalizedTrueFailWhenStrict() { JsonReader reader = new JsonReader(reader("TRUE")); reader.setStrictness(Strictness.STRICT); IOException expected = assertThrows(IOException.class, reader::nextBoolean); assertThat(expected) .hasMessageThat() .startsWith( "Use JsonReader.setStrictness(Strictness.LENIENT) to accept malformed JSON" + " at line 1 column 1 path $\n"); reader = new JsonReader(reader("True")); reader.setStrictness(Strictness.STRICT); expected = assertThrows(IOException.class, reader::nextBoolean); assertThat(expected) .hasMessageThat() .startsWith( "Use JsonReader.setStrictness(Strictness.LENIENT) to accept malformed JSON" + " at line 1 column 1 path $\n"); } @Test public void testCapitalizedFalseFailWhenStrict() { JsonReader reader = new JsonReader(reader("FALSE")); reader.setStrictness(Strictness.STRICT); IOException expected = assertThrows(IOException.class, reader::nextBoolean); assertThat(expected) .hasMessageThat() .startsWith( "Use JsonReader.setStrictness(Strictness.LENIENT) to accept malformed JSON" + " at line 1 column 1 path $\n"); reader = new JsonReader(reader("FaLse")); reader.setStrictness(Strictness.STRICT); expected = assertThrows(IOException.class, reader::nextBoolean); assertThat(expected) .hasMessageThat() .startsWith( "Use JsonReader.setStrictness(Strictness.LENIENT) to accept malformed JSON" + " at line 1 column 1 path $\n"); } @Test public void testCapitalizedNullFailWhenStrict() { JsonReader reader = new JsonReader(reader("NULL")); reader.setStrictness(Strictness.STRICT); IOException expected = assertThrows(IOException.class, reader::nextNull); assertThat(expected) .hasMessageThat() .startsWith( "Use JsonReader.setStrictness(Strictness.LENIENT) to accept malformed JSON" + " at line 1 column 1 path $\n"); reader = new JsonReader(reader("nulL")); reader.setStrictness(Strictness.STRICT); expected = assertThrows(IOException.class, reader::nextNull); assertThat(expected) .hasMessageThat() .startsWith( "Use JsonReader.setStrictness(Strictness.LENIENT) to accept malformed JSON" + " at line 1 column 1 path $\n"); } @Test public void testReadArray() throws IOException { JsonReader reader = new JsonReader(reader("[true, true]")); reader.beginArray(); assertThat(reader.nextBoolean()).isTrue(); assertThat(reader.nextBoolean()).isTrue(); reader.endArray(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test public void testReadEmptyArray() throws IOException { JsonReader reader = new JsonReader(reader("[]")); reader.beginArray(); assertThat(reader.hasNext()).isFalse(); reader.endArray(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test public void testReadObject() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\": \"android\", \"b\": \"banana\"}")); reader.beginObject(); assertThat(reader.nextName()).isEqualTo("a"); assertThat(reader.nextString()).isEqualTo("android"); assertThat(reader.nextName()).isEqualTo("b"); assertThat(reader.nextString()).isEqualTo("banana"); reader.endObject(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test public void testReadEmptyObject() throws IOException { JsonReader reader = new JsonReader(reader("{}")); reader.beginObject(); assertThat(reader.hasNext()).isFalse(); reader.endObject(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test public void testHasNextEndOfDocument() throws IOException { JsonReader reader = new JsonReader(reader("{}")); reader.beginObject(); reader.endObject(); assertThat(reader.hasNext()).isFalse(); } @Test public void testSkipArray() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\": [\"one\", \"two\", \"three\"], \"b\": 123}")); reader.beginObject(); assertThat(reader.nextName()).isEqualTo("a"); reader.skipValue(); assertThat(reader.nextName()).isEqualTo("b"); assertThat(reader.nextInt()).isEqualTo(123); reader.endObject(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test public void testSkipArrayAfterPeek() throws Exception { JsonReader reader = new JsonReader(reader("{\"a\": [\"one\", \"two\", \"three\"], \"b\": 123}")); reader.beginObject(); assertThat(reader.nextName()).isEqualTo("a"); assertThat(reader.peek()).isEqualTo(BEGIN_ARRAY); reader.skipValue(); assertThat(reader.nextName()).isEqualTo("b"); assertThat(reader.nextInt()).isEqualTo(123); reader.endObject(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test public void testSkipTopLevelObject() throws Exception { JsonReader reader = new JsonReader(reader("{\"a\": [\"one\", \"two\", \"three\"], \"b\": 123}")); reader.skipValue(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test public void testSkipObject() throws IOException { JsonReader reader = new JsonReader( reader("{\"a\": { \"c\": [], \"d\": [true, true, {}] }, \"b\": \"banana\"}")); reader.beginObject(); assertThat(reader.nextName()).isEqualTo("a"); reader.skipValue(); assertThat(reader.nextName()).isEqualTo("b"); reader.skipValue(); reader.endObject(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test public void testSkipObjectAfterPeek() throws Exception { String json = "{" + " \"one\": { \"num\": 1 }" + ", \"two\": { \"num\": 2 }" + ", \"three\": { \"num\": 3 }" + "}"; JsonReader reader = new JsonReader(reader(json)); reader.beginObject(); assertThat(reader.nextName()).isEqualTo("one"); assertThat(reader.peek()).isEqualTo(BEGIN_OBJECT); reader.skipValue(); assertThat(reader.nextName()).isEqualTo("two"); assertThat(reader.peek()).isEqualTo(BEGIN_OBJECT); reader.skipValue(); assertThat(reader.nextName()).isEqualTo("three"); reader.skipValue(); reader.endObject(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test public void testSkipObjectName() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\": 1}")); reader.beginObject(); reader.skipValue(); assertThat(reader.peek()).isEqualTo(JsonToken.NUMBER); assertThat(reader.getPath()).isEqualTo("$."); assertThat(reader.nextInt()).isEqualTo(1); } @Test public void testSkipObjectNameSingleQuoted() throws IOException { JsonReader reader = new JsonReader(reader("{'a': 1}")); reader.setStrictness(Strictness.LENIENT); reader.beginObject(); reader.skipValue(); assertThat(reader.peek()).isEqualTo(JsonToken.NUMBER); assertThat(reader.getPath()).isEqualTo("$."); assertThat(reader.nextInt()).isEqualTo(1); } @Test public void testSkipObjectNameUnquoted() throws IOException { JsonReader reader = new JsonReader(reader("{a: 1}")); reader.setStrictness(Strictness.LENIENT); reader.beginObject(); reader.skipValue(); assertThat(reader.peek()).isEqualTo(JsonToken.NUMBER); assertThat(reader.getPath()).isEqualTo("$."); assertThat(reader.nextInt()).isEqualTo(1); } @Test public void testSkipInteger() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\":123456789,\"b\":-123456789}")); reader.beginObject(); assertThat(reader.nextName()).isEqualTo("a"); reader.skipValue(); assertThat(reader.nextName()).isEqualTo("b"); reader.skipValue(); reader.endObject(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test public void testSkipDouble() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\":-123.456e-789,\"b\":123456789.0}")); reader.beginObject(); assertThat(reader.nextName()).isEqualTo("a"); reader.skipValue(); assertThat(reader.nextName()).isEqualTo("b"); reader.skipValue(); reader.endObject(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test public void testSkipValueAfterEndOfDocument() throws IOException { JsonReader reader = new JsonReader(reader("{}")); reader.beginObject(); reader.endObject(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); assertThat(reader.getPath()).isEqualTo("$"); reader.skipValue(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); assertThat(reader.getPath()).isEqualTo("$"); } @Test public void testSkipValueAtArrayEnd() throws IOException { JsonReader reader = new JsonReader(reader("[]")); reader.beginArray(); reader.skipValue(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); assertThat(reader.getPath()).isEqualTo("$"); } @Test public void testSkipValueAtObjectEnd() throws IOException { JsonReader reader = new JsonReader(reader("{}")); reader.beginObject(); reader.skipValue(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); assertThat(reader.getPath()).isEqualTo("$"); } @Test public void testHelloWorld() throws IOException { String json = "{\n" // + " \"hello\": true,\n" // + " \"foo\": [\"world\"]\n" // + "}"; JsonReader reader = new JsonReader(reader(json)); reader.beginObject(); assertThat(reader.nextName()).isEqualTo("hello"); assertThat(reader.nextBoolean()).isTrue(); assertThat(reader.nextName()).isEqualTo("foo"); reader.beginArray(); assertThat(reader.nextString()).isEqualTo("world"); reader.endArray(); reader.endObject(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test public void testInvalidJsonInput() throws IOException { String json = "{\n" // + " \"h\\ello\": true,\n" // + " \"foo\": [\"world\"]\n" // + "}"; JsonReader reader = new JsonReader(reader(json)); reader.beginObject(); var e = assertThrows(MalformedJsonException.class, () -> reader.nextName()); assertThat(e) .hasMessageThat() .isEqualTo( "Invalid escape sequence at line 2 column 8 path $.\n" + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); } @SuppressWarnings("unused") @Test public void testNulls() { assertThrows(NullPointerException.class, () -> new JsonReader(null)); } @Test public void testEmptyString() { assertThrows(EOFException.class, () -> new JsonReader(reader("")).beginArray()); assertThrows(EOFException.class, () -> new JsonReader(reader("")).beginObject()); } @Test 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(); assertThat(reader.nextString()).isEqualTo("a"); assertThat(reader.nextString()).isEqualTo("a\""); assertThat(reader.nextString()).isEqualTo("\""); assertThat(reader.nextString()).isEqualTo(":"); assertThat(reader.nextString()).isEqualTo(","); assertThat(reader.nextString()).isEqualTo("\b"); assertThat(reader.nextString()).isEqualTo("\f"); assertThat(reader.nextString()).isEqualTo("\n"); assertThat(reader.nextString()).isEqualTo("\r"); assertThat(reader.nextString()).isEqualTo("\t"); assertThat(reader.nextString()).isEqualTo(" "); assertThat(reader.nextString()).isEqualTo("\\"); assertThat(reader.nextString()).isEqualTo("{"); assertThat(reader.nextString()).isEqualTo("}"); assertThat(reader.nextString()).isEqualTo("["); assertThat(reader.nextString()).isEqualTo("]"); assertThat(reader.nextString()).isEqualTo("\0"); assertThat(reader.nextString()).isEqualTo("\u0019"); assertThat(reader.nextString()).isEqualTo("\u20AC"); reader.endArray(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test public void testReaderDoesNotTreatU2028U2029AsNewline() throws IOException { // This test shows that the JSON string [\n"whatever"] is seen as valid // And the JSON string [\u2028"whatever"] is not. String jsonInvalid2028 = "[\u2028\"whatever\"]"; JsonReader readerInvalid2028 = new JsonReader(reader(jsonInvalid2028)); readerInvalid2028.beginArray(); assertThrows(IOException.class, readerInvalid2028::nextString); String jsonInvalid2029 = "[\u2029\"whatever\"]"; JsonReader readerInvalid2029 = new JsonReader(reader(jsonInvalid2029)); readerInvalid2029.beginArray(); assertThrows(IOException.class, readerInvalid2029::nextString); String jsonValid = "[\n\"whatever\"]"; JsonReader readerValid = new JsonReader(reader(jsonValid)); readerValid.beginArray(); assertThat(readerValid.nextString()).isEqualTo("whatever"); // And even in STRICT mode U+2028 and U+2029 are not considered control characters // and can appear unescaped in JSON string String jsonValid2028And2029 = "\"whatever\u2028\u2029\""; JsonReader readerValid2028And2029 = new JsonReader(reader(jsonValid2028And2029)); readerValid2028And2029.setStrictness(Strictness.STRICT); assertThat(readerValid2028And2029.nextString()).isEqualTo("whatever\u2028\u2029"); } @Test public void testEscapeCharacterQuoteInStrictMode() { String json = "\"\\'\""; JsonReader reader = new JsonReader(reader(json)); reader.setStrictness(Strictness.STRICT); IOException expected = assertThrows(IOException.class, reader::nextString); assertThat(expected) .hasMessageThat() .startsWith("Invalid escaped character \"'\" in strict mode"); } @Test public void testEscapeCharacterQuoteWithoutStrictMode() throws IOException { String json = "\"\\'\""; JsonReader reader = new JsonReader(reader(json)); assertThat(reader.nextString()).isEqualTo("'"); } @Test public void testUnescapingInvalidCharacters() throws IOException { String json = "[\"\\u000g\"]"; JsonReader reader = new JsonReader(reader(json)); reader.beginArray(); var e = assertThrows(MalformedJsonException.class, () -> reader.nextString()); assertThat(e) .hasMessageThat() .isEqualTo( "Malformed Unicode escape \\u000g at line 1 column 5 path $[0]\n" + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); } @Test public void testUnescapingTruncatedCharacters() throws IOException { String json = "[\"\\u000"; JsonReader reader = new JsonReader(reader(json)); reader.beginArray(); var e = assertThrows(MalformedJsonException.class, () -> reader.nextString()); assertThat(e) .hasMessageThat() .isEqualTo( "Unterminated escape sequence at line 1 column 5 path $[0]\n" + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); } @Test public void testUnescapingTruncatedSequence() throws IOException { String json = "[\"\\"; JsonReader reader = new JsonReader(reader(json)); reader.beginArray(); var e = assertThrows(MalformedJsonException.class, () -> reader.nextString()); assertThat(e) .hasMessageThat() .isEqualTo( "Unterminated escape sequence at line 1 column 4 path $[0]\n" + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); } @Test public void testIntegersWithFractionalPartSpecified() throws IOException { JsonReader reader = new JsonReader(reader("[1.0,1.0,1.0]")); reader.beginArray(); assertThat(reader.nextDouble()).isEqualTo(1.0); assertThat(reader.nextInt()).isEqualTo(1); assertThat(reader.nextLong()).isEqualTo(1L); } @Test 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(); assertThat(reader.nextDouble()).isEqualTo(-0.0); assertThat(reader.nextDouble()).isEqualTo(1.0); assertThat(reader.nextDouble()).isEqualTo(1.7976931348623157E308); assertThat(reader.nextDouble()).isEqualTo(4.9E-324); assertThat(reader.nextDouble()).isEqualTo(0.0); assertThat(reader.nextDouble()).isEqualTo(0.0); assertThat(reader.nextDouble()).isEqualTo(-0.5); assertThat(reader.nextDouble()).isEqualTo(2.2250738585072014E-308); assertThat(reader.nextDouble()).isEqualTo(3.141592653589793); assertThat(reader.nextDouble()).isEqualTo(2.718281828459045); assertThat(reader.nextDouble()).isEqualTo(0.0); assertThat(reader.nextDouble()).isEqualTo(0.01); assertThat(reader.nextDouble()).isEqualTo(0.0); assertThat(reader.nextDouble()).isEqualTo(1.0); assertThat(reader.nextDouble()).isEqualTo(1.0); assertThat(reader.nextDouble()).isEqualTo(1.0); assertThat(reader.nextDouble()).isEqualTo(10.0); assertThat(reader.nextDouble()).isEqualTo(10.0); reader.endArray(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test public void testStrictNonFiniteDoubles() throws IOException { String json = "[NaN]"; JsonReader reader = new JsonReader(reader(json)); reader.beginArray(); var e = assertThrows(MalformedJsonException.class, () -> reader.nextDouble()); assertStrictError(e, "line 1 column 2 path $[0]"); } @Test public void testStrictQuotedNonFiniteDoubles() throws IOException { String json = "[\"NaN\"]"; JsonReader reader = new JsonReader(reader(json)); reader.beginArray(); var e = assertThrows(MalformedJsonException.class, () -> reader.nextDouble()); assertThat(e) .hasMessageThat() .isEqualTo( "JSON forbids NaN and infinities: NaN at line 1 column 7 path $[0]\n" + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); } @Test public void testLenientNonFiniteDoubles() throws IOException { String json = "[NaN, -Infinity, Infinity]"; JsonReader reader = new JsonReader(reader(json)); reader.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.nextDouble()).isNaN(); assertThat(reader.nextDouble()).isEqualTo(Double.NEGATIVE_INFINITY); assertThat(reader.nextDouble()).isEqualTo(Double.POSITIVE_INFINITY); reader.endArray(); } @Test public void testLenientQuotedNonFiniteDoubles() throws IOException { String json = "[\"NaN\", \"-Infinity\", \"Infinity\"]"; JsonReader reader = new JsonReader(reader(json)); reader.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.nextDouble()).isNaN(); assertThat(reader.nextDouble()).isEqualTo(Double.NEGATIVE_INFINITY); assertThat(reader.nextDouble()).isEqualTo(Double.POSITIVE_INFINITY); reader.endArray(); } @Test public void testStrictNonFiniteDoublesWithSkipValue() throws IOException { String json = "[NaN]"; JsonReader reader = new JsonReader(reader(json)); reader.beginArray(); var e = assertThrows(MalformedJsonException.class, () -> reader.skipValue()); assertStrictError(e, "line 1 column 2 path $[0]"); } @Test 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(); assertThat(reader.nextLong()).isEqualTo(0L); assertThat(reader.nextInt()).isEqualTo(0); assertThat(reader.nextDouble()).isEqualTo(0.0); assertThat(reader.nextLong()).isEqualTo(1L); assertThat(reader.nextInt()).isEqualTo(1); assertThat(reader.nextDouble()).isEqualTo(1.0); assertThat(reader.nextLong()).isEqualTo(-1L); assertThat(reader.nextInt()).isEqualTo(-1); assertThat(reader.nextDouble()).isEqualTo(-1.0); assertThrows(NumberFormatException.class, () -> reader.nextInt()); assertThat(reader.nextLong()).isEqualTo(Long.MIN_VALUE); assertThrows(NumberFormatException.class, () -> reader.nextInt()); assertThat(reader.nextLong()).isEqualTo(Long.MAX_VALUE); reader.endArray(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test public void testNonAsciiDigits() throws IOException { String asciiDigits = "123"; String nonAsciiDigits = "123"; // full-width digits // These should work assertThat(new JsonReader(reader(asciiDigits)).nextInt()).isEqualTo(123); assertThat(new JsonReader(reader(asciiDigits)).nextLong()).isEqualTo(123L); assertThat(new JsonReader(reader('"' + asciiDigits + '"')).nextInt()).isEqualTo(123); assertThat(new JsonReader(reader('"' + asciiDigits + '"')).nextLong()).isEqualTo(123L); // Integer.parseInt happily accepts non-ASCII digits... assertThat(Integer.parseInt(nonAsciiDigits)).isEqualTo(123); // ...but nevertheless these should not work assertThrows( MalformedJsonException.class, () -> new JsonReader(reader(nonAsciiDigits)).nextInt()); assertThrows( MalformedJsonException.class, () -> new JsonReader(reader(nonAsciiDigits)).nextLong()); assertThrows( MalformedJsonException.class, () -> new JsonReader(reader('"' + nonAsciiDigits + '"')).nextInt()); assertThrows( MalformedJsonException.class, () -> new JsonReader(reader('"' + nonAsciiDigits + '"')).nextLong()); } @Test public void testNumberWithOctalPrefix() throws IOException { String number = "01"; String expectedLocation = "line 1 column 1 path $"; var e = assertThrows(MalformedJsonException.class, () -> new JsonReader(reader(number)).peek()); assertStrictError(e, expectedLocation); e = assertThrows(MalformedJsonException.class, () -> new JsonReader(reader(number)).nextInt()); assertStrictError(e, expectedLocation); e = assertThrows(MalformedJsonException.class, () -> new JsonReader(reader(number)).nextLong()); assertStrictError(e, expectedLocation); e = assertThrows( MalformedJsonException.class, () -> new JsonReader(reader(number)).nextDouble()); assertStrictError(e, expectedLocation); e = assertThrows( MalformedJsonException.class, () -> new JsonReader(reader(number)).nextString()); assertStrictError(e, expectedLocation); } @Test public void testBooleans() throws IOException { JsonReader reader = new JsonReader(reader("[true,false]")); reader.beginArray(); assertThat(reader.nextBoolean()).isTrue(); assertThat(reader.nextBoolean()).isFalse(); reader.endArray(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test public void testPeekingUnquotedStringsPrefixedWithBooleans() throws IOException { JsonReader reader = new JsonReader(reader("[truey]")); reader.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.peek()).isEqualTo(STRING); var e = assertThrows(IllegalStateException.class, () -> reader.nextBoolean()); assertUnexpectedStructureError(e, "a boolean", "STRING", "line 1 column 2 path $[0]"); assertThat(reader.nextString()).isEqualTo("truey"); reader.endArray(); } @Test 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"); // non-ASCII digits (these are full-width digits) assertNotANumber("12.3"); } private static void assertNotANumber(String s) throws IOException { JsonReader reader = new JsonReader(reader(s)); reader.setStrictness(Strictness.LENIENT); assertThat(reader.peek()).isEqualTo(JsonToken.STRING); assertThat(reader.nextString()).isEqualTo(s); JsonReader strictReader = new JsonReader(reader(s)); var e = assertThrows( "Should have failed reading " + s + " as double", MalformedJsonException.class, () -> strictReader.nextDouble()); assertThat(e) .hasMessageThat() .startsWith("Use JsonReader.setStrictness(Strictness.LENIENT) to accept malformed JSON"); } @Test public void testPeekingUnquotedStringsPrefixedWithIntegers() throws IOException { JsonReader reader = new JsonReader(reader("[12.34e5x]")); reader.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.peek()).isEqualTo(STRING); assertThrows(NumberFormatException.class, () -> reader.nextInt()); assertThat(reader.nextString()).isEqualTo("12.34e5x"); } @Test public void testPeekLongMinValue() throws IOException { JsonReader reader = new JsonReader(reader("[-9223372036854775808]")); reader.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.peek()).isEqualTo(NUMBER); assertThat(reader.nextLong()).isEqualTo(-9223372036854775808L); } @Test public void testPeekLongMaxValue() throws IOException { JsonReader reader = new JsonReader(reader("[9223372036854775807]")); reader.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.peek()).isEqualTo(NUMBER); assertThat(reader.nextLong()).isEqualTo(9223372036854775807L); } @Test public void testLongLargerThanMaxLongThatWrapsAround() throws IOException { JsonReader reader = new JsonReader(reader("[22233720368547758070]")); reader.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.peek()).isEqualTo(NUMBER); assertThrows(NumberFormatException.class, () -> reader.nextLong()); } @Test public void testLongLargerThanMinLongThatWrapsAround() throws IOException { JsonReader reader = new JsonReader(reader("[-22233720368547758070]")); reader.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.peek()).isEqualTo(NUMBER); assertThrows(NumberFormatException.class, () -> reader.nextLong()); } /** Issue 1053, negative zero. */ @Test public void testNegativeZero() throws Exception { JsonReader reader = new JsonReader(reader("[-0]")); reader.setStrictness(Strictness.LEGACY_STRICT); reader.beginArray(); assertThat(reader.peek()).isEqualTo(NUMBER); assertThat(reader.nextString()).isEqualTo("-0"); } /** * This test fails because there's no double for 9223372036854775808, and our long parsing uses * Double.parseDouble() for fractional values. */ @Test @Ignore public void testPeekLargerThanLongMaxValue() throws IOException { JsonReader reader = new JsonReader(reader("[9223372036854775808]")); reader.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.peek()).isEqualTo(NUMBER); assertThrows(NumberFormatException.class, () -> reader.nextLong()); } /** * This test fails because there's no double for -9223372036854775809, and our long parsing uses * Double.parseDouble() for fractional values. */ @Test @Ignore public void testPeekLargerThanLongMinValue() throws IOException { @SuppressWarnings("FloatingPointLiteralPrecision") double d = -9223372036854775809d; JsonReader reader = new JsonReader(reader("[-9223372036854775809]")); reader.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.peek()).isEqualTo(NUMBER); assertThrows(NumberFormatException.class, () -> reader.nextLong()); assertThat(reader.nextDouble()).isEqualTo(d); } /** * This test fails because there's no double for 9223372036854775806, and our long parsing uses * Double.parseDouble() for fractional values. */ @Test @Ignore public void testHighPrecisionLong() throws IOException { String json = "[9223372036854775806.000]"; JsonReader reader = new JsonReader(reader(json)); reader.beginArray(); assertThat(reader.nextLong()).isEqualTo(9223372036854775806L); reader.endArray(); } @Test public void testPeekMuchLargerThanLongMinValue() throws IOException { @SuppressWarnings("FloatingPointLiteralPrecision") double d = -92233720368547758080d; JsonReader reader = new JsonReader(reader("[-92233720368547758080]")); reader.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.peek()).isEqualTo(NUMBER); assertThrows(NumberFormatException.class, () -> reader.nextLong()); assertThat(reader.nextDouble()).isEqualTo(d); } @Test public void testQuotedNumberWithEscape() throws IOException { JsonReader reader = new JsonReader(reader("[\"12\\u00334\"]")); reader.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.peek()).isEqualTo(STRING); assertThat(reader.nextInt()).isEqualTo(1234); } @Test public void testMixedCaseLiterals() throws IOException { JsonReader reader = new JsonReader(reader("[True,TruE,False,FALSE,NULL,nulL]")); reader.beginArray(); assertThat(reader.nextBoolean()).isTrue(); assertThat(reader.nextBoolean()).isTrue(); assertThat(reader.nextBoolean()).isFalse(); assertThat(reader.nextBoolean()).isFalse(); reader.nextNull(); reader.nextNull(); reader.endArray(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test public void testMissingValue() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\":}")); reader.beginObject(); assertThat(reader.nextName()).isEqualTo("a"); var e = assertThrows(MalformedJsonException.class, () -> reader.nextString()); assertThat(e) .hasMessageThat() .isEqualTo( "Expected value at line 1 column 6 path $.a\n" + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); } @Test public void testPrematureEndOfInput() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\":true,")); reader.beginObject(); assertThat(reader.nextName()).isEqualTo("a"); assertThat(reader.nextBoolean()).isTrue(); assertThrows(EOFException.class, () -> reader.nextName()); } @Test public void testPrematurelyClosed() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\":[]}")); reader.beginObject(); reader.close(); var e = assertThrows(IllegalStateException.class, () -> reader.nextName()); assertThat(e).hasMessageThat().isEqualTo("JsonReader is closed"); JsonReader reader2 = new JsonReader(reader("{\"a\":[]}")); reader2.close(); e = assertThrows(IllegalStateException.class, () -> reader2.beginObject()); assertThat(e).hasMessageThat().isEqualTo("JsonReader is closed"); JsonReader reader3 = new JsonReader(reader("{\"a\":true}")); reader3.beginObject(); String unused1 = reader3.nextName(); JsonToken unused2 = reader3.peek(); reader3.close(); e = assertThrows(IllegalStateException.class, () -> reader3.nextBoolean()); assertThat(e).hasMessageThat().isEqualTo("JsonReader is closed"); } @Test public void testNextFailuresDoNotAdvance() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\":true}")); reader.beginObject(); var e = assertThrows(IllegalStateException.class, () -> reader.nextString()); assertUnexpectedStructureError(e, "a string", "NAME", "line 1 column 3 path $."); assertThat(reader.nextName()).isEqualTo("a"); e = assertThrows(IllegalStateException.class, () -> reader.nextName()); assertUnexpectedStructureError(e, "a name", "BOOLEAN", "line 1 column 10 path $.a"); e = assertThrows(IllegalStateException.class, () -> reader.beginArray()); assertUnexpectedStructureError(e, "BEGIN_ARRAY", "BOOLEAN", "line 1 column 10 path $.a"); e = assertThrows(IllegalStateException.class, () -> reader.endArray()); assertUnexpectedStructureError(e, "END_ARRAY", "BOOLEAN", "line 1 column 10 path $.a"); e = assertThrows(IllegalStateException.class, () -> reader.beginObject()); assertUnexpectedStructureError(e, "BEGIN_OBJECT", "BOOLEAN", "line 1 column 10 path $.a"); e = assertThrows(IllegalStateException.class, () -> reader.endObject()); assertUnexpectedStructureError(e, "END_OBJECT", "BOOLEAN", "line 1 column 10 path $.a"); assertThat(reader.nextBoolean()).isTrue(); e = assertThrows(IllegalStateException.class, () -> reader.nextString()); assertUnexpectedStructureError(e, "a string", "END_OBJECT", "line 1 column 11 path $.a"); e = assertThrows(IllegalStateException.class, () -> reader.nextName()); assertUnexpectedStructureError(e, "a name", "END_OBJECT", "line 1 column 11 path $.a"); e = assertThrows(IllegalStateException.class, () -> reader.beginArray()); assertUnexpectedStructureError(e, "BEGIN_ARRAY", "END_OBJECT", "line 1 column 11 path $.a"); e = assertThrows(IllegalStateException.class, () -> reader.endArray()); assertUnexpectedStructureError(e, "END_ARRAY", "END_OBJECT", "line 1 column 11 path $.a"); reader.endObject(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); reader.close(); } @Test public void testIntegerMismatchFailuresDoNotAdvance() throws IOException { JsonReader reader = new JsonReader(reader("[1.5]")); reader.beginArray(); assertThrows(NumberFormatException.class, () -> reader.nextInt()); assertThat(reader.nextDouble()).isEqualTo(1.5d); reader.endArray(); } @Test public void testStringNullIsNotNull() throws IOException { JsonReader reader = new JsonReader(reader("[\"null\"]")); reader.beginArray(); var e = assertThrows(IllegalStateException.class, () -> reader.nextNull()); assertUnexpectedStructureError(e, "null", "STRING", "line 1 column 3 path $[0]"); } @Test public void testNullLiteralIsNotAString() throws IOException { JsonReader reader = new JsonReader(reader("[null]")); reader.beginArray(); var e = assertThrows(IllegalStateException.class, () -> reader.nextString()); assertUnexpectedStructureError(e, "a string", "NULL", "line 1 column 6 path $[0]"); } @Test public void testStrictNameValueSeparator() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\"=true}")); reader.beginObject(); assertThat(reader.nextName()).isEqualTo("a"); var e = assertThrows(MalformedJsonException.class, () -> reader.nextBoolean()); assertStrictError(e, "line 1 column 6 path $.a"); JsonReader reader2 = new JsonReader(reader("{\"a\"=>true}")); reader2.beginObject(); assertThat(reader2.nextName()).isEqualTo("a"); e = assertThrows(MalformedJsonException.class, () -> reader2.nextBoolean()); assertStrictError(e, "line 1 column 6 path $.a"); } @Test public void testLenientNameValueSeparator() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\"=true}")); reader.setStrictness(Strictness.LENIENT); reader.beginObject(); assertThat(reader.nextName()).isEqualTo("a"); assertThat(reader.nextBoolean()).isTrue(); reader = new JsonReader(reader("{\"a\"=>true}")); reader.setStrictness(Strictness.LENIENT); reader.beginObject(); assertThat(reader.nextName()).isEqualTo("a"); assertThat(reader.nextBoolean()).isTrue(); } @Test public void testStrictNameValueSeparatorWithSkipValue() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\"=true}")); reader.beginObject(); assertThat(reader.nextName()).isEqualTo("a"); var e = assertThrows(MalformedJsonException.class, () -> reader.skipValue()); assertStrictError(e, "line 1 column 6 path $.a"); JsonReader reader2 = new JsonReader(reader("{\"a\"=>true}")); reader2.beginObject(); assertThat(reader2.nextName()).isEqualTo("a"); e = assertThrows(MalformedJsonException.class, () -> reader2.skipValue()); assertStrictError(e, "line 1 column 6 path $.a"); } @Test public void testCommentsInStringValue() throws Exception { JsonReader reader = new JsonReader(reader("[\"// comment\"]")); reader.beginArray(); assertThat(reader.nextString()).isEqualTo("// comment"); reader.endArray(); reader = new JsonReader(reader("{\"a\":\"#someComment\"}")); reader.beginObject(); assertThat(reader.nextName()).isEqualTo("a"); assertThat(reader.nextString()).isEqualTo("#someComment"); reader.endObject(); reader = new JsonReader(reader("{\"#//a\":\"#some //Comment\"}")); reader.beginObject(); assertThat(reader.nextName()).isEqualTo("#//a"); assertThat(reader.nextString()).isEqualTo("#some //Comment"); reader.endObject(); } @Test public void testStrictComments() throws IOException { JsonReader reader = new JsonReader(reader("[// comment \n true]")); reader.beginArray(); var e = assertThrows(MalformedJsonException.class, () -> reader.nextBoolean()); assertStrictError(e, "line 1 column 3 path $[0]"); JsonReader reader2 = new JsonReader(reader("[# comment \n true]")); reader2.beginArray(); e = assertThrows(MalformedJsonException.class, () -> reader2.nextBoolean()); assertStrictError(e, "line 1 column 3 path $[0]"); JsonReader reader3 = new JsonReader(reader("[/* comment */ true]")); reader3.beginArray(); e = assertThrows(MalformedJsonException.class, () -> reader3.nextBoolean()); assertStrictError(e, "line 1 column 3 path $[0]"); } @Test public void testLenientComments() throws IOException { JsonReader reader = new JsonReader(reader("[// comment \n true]")); reader.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.nextBoolean()).isTrue(); reader = new JsonReader(reader("[# comment \n true]")); reader.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.nextBoolean()).isTrue(); reader = new JsonReader(reader("[/* comment */ true]")); reader.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.nextBoolean()).isTrue(); } @Test public void testStrictCommentsWithSkipValue() throws IOException { JsonReader reader = new JsonReader(reader("[// comment \n true]")); reader.beginArray(); var e = assertThrows(MalformedJsonException.class, () -> reader.skipValue()); assertStrictError(e, "line 1 column 3 path $[0]"); JsonReader reader2 = new JsonReader(reader("[# comment \n true]")); reader2.beginArray(); e = assertThrows(MalformedJsonException.class, () -> reader2.skipValue()); assertStrictError(e, "line 1 column 3 path $[0]"); JsonReader reader3 = new JsonReader(reader("[/* comment */ true]")); reader3.beginArray(); e = assertThrows(MalformedJsonException.class, () -> reader3.skipValue()); assertStrictError(e, "line 1 column 3 path $[0]"); } @Test public void testStrictUnquotedNames() throws IOException { JsonReader reader = new JsonReader(reader("{a:true}")); reader.beginObject(); var e = assertThrows(MalformedJsonException.class, () -> reader.nextName()); assertStrictError(e, "line 1 column 3 path $."); } @Test public void testLenientUnquotedNames() throws IOException { JsonReader reader = new JsonReader(reader("{a:true}")); reader.setStrictness(Strictness.LENIENT); reader.beginObject(); assertThat(reader.nextName()).isEqualTo("a"); } @Test public void testStrictUnquotedNamesWithSkipValue() throws IOException { JsonReader reader = new JsonReader(reader("{a:true}")); reader.beginObject(); var e = assertThrows(MalformedJsonException.class, () -> reader.skipValue()); assertStrictError(e, "line 1 column 3 path $."); } @Test public void testStrictSingleQuotedNames() throws IOException { JsonReader reader = new JsonReader(reader("{'a':true}")); reader.beginObject(); var e = assertThrows(MalformedJsonException.class, () -> reader.nextName()); assertStrictError(e, "line 1 column 3 path $."); } @Test public void testLenientSingleQuotedNames() throws IOException { JsonReader reader = new JsonReader(reader("{'a':true}")); reader.setStrictness(Strictness.LENIENT); reader.beginObject(); assertThat(reader.nextName()).isEqualTo("a"); } @Test public void testStrictSingleQuotedNamesWithSkipValue() throws IOException { JsonReader reader = new JsonReader(reader("{'a':true}")); reader.beginObject(); var e = assertThrows(MalformedJsonException.class, () -> reader.skipValue()); assertStrictError(e, "line 1 column 3 path $."); } @Test public void testStrictUnquotedStrings() throws IOException { JsonReader reader = new JsonReader(reader("[a]")); reader.beginArray(); var e = assertThrows(MalformedJsonException.class, () -> reader.nextString()); assertStrictError(e, "line 1 column 2 path $[0]"); } @Test public void testStrictUnquotedStringsWithSkipValue() throws IOException { JsonReader reader = new JsonReader(reader("[a]")); reader.beginArray(); var e = assertThrows(MalformedJsonException.class, () -> reader.skipValue()); assertStrictError(e, "line 1 column 2 path $[0]"); } @Test public void testLenientUnquotedStrings() throws IOException { JsonReader reader = new JsonReader(reader("[a]")); reader.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.nextString()).isEqualTo("a"); } @Test public void testStrictSingleQuotedStrings() throws IOException { JsonReader reader = new JsonReader(reader("['a']")); reader.beginArray(); var e = assertThrows(MalformedJsonException.class, () -> reader.nextString()); assertStrictError(e, "line 1 column 3 path $[0]"); } @Test public void testLenientSingleQuotedStrings() throws IOException { JsonReader reader = new JsonReader(reader("['a']")); reader.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.nextString()).isEqualTo("a"); } @Test public void testStrictSingleQuotedStringsWithSkipValue() throws IOException { JsonReader reader = new JsonReader(reader("['a']")); reader.beginArray(); var e = assertThrows(MalformedJsonException.class, () -> reader.skipValue()); assertStrictError(e, "line 1 column 3 path $[0]"); } @Test public void testStrictSemicolonDelimitedArray() throws IOException { JsonReader reader = new JsonReader(reader("[true;true]")); reader.beginArray(); var e = assertThrows(MalformedJsonException.class, () -> reader.nextBoolean()); assertStrictError(e, "line 1 column 2 path $[0]"); } @Test public void testLenientSemicolonDelimitedArray() throws IOException { JsonReader reader = new JsonReader(reader("[true;true]")); reader.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.nextBoolean()).isTrue(); assertThat(reader.nextBoolean()).isTrue(); } @Test public void testStrictSemicolonDelimitedArrayWithSkipValue() throws IOException { JsonReader reader = new JsonReader(reader("[true;true]")); reader.beginArray(); var e = assertThrows(MalformedJsonException.class, () -> reader.skipValue()); assertStrictError(e, "line 1 column 2 path $[0]"); } @Test public void testStrictSemicolonDelimitedNameValuePair() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\":true;\"b\":true}")); reader.beginObject(); assertThat(reader.nextName()).isEqualTo("a"); var e = assertThrows(MalformedJsonException.class, () -> reader.nextBoolean()); assertStrictError(e, "line 1 column 6 path $.a"); } @Test public void testLenientSemicolonDelimitedNameValuePair() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\":true;\"b\":true}")); reader.setStrictness(Strictness.LENIENT); reader.beginObject(); assertThat(reader.nextName()).isEqualTo("a"); assertThat(reader.nextBoolean()).isTrue(); assertThat(reader.nextName()).isEqualTo("b"); } @Test public void testStrictSemicolonDelimitedNameValuePairWithSkipValue() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\":true;\"b\":true}")); reader.beginObject(); assertThat(reader.nextName()).isEqualTo("a"); var e = assertThrows(MalformedJsonException.class, () -> reader.skipValue()); assertStrictError(e, "line 1 column 6 path $.a"); } @Test public void testStrictUnnecessaryArraySeparators() throws IOException { // The following calls `nextNull()` because a lenient JsonReader would treat redundant array // separators as implicit JSON null JsonReader reader = new JsonReader(reader("[true,,true]")); reader.beginArray(); assertThat(reader.nextBoolean()).isTrue(); var e = assertThrows(MalformedJsonException.class, () -> reader.nextNull()); assertStrictError(e, "line 1 column 8 path $[1]"); JsonReader reader2 = new JsonReader(reader("[,true]")); reader2.beginArray(); e = assertThrows(MalformedJsonException.class, () -> reader2.nextNull()); assertStrictError(e, "line 1 column 3 path $[0]"); JsonReader reader3 = new JsonReader(reader("[true,]")); reader3.beginArray(); assertThat(reader3.nextBoolean()).isTrue(); e = assertThrows(MalformedJsonException.class, () -> reader3.nextNull()); assertStrictError(e, "line 1 column 8 path $[1]"); JsonReader reader4 = new JsonReader(reader("[,]")); reader4.beginArray(); e = assertThrows(MalformedJsonException.class, () -> reader4.nextNull()); assertStrictError(e, "line 1 column 3 path $[0]"); } @Test public void testLenientUnnecessaryArraySeparators() throws IOException { JsonReader reader = new JsonReader(reader("[true,,true]")); reader.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.nextBoolean()).isTrue(); // Redundant array separators are treated as implicit JSON null reader.nextNull(); assertThat(reader.nextBoolean()).isTrue(); reader.endArray(); reader = new JsonReader(reader("[,true]")); reader.setStrictness(Strictness.LENIENT); reader.beginArray(); reader.nextNull(); assertThat(reader.nextBoolean()).isTrue(); reader.endArray(); reader = new JsonReader(reader("[true,]")); reader.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.nextBoolean()).isTrue(); reader.nextNull(); reader.endArray(); reader = new JsonReader(reader("[,]")); reader.setStrictness(Strictness.LENIENT); reader.beginArray(); reader.nextNull(); reader.nextNull(); reader.endArray(); } @Test public void testStrictUnnecessaryArraySeparatorsWithSkipValue() throws IOException { JsonReader reader = new JsonReader(reader("[true,,true]")); reader.beginArray(); assertThat(reader.nextBoolean()).isTrue(); var e = assertThrows(MalformedJsonException.class, () -> reader.skipValue()); assertStrictError(e, "line 1 column 8 path $[1]"); JsonReader reader2 = new JsonReader(reader("[,true]")); reader2.beginArray(); e = assertThrows(MalformedJsonException.class, () -> reader2.skipValue()); assertStrictError(e, "line 1 column 3 path $[0]"); JsonReader reader3 = new JsonReader(reader("[true,]")); reader3.beginArray(); assertThat(reader3.nextBoolean()).isTrue(); e = assertThrows(MalformedJsonException.class, () -> reader3.skipValue()); assertStrictError(e, "line 1 column 8 path $[1]"); JsonReader reader4 = new JsonReader(reader("[,]")); reader4.beginArray(); e = assertThrows(MalformedJsonException.class, () -> reader4.skipValue()); assertStrictError(e, "line 1 column 3 path $[0]"); } @Test public void testStrictMultipleTopLevelValues() throws IOException { JsonReader reader = new JsonReader(reader("[] []")); reader.beginArray(); reader.endArray(); var e = assertThrows(MalformedJsonException.class, () -> reader.peek()); assertStrictError(e, "line 1 column 5 path $"); } @Test public void testLenientMultipleTopLevelValues() throws IOException { JsonReader reader = new JsonReader(reader("[] true {}")); reader.setStrictness(Strictness.LENIENT); reader.beginArray(); reader.endArray(); assertThat(reader.nextBoolean()).isTrue(); reader.beginObject(); reader.endObject(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test public void testStrictMultipleTopLevelValuesWithSkipValue() throws IOException { JsonReader reader = new JsonReader(reader("[] []")); reader.beginArray(); reader.endArray(); var e = assertThrows(MalformedJsonException.class, () -> reader.skipValue()); assertStrictError(e, "line 1 column 5 path $"); } @Test public void testTopLevelValueTypes() throws IOException { JsonReader reader1 = new JsonReader(reader("true")); assertThat(reader1.nextBoolean()).isTrue(); assertThat(reader1.peek()).isEqualTo(JsonToken.END_DOCUMENT); JsonReader reader2 = new JsonReader(reader("false")); assertThat(reader2.nextBoolean()).isFalse(); assertThat(reader2.peek()).isEqualTo(JsonToken.END_DOCUMENT); JsonReader reader3 = new JsonReader(reader("null")); assertThat(reader3.peek()).isEqualTo(JsonToken.NULL); reader3.nextNull(); assertThat(reader3.peek()).isEqualTo(JsonToken.END_DOCUMENT); JsonReader reader4 = new JsonReader(reader("123")); assertThat(reader4.nextInt()).isEqualTo(123); assertThat(reader4.peek()).isEqualTo(JsonToken.END_DOCUMENT); JsonReader reader5 = new JsonReader(reader("123.4")); assertThat(reader5.nextDouble()).isEqualTo(123.4); assertThat(reader5.peek()).isEqualTo(JsonToken.END_DOCUMENT); JsonReader reader6 = new JsonReader(reader("\"a\"")); assertThat(reader6.nextString()).isEqualTo("a"); assertThat(reader6.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test public void testTopLevelValueTypeWithSkipValue() throws IOException { JsonReader reader = new JsonReader(reader("true")); reader.skipValue(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test public void testStrictNonExecutePrefix() { JsonReader reader = new JsonReader(reader(")]}'\n []")); var e = assertThrows(MalformedJsonException.class, () -> reader.beginArray()); assertStrictError(e, "line 1 column 1 path $"); } @Test public void testStrictNonExecutePrefixWithSkipValue() { JsonReader reader = new JsonReader(reader(")]}'\n []")); var e = assertThrows(MalformedJsonException.class, () -> reader.skipValue()); assertStrictError(e, "line 1 column 1 path $"); } @Test public void testLenientNonExecutePrefix() throws IOException { JsonReader reader = new JsonReader(reader(")]}'\n []")); reader.setStrictness(Strictness.LENIENT); reader.beginArray(); reader.endArray(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test public void testLenientNonExecutePrefixWithLeadingWhitespace() throws IOException { JsonReader reader = new JsonReader(reader("\r\n \t)]}'\n []")); reader.setStrictness(Strictness.LENIENT); reader.beginArray(); reader.endArray(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test public void testLenientPartialNonExecutePrefix() throws IOException { JsonReader reader = new JsonReader(reader(")]}' []")); reader.setStrictness(Strictness.LENIENT); assertThat(reader.nextString()).isEqualTo(")"); var e = assertThrows(MalformedJsonException.class, () -> reader.nextString()); assertThat(e) .hasMessageThat() .isEqualTo( "Unexpected value at line 1 column 3 path $\n" + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); } @Test public void testBomIgnoredAsFirstCharacterOfDocument() throws IOException { JsonReader reader = new JsonReader(reader("\ufeff[]")); reader.beginArray(); reader.endArray(); } @Test public void testBomForbiddenAsOtherCharacterInDocument() throws IOException { JsonReader reader = new JsonReader(reader("[\ufeff]")); reader.beginArray(); var e = assertThrows(MalformedJsonException.class, () -> reader.endArray()); assertStrictError(e, "line 1 column 2 path $[0]"); } @SuppressWarnings("UngroupedOverloads") @Test public void testFailWithPosition() throws IOException { testFailWithPosition("Expected value at line 6 column 5 path $[1]", "[\n\n\n\n\n\"a\",}]"); } @Test 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\",}]"); } @Test public void testFailWithPositionOverSlashSlashEndOfLineComment() throws IOException { testFailWithPosition( "Expected value at line 5 column 6 path $[1]", "\n// foo\n\n//bar\r\n[\"a\",}"); } @Test public void testFailWithPositionOverHashEndOfLineComment() throws IOException { testFailWithPosition( "Expected value at line 5 column 6 path $[1]", "\n# foo\n\n#bar\r\n[\"a\",}"); } @Test public void testFailWithPositionOverCStyleComment() throws IOException { testFailWithPosition( "Expected value at line 6 column 12 path $[1]", "\n\n/* foo\n*\n*\r\nbar */[\"a\",}"); } @Test public void testFailWithPositionOverQuotedString() throws IOException { testFailWithPosition( "Expected value at line 5 column 3 path $[1]", "[\"foo\nbar\r\nbaz\n\",\n }"); } @Test public void testFailWithPositionOverUnquotedString() throws IOException { testFailWithPosition("Expected value at line 5 column 2 path $[1]", "[\n\nabcd\n\n,}"); } @Test public void testFailWithEscapedNewlineCharacter() throws IOException { testFailWithPosition("Expected value at line 5 column 3 path $[1]", "[\n\n\"\\\n\n\",}"); } @Test public void testFailWithPositionIsOffsetByBom() throws IOException { testFailWithPosition("Expected value at line 1 column 6 path $[1]", "\ufeff[\"a\",}]"); } private static void testFailWithPosition(String message, String json) throws IOException { // Validate that it works reading the string normally. JsonReader reader1 = new JsonReader(reader(json)); reader1.setStrictness(Strictness.LENIENT); reader1.beginArray(); String unused1 = reader1.nextString(); var e = assertThrows(MalformedJsonException.class, () -> reader1.peek()); assertThat(e) .hasMessageThat() .isEqualTo( message + "\n" + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); // Also validate that it works when skipping. JsonReader reader2 = new JsonReader(reader(json)); reader2.setStrictness(Strictness.LENIENT); reader2.beginArray(); reader2.skipValue(); e = assertThrows(MalformedJsonException.class, () -> reader2.peek()); assertThat(e) .hasMessageThat() .isEqualTo( message + "\n" + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); } @Test public void testFailWithPositionDeepPath() throws IOException { JsonReader reader = new JsonReader(reader("[1,{\"a\":[2,3,}")); reader.beginArray(); int unused1 = reader.nextInt(); reader.beginObject(); String unused2 = reader.nextName(); reader.beginArray(); int unused3 = reader.nextInt(); int unused4 = reader.nextInt(); var e = assertThrows(MalformedJsonException.class, () -> reader.peek()); assertThat(e) .hasMessageThat() .isEqualTo( "Expected value at line 1 column 14 path $[1].a[2]\n" + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); } @Test public void testStrictVeryLongNumber() throws IOException { JsonReader reader = new JsonReader(reader("[0." + repeat('9', 8192) + "]")); reader.beginArray(); var e = assertThrows(MalformedJsonException.class, () -> reader.nextDouble()); assertStrictError(e, "line 1 column 2 path $[0]"); } @Test public void testLenientVeryLongNumber() throws IOException { JsonReader reader = new JsonReader(reader("[0." + repeat('9', 8192) + "]")); reader.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.peek()).isEqualTo(JsonToken.STRING); assertThat(reader.nextDouble()).isEqualTo(1d); reader.endArray(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test public void testVeryLongUnquotedLiteral() throws IOException { String literal = "a" + repeat('b', 8192) + "c"; JsonReader reader = new JsonReader(reader("[" + literal + "]")); reader.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.nextString()).isEqualTo(literal); reader.endArray(); } @Test 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(); } assertThat(reader.getPath()) .isEqualTo( "$[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]"); for (int i = 0; i < 40; i++) { reader.endArray(); } assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test public void testDeeplyNestedObjects() throws IOException { // Build a JSON document structured like {"a":{"a":{"a":{"a":true}}}}, but 40 levels deep String json = "true"; for (int i = 0; i < 40; i++) { json = String.format("{\"a\":%s}", json); } JsonReader reader = new JsonReader(reader(json)); for (int i = 0; i < 40; i++) { reader.beginObject(); assertThat(reader.nextName()).isEqualTo("a"); } assertThat(reader.getPath()) .isEqualTo( "$.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"); assertThat(reader.nextBoolean()).isTrue(); for (int i = 0; i < 40; i++) { reader.endObject(); } assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test public void testNestingLimitDefault() throws IOException { int defaultLimit = JsonReader.DEFAULT_NESTING_LIMIT; String json = repeat('[', defaultLimit + 1); JsonReader reader = new JsonReader(reader(json)); assertThat(reader.getNestingLimit()).isEqualTo(defaultLimit); for (int i = 0; i < defaultLimit; i++) { reader.beginArray(); } MalformedJsonException e = assertThrows(MalformedJsonException.class, () -> reader.beginArray()); assertThat(e) .hasMessageThat() .isEqualTo( "Nesting limit " + defaultLimit + " reached at line 1 column " + (defaultLimit + 2) + " path $" + "[0]".repeat(defaultLimit)); } // Note: The column number reported in the expected exception messages is slightly off and points // behind instead of directly at the '[' or '{' @Test public void testNestingLimit() throws IOException { JsonReader reader = new JsonReader(reader("[{\"a\":1}]")); reader.setNestingLimit(2); assertThat(reader.getNestingLimit()).isEqualTo(2); reader.beginArray(); reader.beginObject(); assertThat(reader.nextName()).isEqualTo("a"); assertThat(reader.nextInt()).isEqualTo(1); reader.endObject(); reader.endArray(); JsonReader reader2 = new JsonReader(reader("[{\"a\":[]}]")); reader2.setNestingLimit(2); reader2.beginArray(); reader2.beginObject(); assertThat(reader2.nextName()).isEqualTo("a"); MalformedJsonException e = assertThrows(MalformedJsonException.class, () -> reader2.beginArray()); assertThat(e) .hasMessageThat() .isEqualTo("Nesting limit 2 reached at line 1 column 8 path $[0].a"); JsonReader reader3 = new JsonReader(reader("[]")); reader3.setNestingLimit(0); e = assertThrows(MalformedJsonException.class, () -> reader3.beginArray()); assertThat(e).hasMessageThat().isEqualTo("Nesting limit 0 reached at line 1 column 2 path $"); JsonReader reader4 = new JsonReader(reader("[]")); reader4.setNestingLimit(0); // Currently also checked when skipping values e = assertThrows(MalformedJsonException.class, () -> reader4.skipValue()); assertThat(e).hasMessageThat().isEqualTo("Nesting limit 0 reached at line 1 column 2 path $"); JsonReader reader5 = new JsonReader(reader("1")); reader5.setNestingLimit(0); // Reading value other than array or object should be allowed assertThat(reader5.nextInt()).isEqualTo(1); // Test multiple top-level arrays JsonReader reader6 = new JsonReader(reader("[] [[]]")); reader6.setStrictness(Strictness.LENIENT); reader6.setNestingLimit(1); reader6.beginArray(); reader6.endArray(); reader6.beginArray(); e = assertThrows(MalformedJsonException.class, () -> reader6.beginArray()); assertThat(e) .hasMessageThat() .isEqualTo("Nesting limit 1 reached at line 1 column 6 path $[0]"); JsonReader reader7 = new JsonReader(reader("[]")); IllegalArgumentException argException = assertThrows(IllegalArgumentException.class, () -> reader7.setNestingLimit(-1)); assertThat(argException).hasMessageThat().isEqualTo("Invalid nesting limit: -1"); } // http://code.google.com/p/google-gson/issues/detail?id=409 @Test public void testStringEndingInSlash() { JsonReader reader = new JsonReader(reader("/")); reader.setStrictness(Strictness.LENIENT); var e = assertThrows(MalformedJsonException.class, () -> reader.peek()); assertThat(e) .hasMessageThat() .isEqualTo( "Expected value at line 1 column 1 path $\n" + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); } @Test public void testDocumentWithCommentEndingInSlash() { JsonReader reader = new JsonReader(reader("/* foo *//")); reader.setStrictness(Strictness.LENIENT); var e = assertThrows(MalformedJsonException.class, () -> reader.peek()); assertThat(e) .hasMessageThat() .isEqualTo( "Expected value at line 1 column 10 path $\n" + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); } @Test public void testStringWithLeadingSlash() { JsonReader reader = new JsonReader(reader("/x")); reader.setStrictness(Strictness.LENIENT); var e = assertThrows(MalformedJsonException.class, () -> reader.peek()); assertThat(e) .hasMessageThat() .isEqualTo( "Expected value at line 1 column 1 path $\n" + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); } @Test public void testUnterminatedObject() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\":\"android\"x")); reader.setStrictness(Strictness.LENIENT); reader.beginObject(); assertThat(reader.nextName()).isEqualTo("a"); assertThat(reader.nextString()).isEqualTo("android"); var e = assertThrows(MalformedJsonException.class, () -> reader.peek()); assertThat(e) .hasMessageThat() .isEqualTo( "Unterminated object at line 1 column 16 path $.a\n" + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); } @Test 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(); assertThat(reader.nextString()).isEqualTo(string); reader.endArray(); } @Test 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.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.nextString()).isEqualTo(string); reader.endArray(); } @Test 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.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.nextString()).isEqualTo(string); assertThrows(EOFException.class, () -> reader.peek()); } @Test public void testSkipVeryLongUnquotedString() throws IOException { JsonReader reader = new JsonReader(reader("[" + repeat('x', 8192) + "]")); reader.setStrictness(Strictness.LENIENT); reader.beginArray(); reader.skipValue(); reader.endArray(); } @Test public void testSkipTopLevelUnquotedString() throws IOException { JsonReader reader = new JsonReader(reader(repeat('x', 8192))); reader.setStrictness(Strictness.LENIENT); reader.skipValue(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test public void testSkipVeryLongQuotedString() throws IOException { JsonReader reader = new JsonReader(reader("[\"" + repeat('x', 8192) + "\"]")); reader.beginArray(); reader.skipValue(); reader.endArray(); } @Test public void testSkipTopLevelQuotedString() throws IOException { JsonReader reader = new JsonReader(reader("\"" + repeat('x', 8192) + "\"")); reader.setStrictness(Strictness.LENIENT); reader.skipValue(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test public void testStringAsNumberWithTruncatedExponent() throws IOException { JsonReader reader = new JsonReader(reader("[123e]")); reader.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.peek()).isEqualTo(STRING); } @Test public void testStringAsNumberWithDigitAndNonDigitExponent() throws IOException { JsonReader reader = new JsonReader(reader("[123e4b]")); reader.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.peek()).isEqualTo(STRING); } @Test public void testStringAsNumberWithNonDigitExponent() throws IOException { JsonReader reader = new JsonReader(reader("[123eb]")); reader.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.peek()).isEqualTo(STRING); } @Test public void testEmptyStringName() throws IOException { JsonReader reader = new JsonReader(reader("{\"\":true}")); reader.setStrictness(Strictness.LENIENT); assertThat(reader.peek()).isEqualTo(BEGIN_OBJECT); reader.beginObject(); assertThat(reader.peek()).isEqualTo(NAME); assertThat(reader.nextName()).isEqualTo(""); assertThat(reader.peek()).isEqualTo(JsonToken.BOOLEAN); assertThat(reader.nextBoolean()).isTrue(); assertThat(reader.peek()).isEqualTo(JsonToken.END_OBJECT); reader.endObject(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test public void testStrictExtraCommasInMaps() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\":\"b\",}")); reader.beginObject(); assertThat(reader.nextName()).isEqualTo("a"); assertThat(reader.nextString()).isEqualTo("b"); var e = assertThrows(MalformedJsonException.class, () -> reader.peek()); assertThat(e) .hasMessageThat() .isEqualTo( "Expected name at line 1 column 11 path $.a\n" + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); } @Test public void testLenientExtraCommasInMaps() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\":\"b\",}")); reader.setStrictness(Strictness.LENIENT); reader.beginObject(); assertThat(reader.nextName()).isEqualTo("a"); assertThat(reader.nextString()).isEqualTo("b"); var e = assertThrows(MalformedJsonException.class, () -> reader.peek()); assertThat(e) .hasMessageThat() .isEqualTo( "Expected name at line 1 column 11 path $.a\n" + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); } private static String repeat(char c, int count) { char[] array = new char[count]; Arrays.fill(array, c); return new String(array); } @Test public void testMalformedDocuments() throws IOException { assertDocument("{]", BEGIN_OBJECT, MalformedJsonException.class); assertDocument("{,", BEGIN_OBJECT, MalformedJsonException.class); assertDocument("{{", BEGIN_OBJECT, MalformedJsonException.class); assertDocument("{[", BEGIN_OBJECT, MalformedJsonException.class); assertDocument("{:", BEGIN_OBJECT, MalformedJsonException.class); assertDocument("{\"name\",", BEGIN_OBJECT, NAME, MalformedJsonException.class); assertDocument("{\"name\",", BEGIN_OBJECT, NAME, MalformedJsonException.class); assertDocument("{\"name\":}", BEGIN_OBJECT, NAME, MalformedJsonException.class); assertDocument("{\"name\"::", BEGIN_OBJECT, NAME, MalformedJsonException.class); assertDocument("{\"name\":,", BEGIN_OBJECT, NAME, MalformedJsonException.class); assertDocument("{\"name\"=}", BEGIN_OBJECT, NAME, MalformedJsonException.class); assertDocument("{\"name\"=>}", BEGIN_OBJECT, NAME, MalformedJsonException.class); assertDocument( "{\"name\"=>\"string\":", BEGIN_OBJECT, NAME, STRING, MalformedJsonException.class); assertDocument( "{\"name\"=>\"string\"=", BEGIN_OBJECT, NAME, STRING, MalformedJsonException.class); assertDocument( "{\"name\"=>\"string\"=>", BEGIN_OBJECT, NAME, STRING, MalformedJsonException.class); assertDocument("{\"name\"=>\"string\",", BEGIN_OBJECT, NAME, STRING, EOFException.class); assertDocument("{\"name\"=>\"string\",\"name\"", BEGIN_OBJECT, NAME, STRING, NAME); assertDocument("[}", BEGIN_ARRAY, MalformedJsonException.class); assertDocument("[,]", BEGIN_ARRAY, NULL, NULL, END_ARRAY); assertDocument("{", BEGIN_OBJECT, EOFException.class); assertDocument("{\"name\"", BEGIN_OBJECT, NAME, EOFException.class); assertDocument("{\"name\",", BEGIN_OBJECT, NAME, MalformedJsonException.class); assertDocument("{'name'", BEGIN_OBJECT, NAME, EOFException.class); assertDocument("{'name',", BEGIN_OBJECT, NAME, MalformedJsonException.class); assertDocument("{name", BEGIN_OBJECT, NAME, EOFException.class); assertDocument("[", BEGIN_ARRAY, EOFException.class); assertDocument("[string", BEGIN_ARRAY, STRING, EOFException.class); assertDocument("[\"string\"", BEGIN_ARRAY, STRING, EOFException.class); assertDocument("['string'", BEGIN_ARRAY, STRING, EOFException.class); assertDocument("[123", BEGIN_ARRAY, NUMBER, EOFException.class); assertDocument("[123,", BEGIN_ARRAY, NUMBER, EOFException.class); assertDocument("{\"name\":123", BEGIN_OBJECT, NAME, NUMBER, EOFException.class); assertDocument("{\"name\":123,", BEGIN_OBJECT, NAME, NUMBER, EOFException.class); assertDocument("{\"name\":\"string\"", BEGIN_OBJECT, NAME, STRING, EOFException.class); assertDocument("{\"name\":\"string\",", BEGIN_OBJECT, NAME, STRING, EOFException.class); assertDocument("{\"name\":'string'", BEGIN_OBJECT, NAME, STRING, EOFException.class); assertDocument("{\"name\":'string',", BEGIN_OBJECT, NAME, STRING, EOFException.class); assertDocument("{\"name\":false", BEGIN_OBJECT, NAME, BOOLEAN, EOFException.class); assertDocument("{\"name\":false,,", BEGIN_OBJECT, NAME, BOOLEAN, MalformedJsonException.class); } /** * This test behaves slightly differently in Gson 2.2 and earlier. It fails during peek rather * than during nextString(). */ @Test public void testUnterminatedStringFailure() throws IOException { JsonReader reader = new JsonReader(reader("[\"string")); reader.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.peek()).isEqualTo(JsonToken.STRING); var e = assertThrows(MalformedJsonException.class, () -> reader.nextString()); assertThat(e) .hasMessageThat() .isEqualTo( "Unterminated string at line 1 column 9 path $[0]\n" + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); } /** Regression test for an issue with buffer filling and consumeNonExecutePrefix. */ @Test 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.setStrictness(Strictness.LENIENT); JsonToken token = reader.peek(); assertThat(token).isEqualTo(JsonToken.NUMBER); } private static void assertStrictError(MalformedJsonException exception, String expectedLocation) { assertThat(exception) .hasMessageThat() .isEqualTo( "Use JsonReader.setStrictness(Strictness.LENIENT) to accept malformed JSON at " + expectedLocation + "\n" + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); } private static void assertUnexpectedStructureError( IllegalStateException exception, String expectedToken, String actualToken, String expectedLocation) { String troubleshootingId = actualToken.equals("NULL") ? "adapter-not-null-safe" : "unexpected-json-structure"; assertThat(exception) .hasMessageThat() .isEqualTo( "Expected " + expectedToken + " but was " + actualToken + " at " + expectedLocation + "\nSee https://github.com/google/gson/blob/main/Troubleshooting.md#" + troubleshootingId); } private static void assertDocument(String document, Object... expectations) throws IOException { JsonReader reader = new JsonReader(reader(document)); reader.setStrictness(Strictness.LENIENT); 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) { assertThat(reader.nextName()).isEqualTo("name"); } else if (expectation == BOOLEAN) { assertThat(reader.nextBoolean()).isFalse(); } else if (expectation == STRING) { assertThat(reader.nextString()).isEqualTo("string"); } else if (expectation == NUMBER) { assertThat(reader.nextInt()).isEqualTo(123); } else if (expectation == NULL) { reader.nextNull(); } else if (expectation instanceof Class && Exception.class.isAssignableFrom((Class) expectation)) { var expected = assertThrows(Exception.class, () -> reader.peek()); assertThat(expected.getClass()).isEqualTo((Class) expectation); } else { throw new AssertionError("Unsupported expectation value: " + expectation); } } } /** Returns a reader that returns one character at a time. */ private static Reader reader(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 { } }; */ } } ================================================ FILE: gson/src/test/java/com/google/gson/stream/JsonWriterTest.java ================================================ /* * 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 static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import com.google.gson.FormattingStyle; import com.google.gson.Strictness; import com.google.gson.internal.LazilyParsedNumber; import java.io.IOException; import java.io.StringWriter; import java.math.BigDecimal; import java.math.BigInteger; import org.junit.Test; @SuppressWarnings("resource") public final class JsonWriterTest { @Test public void testDefaultStrictness() throws IOException { JsonWriter jsonWriter = new JsonWriter(new StringWriter()); assertThat(jsonWriter.getStrictness()).isEqualTo(Strictness.LEGACY_STRICT); jsonWriter.value(false); jsonWriter.close(); } @SuppressWarnings("deprecation") // for JsonWriter.setLenient @Test public void testSetLenientTrue() throws IOException { JsonWriter jsonWriter = new JsonWriter(new StringWriter()); jsonWriter.setLenient(true); assertThat(jsonWriter.getStrictness()).isEqualTo(Strictness.LENIENT); jsonWriter.value(false); jsonWriter.close(); } @SuppressWarnings("deprecation") // for JsonWriter.setLenient @Test public void testSetLenientFalse() throws IOException { JsonWriter jsonWriter = new JsonWriter(new StringWriter()); jsonWriter.setLenient(false); assertThat(jsonWriter.getStrictness()).isEqualTo(Strictness.LEGACY_STRICT); jsonWriter.value(false); jsonWriter.close(); } @Test public void testSetStrictness() throws IOException { JsonWriter jsonWriter = new JsonWriter(new StringWriter()); jsonWriter.setStrictness(Strictness.STRICT); assertThat(jsonWriter.getStrictness()).isEqualTo(Strictness.STRICT); jsonWriter.value(false); jsonWriter.close(); } @Test public void testSetStrictnessNull() throws IOException { JsonWriter jsonWriter = new JsonWriter(new StringWriter()); assertThrows(NullPointerException.class, () -> jsonWriter.setStrictness(null)); jsonWriter.value(false); jsonWriter.close(); } @Test public void testTopLevelValueTypes() throws IOException { StringWriter string1 = new StringWriter(); JsonWriter writer1 = new JsonWriter(string1); writer1.value(true); writer1.close(); assertThat(string1.toString()).isEqualTo("true"); StringWriter string2 = new StringWriter(); JsonWriter writer2 = new JsonWriter(string2); writer2.nullValue(); writer2.close(); assertThat(string2.toString()).isEqualTo("null"); StringWriter string3 = new StringWriter(); JsonWriter writer3 = new JsonWriter(string3); writer3.value(123); writer3.close(); assertThat(string3.toString()).isEqualTo("123"); StringWriter string4 = new StringWriter(); JsonWriter writer4 = new JsonWriter(string4); writer4.value(123.4); writer4.close(); assertThat(string4.toString()).isEqualTo("123.4"); StringWriter string5 = new StringWriter(); JsonWriter writert = new JsonWriter(string5); writert.value("a"); writert.close(); assertThat(string5.toString()).isEqualTo("\"a\""); } @Test public void testNameAsTopLevelValue() throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(stringWriter); IllegalStateException e = assertThrows(IllegalStateException.class, () -> jsonWriter.name("hello")); assertThat(e).hasMessageThat().isEqualTo("Please begin an object before writing a name."); jsonWriter.value(12); jsonWriter.close(); e = assertThrows(IllegalStateException.class, () -> jsonWriter.name("hello")); assertThat(e).hasMessageThat().isEqualTo("JsonWriter is closed."); } @Test public void testNameInArray() throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(stringWriter); jsonWriter.beginArray(); IllegalStateException e = assertThrows(IllegalStateException.class, () -> jsonWriter.name("hello")); assertThat(e).hasMessageThat().isEqualTo("Please begin an object before writing a name."); jsonWriter.value(12); e = assertThrows(IllegalStateException.class, () -> jsonWriter.name("hello")); assertThat(e).hasMessageThat().isEqualTo("Please begin an object before writing a name."); jsonWriter.endArray(); jsonWriter.close(); assertThat(stringWriter.toString()).isEqualTo("[12]"); } @Test public void testTwoNames() throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(stringWriter); jsonWriter.beginObject(); jsonWriter.name("a"); var e = assertThrows(IllegalStateException.class, () -> jsonWriter.name("a")); assertThat(e).hasMessageThat().isEqualTo("Already wrote a name, expecting a value."); } @Test public void testNameWithoutValue() throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(stringWriter); jsonWriter.beginObject(); jsonWriter.name("a"); var e = assertThrows(IllegalStateException.class, () -> jsonWriter.endObject()); assertThat(e).hasMessageThat().isEqualTo("Dangling name: a"); } @Test public void testValueWithoutName() throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(stringWriter); jsonWriter.beginObject(); var e = assertThrows(IllegalStateException.class, () -> jsonWriter.value(true)); assertThat(e).hasMessageThat().isEqualTo("Nesting problem."); } @Test public void testMultipleTopLevelValues() throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(stringWriter); jsonWriter.beginArray().endArray(); IllegalStateException expected = assertThrows(IllegalStateException.class, jsonWriter::beginArray); assertThat(expected).hasMessageThat().isEqualTo("JSON must have only one top-level value."); } @Test public void testMultipleTopLevelValuesStrict() throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(stringWriter); jsonWriter.setStrictness(Strictness.STRICT); jsonWriter.beginArray().endArray(); IllegalStateException expected = assertThrows(IllegalStateException.class, jsonWriter::beginArray); assertThat(expected).hasMessageThat().isEqualTo("JSON must have only one top-level value."); } @Test public void testMultipleTopLevelValuesLenient() throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter writer = new JsonWriter(stringWriter); writer.setStrictness(Strictness.LENIENT); writer.beginArray(); writer.endArray(); writer.beginArray(); writer.endArray(); writer.close(); assertThat(stringWriter.toString()).isEqualTo("[][]"); } @Test public void testBadNestingObject() throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(stringWriter); jsonWriter.beginArray(); jsonWriter.beginObject(); var e = assertThrows(IllegalStateException.class, () -> jsonWriter.endArray()); assertThat(e).hasMessageThat().isEqualTo("Nesting problem."); } @Test public void testBadNestingArray() throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(stringWriter); jsonWriter.beginArray(); jsonWriter.beginArray(); var e = assertThrows(IllegalStateException.class, () -> jsonWriter.endObject()); assertThat(e).hasMessageThat().isEqualTo("Nesting problem."); } @Test public void testNullName() throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(stringWriter); jsonWriter.beginObject(); assertThrows(NullPointerException.class, () -> jsonWriter.name(null)); } @Test 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(); assertThat(stringWriter.toString()).isEqualTo("{\"a\":null}"); } @Test 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(); assertThat(stringWriter.toString()).isEqualTo("{\"a\":{\"b\":true},\"c\":1}"); } private static void assertNonFiniteFloatsExceptions(JsonWriter jsonWriter) throws IOException { jsonWriter.beginArray(); IllegalArgumentException expected = assertThrows(IllegalArgumentException.class, () -> jsonWriter.value(Float.NaN)); assertThat(expected).hasMessageThat().isEqualTo("Numeric values must be finite, but was NaN"); expected = assertThrows( IllegalArgumentException.class, () -> jsonWriter.value(Float.NEGATIVE_INFINITY)); assertThat(expected) .hasMessageThat() .isEqualTo("Numeric values must be finite, but was -Infinity"); expected = assertThrows( IllegalArgumentException.class, () -> jsonWriter.value(Float.POSITIVE_INFINITY)); assertThat(expected) .hasMessageThat() .isEqualTo("Numeric values must be finite, but was Infinity"); } @Test public void testNonFiniteFloats() throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(stringWriter); assertNonFiniteFloatsExceptions(jsonWriter); } @Test public void testNonFiniteFloatsWhenStrict() throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(stringWriter); jsonWriter.setStrictness(Strictness.STRICT); assertNonFiniteFloatsExceptions(jsonWriter); } private static void assertNonFiniteDoublesExceptions(JsonWriter jsonWriter) throws IOException { jsonWriter.beginArray(); IllegalArgumentException expected = assertThrows(IllegalArgumentException.class, () -> jsonWriter.value(Double.NaN)); assertThat(expected).hasMessageThat().isEqualTo("Numeric values must be finite, but was NaN"); expected = assertThrows( IllegalArgumentException.class, () -> jsonWriter.value(Double.NEGATIVE_INFINITY)); assertThat(expected) .hasMessageThat() .isEqualTo("Numeric values must be finite, but was -Infinity"); expected = assertThrows( IllegalArgumentException.class, () -> jsonWriter.value(Double.POSITIVE_INFINITY)); assertThat(expected) .hasMessageThat() .isEqualTo("Numeric values must be finite, but was Infinity"); } @Test public void testNonFiniteDoubles() throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(stringWriter); assertNonFiniteDoublesExceptions(jsonWriter); } @Test public void testNonFiniteDoublesWhenStrict() throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(stringWriter); jsonWriter.setStrictness(Strictness.STRICT); assertNonFiniteDoublesExceptions(jsonWriter); } private static void assertNonFiniteNumbersExceptions(JsonWriter jsonWriter) throws IOException { jsonWriter.beginArray(); IllegalArgumentException expected = assertThrows( IllegalArgumentException.class, () -> jsonWriter.value(Double.valueOf(Double.NaN))); assertThat(expected).hasMessageThat().isEqualTo("Numeric values must be finite, but was NaN"); expected = assertThrows( IllegalArgumentException.class, () -> jsonWriter.value(Double.valueOf(Double.NEGATIVE_INFINITY))); assertThat(expected) .hasMessageThat() .isEqualTo("Numeric values must be finite, but was -Infinity"); expected = assertThrows( IllegalArgumentException.class, () -> jsonWriter.value(Double.valueOf(Double.POSITIVE_INFINITY))); assertThat(expected) .hasMessageThat() .isEqualTo("Numeric values must be finite, but was Infinity"); expected = assertThrows( IllegalArgumentException.class, () -> jsonWriter.value(new LazilyParsedNumber("Infinity"))); assertThat(expected) .hasMessageThat() .isEqualTo("Numeric values must be finite, but was Infinity"); } @Test public void testNonFiniteNumbers() throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(stringWriter); assertNonFiniteNumbersExceptions(jsonWriter); } @Test public void testNonFiniteNumbersWhenStrict() throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(stringWriter); jsonWriter.setStrictness(Strictness.STRICT); assertNonFiniteNumbersExceptions(jsonWriter); } @Test public void testNonFiniteFloatsWhenLenient() throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(stringWriter); jsonWriter.setStrictness(Strictness.LENIENT); jsonWriter.beginArray(); jsonWriter.value(Float.NaN); jsonWriter.value(Float.NEGATIVE_INFINITY); jsonWriter.value(Float.POSITIVE_INFINITY); jsonWriter.endArray(); assertThat(stringWriter.toString()).isEqualTo("[NaN,-Infinity,Infinity]"); } @Test public void testNonFiniteDoublesWhenLenient() throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(stringWriter); jsonWriter.setStrictness(Strictness.LENIENT); jsonWriter.beginArray(); jsonWriter.value(Double.NaN); jsonWriter.value(Double.NEGATIVE_INFINITY); jsonWriter.value(Double.POSITIVE_INFINITY); jsonWriter.endArray(); assertThat(stringWriter.toString()).isEqualTo("[NaN,-Infinity,Infinity]"); } @Test public void testNonFiniteNumbersWhenLenient() throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(stringWriter); jsonWriter.setStrictness(Strictness.LENIENT); 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(); assertThat(stringWriter.toString()).isEqualTo("[NaN,-Infinity,Infinity,Infinity]"); } @Test 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(); assertThat(stringWriter.toString()) .isEqualTo( "[-0.0," + "1.0," + "3.4028235E38," + "1.4E-45," + "0.0," + "-0.5," + "2.2250739E-38," + "3.723379," + "3.1415927," + "2.7182817]"); } @Test 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(); assertThat(stringWriter.toString()) .isEqualTo( "[-0.0," + "1.0," + "1.7976931348623157E308," + "4.9E-324," + "0.0," + "-0.5," + "2.2250738585072014E-308," + "3.141592653589793," + "2.718281828459045]"); } @Test 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(); assertThat(stringWriter.toString()) .isEqualTo("[0," + "1," + "-1," + "-9223372036854775808," + "9223372036854775807]"); } @Test 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(); assertThat(stringWriter.toString()) .isEqualTo( "[0," + "9223372036854775808," + "-9223372036854775809," + "3.141592653589793238462643383]"); } /** Tests writing {@code Number} instances which are not one of the standard JDK ones. */ @Test 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(); assertThat(stringWriter.toString()).isEqualTo(validNumber); } } @Test 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()); var e = assertThrows( IllegalArgumentException.class, () -> jsonWriter.value(new LazilyParsedNumber(malformedNumber))); assertThat(e) .hasMessageThat() .isEqualTo( "String created by class com.google.gson.internal.LazilyParsedNumber is not a valid" + " JSON number: " + malformedNumber); } } @Test public void testBooleans() throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(stringWriter); jsonWriter.beginArray(); jsonWriter.value(true); jsonWriter.value(false); jsonWriter.endArray(); assertThat(stringWriter.toString()).isEqualTo("[true,false]"); } @Test 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(); assertThat(stringWriter.toString()).isEqualTo("[true,false,null]"); } @Test public void testNulls() throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(stringWriter); jsonWriter.beginArray(); jsonWriter.nullValue(); jsonWriter.endArray(); assertThat(stringWriter.toString()).isEqualTo("[null]"); } @Test 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(); assertThat(stringWriter.toString()) .isEqualTo( "[\"a\"," + "\"a\\\"\"," + "\"\\\"\"," + "\":\"," + "\",\"," + "\"\\b\"," + "\"\\f\"," + "\"\\n\"," + "\"\\r\"," + "\"\\t\"," + "\" \"," + "\"\\\\\"," + "\"{\"," + "\"}\"," + "\"[\"," + "\"]\"," + "\"\\u0000\"," + "\"\\u0019\"]"); } @Test public void testUnicodeLineBreaksEscaped() throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(stringWriter); jsonWriter.beginArray(); jsonWriter.value("\u2028 \u2029"); jsonWriter.endArray(); // JSON specification does not require that they are escaped, but Gson escapes them for // compatibility with JavaScript where they are considered line breaks assertThat(stringWriter.toString()).isEqualTo("[\"\\u2028 \\u2029\"]"); } @Test public void testEmptyArray() throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(stringWriter); jsonWriter.beginArray(); jsonWriter.endArray(); assertThat(stringWriter.toString()).isEqualTo("[]"); } @Test public void testEmptyObject() throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(stringWriter); jsonWriter.beginObject(); jsonWriter.endObject(); assertThat(stringWriter.toString()).isEqualTo("{}"); } @Test 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(); assertThat(stringWriter.toString()) .isEqualTo("[{\"a\":5,\"b\":false}," + "{\"c\":6,\"d\":true}]"); } @Test 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(); assertThat(stringWriter.toString()).isEqualTo("{\"a\":[5,false]," + "\"b\":[6,true]}"); } @Test 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(); } assertThat(stringWriter.toString()).isEqualTo("[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]"); } @Test 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(); assertThat(stringWriter.toString()) .isEqualTo( "{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":" + "{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{" + "}}}}}}}}}}}}}}}}}}}}}"); } @Test 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 assertThat(stringWriter.toString()).isEqualTo("{\"a\":true,\"a\":false}"); } @Test 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" + "}"; assertThat(stringWriter.toString()).isEqualTo(expected); } @Test 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" + "]"; assertThat(stringWriter.toString()).isEqualTo(expected); } @Test public void testClosedWriterThrowsOnStructure() throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter writer = new JsonWriter(stringWriter); writer.beginArray(); writer.endArray(); writer.close(); String expectedMessage = "JsonWriter is closed."; var e = assertThrows(IllegalStateException.class, () -> writer.beginArray()); assertThat(e).hasMessageThat().isEqualTo(expectedMessage); e = assertThrows(IllegalStateException.class, () -> writer.endArray()); assertThat(e).hasMessageThat().isEqualTo(expectedMessage); e = assertThrows(IllegalStateException.class, () -> writer.beginObject()); assertThat(e).hasMessageThat().isEqualTo(expectedMessage); e = assertThrows(IllegalStateException.class, () -> writer.endObject()); assertThat(e).hasMessageThat().isEqualTo(expectedMessage); } @Test public void testClosedWriterThrowsOnName() throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter writer = new JsonWriter(stringWriter); writer.beginArray(); writer.endArray(); writer.close(); var e = assertThrows(IllegalStateException.class, () -> writer.name("a")); assertThat(e).hasMessageThat().isEqualTo("JsonWriter is closed."); } @Test public void testClosedWriterThrowsOnValue() throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter writer = new JsonWriter(stringWriter); writer.beginArray(); writer.endArray(); writer.close(); var e = assertThrows(IllegalStateException.class, () -> writer.value("a")); assertThat(e).hasMessageThat().isEqualTo("JsonWriter is closed."); } @Test public void testClosedWriterThrowsOnFlush() throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter writer = new JsonWriter(stringWriter); writer.beginArray(); writer.endArray(); writer.close(); var e = assertThrows(IllegalStateException.class, () -> writer.flush()); assertThat(e).hasMessageThat().isEqualTo("JsonWriter is closed."); } @Test public void testWriterCloseIsIdempotent() throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter writer = new JsonWriter(stringWriter); writer.beginArray(); writer.endArray(); writer.close(); assertThat(stringWriter.toString()).isEqualTo("[]"); writer.close(); assertThat(stringWriter.toString()).isEqualTo("[]"); } @Test public void testSetGetFormattingStyle() throws IOException { String lineSeparator = "\r\n"; StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(stringWriter); // Default should be FormattingStyle.COMPACT assertThat(jsonWriter.getFormattingStyle()).isSameInstanceAs(FormattingStyle.COMPACT); jsonWriter.setFormattingStyle( FormattingStyle.PRETTY.withIndent(" \t ").withNewline(lineSeparator)); jsonWriter.beginArray(); jsonWriter.value(true); jsonWriter.value("text"); jsonWriter.value(5.0); jsonWriter.nullValue(); jsonWriter.endArray(); String expected = "[\r\n" // + " \t true,\r\n" // + " \t \"text\",\r\n" // + " \t 5.0,\r\n" // + " \t null\r\n" // + "]"; assertThat(stringWriter.toString()).isEqualTo(expected); assertThat(jsonWriter.getFormattingStyle().getNewline()).isEqualTo(lineSeparator); } @Test public void testIndentOverwritesFormattingStyle() throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(stringWriter); jsonWriter.setFormattingStyle(FormattingStyle.COMPACT); // Should overwrite formatting style jsonWriter.setIndent(" "); jsonWriter.beginObject(); jsonWriter.name("a"); jsonWriter.beginArray(); jsonWriter.value(1); jsonWriter.value(2); jsonWriter.endArray(); jsonWriter.endObject(); String expected = "{\n" // + " \"a\": [\n" // + " 1,\n" // + " 2\n" // + " ]\n" // + "}"; assertThat(stringWriter.toString()).isEqualTo(expected); } } ================================================ FILE: gson/src/test/resources/testcases-proguard.conf ================================================ # 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*(); public void setUp(); } -dontwarn com.google.gson.functional.EnumWithObfuscatedTest -dontwarn junit.framework.TestCase # Ignore notes about duplicate JDK classes -dontnote module-info,jdk.internal.** ================================================ FILE: metrics/README.md ================================================ # metrics This Maven module contains the source code for running internal benchmark tests against Gson. ================================================ FILE: metrics/pom.xml ================================================ 4.0.0 com.google.code.gson gson-parent 2.13.3-SNAPSHOT gson-metrics 2011 Gson Metrics Performance Metrics for Google Gson library true Apache-2.0 https://www.apache.org/licenses/LICENSE-2.0.txt Google, Inc. https://www.google.com com.google.code.gson gson ${project.parent.version} com.fasterxml.jackson.core jackson-databind 2.21.0 com.google.caliper caliper 1.0-beta-3 Inderjeet Singh Google Inc. Joel Leitch Google Inc. Jesse Wilson Google Inc. ================================================ FILE: metrics/src/main/java/com/google/gson/metrics/BagOfPrimitives.java ================================================ /* * 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.common.base.Objects; /** * 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() { return "{" + "\"longValue\":" + longValue + "," + "\"intValue\":" + intValue + "," + "\"booleanValue\":" + booleanValue + "," + "\"stringValue\":\"" + stringValue + "\"" + "}"; } @Override public int hashCode() { 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 o) { if (this == o) { return true; } if (!(o instanceof BagOfPrimitives)) { return false; } BagOfPrimitives that = (BagOfPrimitives) o; return longValue == that.longValue && intValue == that.intValue && booleanValue == that.booleanValue && Objects.equal(stringValue, that.stringValue); } @Override public String toString() { return String.format( "(longValue=%d,intValue=%d,booleanValue=%b,stringValue=%s)", longValue, intValue, booleanValue, stringValue); } } ================================================ FILE: metrics/src/main/java/com/google/gson/metrics/BagOfPrimitivesDeserializationBenchmark.java ================================================ /* * 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) { BagOfPrimitives unused = 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(); switch (name) { case "longValue": longValue = jr.nextLong(); break; case "intValue": intValue = jr.nextInt(); break; case "booleanValue": booleanValue = jr.nextBoolean(); break; case "stringValue": stringValue = jr.nextString(); break; default: 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(); } } } ================================================ FILE: metrics/src/main/java/com/google/gson/metrics/CollectionsDeserializationBenchmark.java ================================================ /* * 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 TypeToken> LIST_TYPE_TOKEN = new TypeToken>() {}; private static final Type LIST_TYPE = LIST_TYPE_TOKEN.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 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) { List unused = gson.fromJson(json, LIST_TYPE_TOKEN); } } /** Benchmark to measure deserializing objects by hand */ @SuppressWarnings("ModifiedButNotUsed") 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 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(); switch (name) { case "longValue": longValue = jr.nextLong(); break; case "intValue": intValue = jr.nextInt(); break; case "booleanValue": booleanValue = jr.nextBoolean(); break; case "stringValue": stringValue = jr.nextString(); break; default: 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)} . */ @SuppressWarnings("ModifiedButNotUsed") 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 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(); } } } ================================================ FILE: metrics/src/main/java/com/google/gson/metrics/NonUploadingCaliperRunner.java ================================================ /* * 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.metrics; import com.google.caliper.runner.CaliperMain; class NonUploadingCaliperRunner { private 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)); } } ================================================ FILE: metrics/src/main/java/com/google/gson/metrics/ParseBenchmark.java ================================================ /* * 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.JsonElement; import com.google.gson.JsonParser; import com.google.gson.annotations.SerializedName; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; 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.net.URL; import java.nio.charset.StandardCharsets; 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. * *

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>() {}, new TypeReference>() {}), READER_SHORT(new TypeToken() {}, new TypeReference() {}), READER_LONG(new TypeToken() {}, new TypeReference() {}); @SuppressWarnings("ImmutableEnumChecker") private final TypeToken gsonType; @SuppressWarnings("ImmutableEnumChecker") private final TypeReference jacksonType; private Document(TypeToken typeToken, TypeReference typeReference) { this.gsonType = typeToken; 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 { try (ZipFile zipFile = new ZipFile(getResourceFile("/ParseBenchmarkData.zip"))) { ZipEntry zipEntry = zipFile.getEntry(fileName); Reader reader = new InputStreamReader(zipFile.getInputStream(zipEntry), StandardCharsets.UTF_8); 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(); } } 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 { JsonReader jsonReader = new JsonReader(new CharArrayReader(data)); readToken(jsonReader); jsonReader.close(); } private static void readToken(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: String unusedName = reader.nextName(); break; case BOOLEAN: boolean unusedBoolean = reader.nextBoolean(); break; case NULL: reader.nextNull(); break; case NUMBER: long unusedLong = reader.nextLong(); break; case STRING: String unusedString = reader.nextString(); break; case END_DOCUMENT: return; } } } } private static class GsonSkipParser implements Parser { @Override public void parse(char[] data, Document document) throws Exception { JsonReader jsonReader = new 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.currentName(); 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 { JsonElement unused = JsonParser.parseReader(new CharArrayReader(data)); } } private static class GsonBindParser implements Parser { private static final Gson gson = new GsonBuilder().setDateFormat("EEE MMM dd HH:mm:ss Z yyyy").create(); @Override public void parse(char[] data, Document document) throws Exception { Object unused = 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); } } @SuppressWarnings("MemberName") 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; } @SuppressWarnings("MemberName") 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 default_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 alternates; @JsonProperty long updated; @JsonProperty List 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 categories; @JsonProperty String title; @JsonProperty long published; @JsonProperty long updated; @JsonProperty("alternate") @SerializedName("alternate") List alternates; @JsonProperty Content content; @JsonProperty String author; @JsonProperty List 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; } } } ================================================ FILE: metrics/src/main/java/com/google/gson/metrics/SerializationBenchmark.java ================================================ /* * 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) { String unused = gson.toJson(bag); } } } ================================================ FILE: pom.xml ================================================ 4.0.0 com.google.code.gson gson-parent 2.13.3-SNAPSHOT pom Gson Parent Gson JSON library https://github.com/google/gson gson test-jpms test-graal-native-image test-shrinker extras metrics proto UTF-8 8 11 2025-09-10T20:39:14Z false https://github.com/google/gson/ scm:git:https://github.com/google/gson.git scm:git:git@github.com:google/gson.git HEAD google Google https://www.google.com GitHub Issues https://github.com/google/gson/issues Apache-2.0 https://www.apache.org/licenses/LICENSE-2.0.txt junit junit 4.13.2 com.google.truth truth 1.4.5 org.apache.maven.plugins maven-enforcer-plugin 3.6.2 enforce-versions enforce [3.3.1,) [17,22) com.diffplug.spotless spotless-maven-plugin 3.2.1 check *.md *.xml .github/**/*.yml .gitignore true 2 true true true org.apache.maven.plugins maven-artifact-plugin 3.6.1 buildinfo org.sonatype.central central-publishing-maven-plugin false org.apache.maven.plugins maven-compiler-plugin 3.15.0 true true true -XDcompilePolicy=simple -XDaddTypeAnnotationsToSymbol=true --should-stop=ifError=FLOW -Xplugin:ErrorProne -XepExcludedPaths:.*/generated-test-sources/protobuf/.* -Xep:NotJavadoc:OFF -XepAllSuggestionsAsWarnings -Xep:AnnotationPosition -Xep:AssertFalse -Xep:ClassName -Xep:ClassNamedLikeTypeParameter:WARN -Xep:ComparisonContractViolated -Xep:ConstantField:WARN -Xep:DepAnn -Xep:DifferentNameButSame -Xep:EmptyIf -Xep:EqualsBrokenForNull -Xep:ForEachIterable:WARN -Xep:FunctionalInterfaceClash -Xep:InitializeInline -Xep:InterfaceWithOnlyStatics -Xep:LambdaFunctionalInterface:WARN -Xep:LongLiteralLowerCaseSuffix -Xep:MemberName -Xep:MissingBraces:WARN -Xep:MissingDefault -Xep:MixedArrayDimensions:WARN -Xep:MultiVariableDeclaration:WARN -Xep:MultipleTopLevelClasses:WARN -Xep:NonCanonicalStaticMemberImport -Xep:NonFinalStaticField -Xep:PackageLocation:WARN -Xep:PatternMatchingInstanceof:OFF -Xep:PrimitiveArrayPassedToVarargsMethod -Xep:PrivateConstructorForUtilityClass:WARN -Xep:RemoveUnusedImports:WARN -Xep:StatementSwitchToExpressionSwitch:OFF -Xep:StaticQualifiedUsingExpression -Xep:StringConcatToTextBlock:OFF -Xep:SwitchDefault:WARN -Xep:SystemExitOutsideMain -Xep:SystemOut -Xep:TestExceptionChecker -Xep:ThrowSpecificExceptions:OFF -Xep:TryFailRefactoring:OFF -Xep:TypeParameterNaming:WARN -Xep:UnescapedEntity -Xep:UngroupedOverloads:WARN -Xep:UnnecessarilyFullyQualified -Xep:UnnecessarilyUsedValue -Xep:UnnecessaryBoxedVariable:WARN -Xep:UnnecessaryDefaultInEnumSwitch -Xep:UnnecessaryFinal -Xep:UnnecessaryStaticImport:WARN -Xep:UnusedException -Xep:UrlInSee -Xep:UseCorrectAssertInTests -Xep:UseEnumSwitch:WARN -Xep:WildcardImport:WARN -Xep:YodaCondition -Xlint:all,-options com.google.errorprone error_prone_core 2.47.0 org.apache.maven.plugins maven-javadoc-plugin 3.12.0 ${gson.isTestModule} 11 all,-missing false https://docs.oracle.com/en/java/javase/11/docs/api/ https://errorprone.info/api/latest/ false true true org.apache.maven.plugins maven-surefire-plugin 3.5.4 org.apache.maven.plugins maven-failsafe-plugin 3.5.4 org.apache.maven.plugins maven-jar-plugin 3.5.0 org.apache.maven.plugins maven-install-plugin 3.1.4 ${gson.isTestModule} org.apache.maven.plugins maven-source-plugin 3.4.0 ${gson.isTestModule} org.apache.maven.plugins maven-gpg-plugin 3.2.8 ${gson.isTestModule} org.apache.maven.plugins maven-deploy-plugin 3.1.4 true org.sonatype.central central-publishing-maven-plugin 0.10.0 true central org.apache.maven.plugins maven-release-plugin 3.3.1 true false release clean verify antrun:run@replace-version-placeholders antrun:run@replace-old-version-references antrun:run@git-add-changed org.apache.maven.plugins maven-antrun-plugin 3.2.0 replace-version-placeholders run replace-old-version-references run false git-add-changed run com.github.siom79.japicmp japicmp-maven-plugin 0.25.4 ${gson.isTestModule} ${project.groupId} ${project.artifactId} 0.0.0-JAPICMP-OLD true true com.google.gson.internal true true true org.codehaus.mojo animal-sniffer-maven-plugin 1.27 check-android-compatibility check ${gson.isTestModule} net.sf.androidscents.signature android-api-level-23 6.0_r3 com.google.gson.internal.bind.IgnoreJRERequirement disable-spotless [,17) com.diffplug.spotless spotless-maven-plugin default none disable-error-prone [,21) org.apache.maven.plugins maven-compiler-plugin -Xlint:all,-options release org.apache.maven.plugins maven-source-plugin attach-sources jar-no-fork org.apache.maven.plugins maven-javadoc-plugin attach-javadocs jar org.apache.maven.plugins maven-gpg-plugin sign-artifacts verify sign ================================================ FILE: proto/.gitignore ================================================ src/main/java/com/google/gson/protobuf/generated/ ================================================ FILE: proto/README.md ================================================ # 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. ================================================ FILE: proto/pom.xml ================================================ 4.0.0 com.google.code.gson gson-parent 2.13.3-SNAPSHOT proto Gson Protobuf Support Gson support for Protobufs 2025-09-10T20:39:14Z 4.33.5 Apache-2.0 https://www.apache.org/licenses/LICENSE-2.0.txt com.google.code.gson gson ${project.parent.version} com.google.protobuf protobuf-java ${protobufVersion} com.google.guava guava 33.5.0-jre junit junit test com.google.truth truth test gson-proto io.github.ascopes protobuf-maven-plugin 4.1.3 ${maven.test.skip} ${protobufVersion} true false generate-test Inderjeet Singh Google Inc. ================================================ FILE: proto/src/main/java/com/google/gson/protobuf/ProtoTypeAdapter.java ================================================ /* * 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 java.util.Objects.requireNonNull; import com.google.common.base.CaseFormat; import com.google.common.collect.MapMaker; import com.google.common.reflect.TypeToken; import com.google.errorprone.annotations.CanIgnoreReturnValue; 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.Method; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; 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. * *

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)}. * *

An example of default serialization/deserialization using custom proto field names is shown * below: * *

 * message MyMessage {
 *   // Will be serialized as 'osBuildID' instead of the default 'osBuildId'.
 *   string os_build_id = 1 [(serialized_name) = "osBuildID"];
 * }
 * 
* * @author Inderjeet Singh * @author Emmanuel Cron * @author Stanley Wang */ public class ProtoTypeAdapter implements JsonSerializer, JsonDeserializer { /** Determines how enum values should be serialized. */ public enum EnumSerialization { /** * Serializes and deserializes enum values using their number. When this is used, custom * value names set on enums are ignored. */ NUMBER, /** Serializes and deserializes enum values using their name. */ NAME; } /** Builder for {@link ProtoTypeAdapter}s. */ public static class Builder { private final Set> serializedNameExtensions; private final Set> serializedEnumValueExtensions; private EnumSerialization enumSerialization; private CaseFormat protoFormat; private CaseFormat jsonFormat; private boolean shouldUseJsonNameFieldOption; private Builder( EnumSerialization enumSerialization, CaseFormat fromFieldNameFormat, CaseFormat toFieldNameFormat) { this.serializedNameExtensions = new HashSet<>(); this.serializedEnumValueExtensions = new HashSet<>(); setEnumSerialization(enumSerialization); setFieldNameSerializationFormat(fromFieldNameFormat, toFieldNameFormat); this.shouldUseJsonNameFieldOption = false; } @CanIgnoreReturnValue public Builder setEnumSerialization(EnumSerialization enumSerialization) { this.enumSerialization = requireNonNull(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. * *

For example, if you use the following parameters: {@link CaseFormat#LOWER_UNDERSCORE}, * {@link CaseFormat#LOWER_CAMEL}, the following conversion will occur: * *

{@code
     * PROTO     <->  JSON
     * my_field       myField
     * foo            foo
     * n__id_ct       nIdCt
     * }
*/ @CanIgnoreReturnValue 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: * *
     * string client_app_id = 1 [(serialized_name) = "appId"];
     * 
* * ...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. */ @CanIgnoreReturnValue public Builder addSerializedNameExtension( Extension serializedNameExtension) { serializedNameExtensions.add(requireNonNull(serializedNameExtension)); return this; } /** * Adds an enum value proto annotation that, when set, overrides the default enum 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: * *
     * enum MyEnum {
     *   UNKNOWN = 0;
     *   CLIENT_APP_ID = 1 [(serialized_value) = "APP_ID"];
     *   TWO = 2 [(serialized_value) = "2"];
     * }
     * 
* * ...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. * *

Note that you need to set the enum serialization of this adapter to {@link * EnumSerialization#NAME}, otherwise these annotations will be ignored. */ @CanIgnoreReturnValue public Builder addSerializedEnumValueExtension( Extension serializedEnumValueExtension) { serializedEnumValueExtensions.add(requireNonNull(serializedEnumValueExtension)); return this; } /** * Sets or unsets a flag (default false) that, when set, causes the adapter to use the {@code * json_name} field option from a proto field for serialization. Unlike other field options that * can be defined as annotations on a proto field, {@code json_name} cannot be accessed via a * proto field's {@link FieldDescriptor#getOptions} and registered via {@link * ProtoTypeAdapter.Builder#addSerializedNameExtension}. * *

This flag is subordinate to any custom serialized name extensions added to this adapter. * In other words, serialized name extensions take precedence over this setting. For example, a * field defined like: * *

     * string client_app_id = 1 [json_name = "foo", (serialized_name) = "bar"];
     * 
* * ...will be serialized as '{@code bar}' if {@code shouldUseJsonNameFieldOption} is set to * {@code true} and the '{@code serialized_name}' annotation is added to the adapter. * * @since 2.12.0 */ @CanIgnoreReturnValue public Builder setShouldUseJsonNameFieldOption(boolean shouldUseJsonNameFieldOption) { this.shouldUseJsonNameFieldOption = shouldUseJsonNameFieldOption; return this; } public ProtoTypeAdapter build() { return new ProtoTypeAdapter( enumSerialization, protoFormat, jsonFormat, serializedNameExtensions, serializedEnumValueExtensions, shouldUseJsonNameFieldOption); } } /** * 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 FieldDescriptor.Type ENUM_TYPE = FieldDescriptor.Type.ENUM; private static final ConcurrentMap, Method>> mapOfMapOfMethods = new MapMaker().makeMap(); private final EnumSerialization enumSerialization; private final CaseFormat protoFormat; private final CaseFormat jsonFormat; private final Set> serializedNameExtensions; private final Set> serializedEnumValueExtensions; private final boolean shouldUseJsonNameFieldOption; private ProtoTypeAdapter( EnumSerialization enumSerialization, CaseFormat protoFormat, CaseFormat jsonFormat, Set> serializedNameExtensions, Set> serializedEnumValueExtensions, boolean shouldUseJsonNameFieldOption) { this.enumSerialization = enumSerialization; this.protoFormat = protoFormat; this.jsonFormat = jsonFormat; this.serializedNameExtensions = serializedNameExtensions; this.serializedEnumValueExtensions = serializedEnumValueExtensions; this.shouldUseJsonNameFieldOption = shouldUseJsonNameFieldOption; } @Override public JsonElement serialize(Message src, Type typeOfSrc, JsonSerializationContext context) { JsonObject ret = new JsonObject(); Map fields = src.getAllFields(); for (Map.Entry fieldPair : fields.entrySet()) { FieldDescriptor desc = fieldPair.getKey(); String name = getCustSerializedName(desc); 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 enumDescs = (Collection) 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 protoClass = (Class) typeOfT; if (DynamicMessage.class.isAssignableFrom(protoClass)) { throw new IllegalStateException("only generated messages are supported"); } // 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); 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 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); @SuppressWarnings("unchecked") TypeToken> protoArrayFieldType = (TypeToken>) TypeToken.of(protoArrayField.getGenericType()); // Get the type as `List`, otherwise type might be Protobuf internal interface for // which no instance can be created Type protoArrayResolvedFieldType = protoArrayFieldType.getSupertype(List.class).getType(); fieldValue = context.deserialize(jsonElement, protoArrayResolvedFieldType); protoBuilder.setField(fieldDescriptor, fieldValue); } else { Object field = defaultInstance.getField(fieldDescriptor); fieldValue = context.deserialize(jsonElement, field.getClass()); protoBuilder.setField(fieldDescriptor, fieldValue); } } } return protoBuilder.build(); } catch (Exception e) { throw new JsonParseException("Error while parsing proto", e); } } /** * Retrieves the custom field name for a given FieldDescriptor via its field options, falling back * to its name as a default. */ private String getCustSerializedName(FieldDescriptor fieldDescriptor) { FieldOptions options = fieldDescriptor.getOptions(); for (Extension extension : serializedNameExtensions) { if (options.hasExtension(extension)) { return options.getExtension(extension); } } if (shouldUseJsonNameFieldOption && fieldDescriptor.toProto().hasJsonName()) { return fieldDescriptor.getJsonName(); } return protoFormat.to(jsonFormat, fieldDescriptor.getName()); } /** * 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 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, Method> mapOfMethods = mapOfMapOfMethods.get(methodName); if (mapOfMethods == null) { mapOfMethods = new MapMaker().makeMap(); ConcurrentMap, 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; } } ================================================ FILE: proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithAnnotationsAndJsonNamesTest.java ================================================ /* * Copyright (C) 2024 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 com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.protobuf.ProtoTypeAdapter; import com.google.gson.protobuf.generated.Annotations; import com.google.gson.protobuf.generated.Bag.ProtoWithAnnotationsAndJsonNames; import com.google.protobuf.GeneratedMessage; import java.util.Map; import org.junit.Test; /** * Functional tests for protocol buffers using annotations and custom json_name values for field * names. * * @author Andrew Szeto */ public class ProtosWithAnnotationsAndJsonNamesTest { private static final Gson GSON_PLAIN = new GsonBuilder() .registerTypeHierarchyAdapter( GeneratedMessage.class, ProtoTypeAdapter.newBuilder().build()) .create(); private static final Gson GSON_WITH_SERIALIZED_NAME = new GsonBuilder() .registerTypeHierarchyAdapter( GeneratedMessage.class, ProtoTypeAdapter.newBuilder() .addSerializedNameExtension(Annotations.serializedName) .setShouldUseJsonNameFieldOption(false) .build()) .create(); private static final Gson GSON_WITH_JSON_NAME = new GsonBuilder() .registerTypeHierarchyAdapter( GeneratedMessage.class, ProtoTypeAdapter.newBuilder().setShouldUseJsonNameFieldOption(true).build()) .create(); private static final Gson GSON_WITH_SERIALIZED_NAME_AND_JSON_NAME = new GsonBuilder() .registerTypeHierarchyAdapter( GeneratedMessage.class, ProtoTypeAdapter.newBuilder() .addSerializedNameExtension(Annotations.serializedName) .setShouldUseJsonNameFieldOption(true) .build()) .create(); private static final Map JSON_OUTPUTS = Map.of( GSON_PLAIN, "{\"neither\":\"xxx\",\"jsonNameOnly\":\"yyy\",\"annotationOnly\":\"zzz\",\"both\":\"www\"}", GSON_WITH_JSON_NAME, "{\"neither\":\"xxx\",\"aaa\":\"yyy\",\"annotationOnly\":\"zzz\",\"ccc\":\"www\"}", GSON_WITH_SERIALIZED_NAME, "{\"neither\":\"xxx\",\"jsonNameOnly\":\"yyy\",\"bbb\":\"zzz\",\"ddd\":\"www\"}", GSON_WITH_SERIALIZED_NAME_AND_JSON_NAME, "{\"neither\":\"xxx\",\"aaa\":\"yyy\",\"bbb\":\"zzz\",\"ddd\":\"www\"}"); private static final ProtoWithAnnotationsAndJsonNames PROTO = ProtoWithAnnotationsAndJsonNames.newBuilder() .setNeither("xxx") .setJsonNameOnly("yyy") .setAnnotationOnly("zzz") .setBoth("www") .build(); @Test public void testProtoWithAnnotationsAndJsonNames_basicConversions() { JSON_OUTPUTS.forEach( (gson, json) -> { assertThat(gson.fromJson(json, ProtoWithAnnotationsAndJsonNames.class)).isEqualTo(PROTO); assertThat(gson.toJson(PROTO)).isEqualTo(json); }); } @Test public void testProtoWithAnnotationsAndJsonNames_basicRoundTrips() { JSON_OUTPUTS.forEach( (gson, json) -> { assertThat(roundTrip(gson, gson, json)).isEqualTo(json); assertThat(roundTrip(gson, gson, PROTO)).isEqualTo(PROTO); }); } @Test public void testProtoWithAnnotationsAndJsonNames_unannotatedField() { ProtoWithAnnotationsAndJsonNames proto = ProtoWithAnnotationsAndJsonNames.newBuilder().setNeither("zzz").build(); String json = "{\"neither\":\"zzz\"}"; for (Gson gson1 : JSON_OUTPUTS.keySet()) { for (Gson gson2 : JSON_OUTPUTS.keySet()) { // all configs should match with each other in how they serialize this proto, and they // should be able to deserialize any other config's serialization of the proto back to its // original form assertThat(gson1.toJson(proto)).isEqualTo(gson2.toJson(proto)); assertThat(roundTrip(gson1, gson2, proto)).isEqualTo(proto); // the same, but in the other direction assertThat(gson1.fromJson(json, ProtoWithAnnotationsAndJsonNames.class)) .isEqualTo(gson2.fromJson(json, ProtoWithAnnotationsAndJsonNames.class)); assertThat(roundTrip(gson1, gson2, json)).isEqualTo(json); } } } @Test public void testProtoWithAnnotationsAndJsonNames_fieldWithJsonName() { ProtoWithAnnotationsAndJsonNames proto = ProtoWithAnnotationsAndJsonNames.newBuilder().setJsonNameOnly("zzz").build(); String jsonWithoutJsonName = "{\"jsonNameOnly\":\"zzz\"}"; String jsonWithJsonName = "{\"aaa\":\"zzz\"}"; // the ProtoTypeAdapter that checks for the custom annotation should default to the basic name assertThat(GSON_PLAIN.toJson(proto)).isEqualTo(jsonWithoutJsonName); assertThat(GSON_WITH_SERIALIZED_NAME.toJson(proto)).isEqualTo(GSON_PLAIN.toJson(proto)); // the ProtoTypeAdapter that respects the `json_name` option should not have the same output as // the base case assertThat(GSON_WITH_JSON_NAME.toJson(proto)).isNotEqualTo(GSON_PLAIN.toJson(proto)); // both ProtoTypeAdapters that set shouldUseJsonNameFieldOption to true should match in output assertThat(GSON_WITH_JSON_NAME.toJson(proto)).isEqualTo(jsonWithJsonName); assertThat(GSON_WITH_JSON_NAME.toJson(proto)) .isEqualTo(GSON_WITH_SERIALIZED_NAME_AND_JSON_NAME.toJson(proto)); // should fail to round-trip if we serialize via the `json_name` and deserialize without it or // vice versa assertThat(roundTrip(GSON_PLAIN, GSON_WITH_JSON_NAME, proto)).isNotEqualTo(proto); assertThat(roundTrip(GSON_WITH_JSON_NAME, GSON_PLAIN, proto)).isNotEqualTo(proto); } @Test public void testProtoWithAnnotationsAndJsonNames_fieldWithCustomSerializedName() { ProtoWithAnnotationsAndJsonNames proto = ProtoWithAnnotationsAndJsonNames.newBuilder().setAnnotationOnly("zzz").build(); String jsonWithoutCustomName = "{\"annotationOnly\":\"zzz\"}"; String jsonWithCustomName = "{\"bbb\":\"zzz\"}"; // the ProtoTypeAdapter that checks for the json name should default to the basic name assertThat(GSON_PLAIN.toJson(proto)).isEqualTo(jsonWithoutCustomName); assertThat(GSON_WITH_JSON_NAME.toJson(proto)).isEqualTo(GSON_PLAIN.toJson(proto)); // the ProtoTypeAdapter that checks for the custom serialized name should not have the same // output as the base case assertThat(GSON_WITH_SERIALIZED_NAME.toJson(proto)).isNotEqualTo(GSON_PLAIN.toJson(proto)); // both ProtoTypeAdapters that check for the custom serialized name should match in output assertThat(GSON_WITH_SERIALIZED_NAME.toJson(proto)).isEqualTo(jsonWithCustomName); assertThat(GSON_WITH_SERIALIZED_NAME.toJson(proto)) .isEqualTo(GSON_WITH_SERIALIZED_NAME_AND_JSON_NAME.toJson(proto)); // should fail to round-trip if we serialize via the custom name and deserialize without it or // vice versa assertThat(roundTrip(GSON_PLAIN, GSON_WITH_SERIALIZED_NAME, proto)).isNotEqualTo(proto); assertThat(roundTrip(GSON_WITH_SERIALIZED_NAME, GSON_PLAIN, proto)).isNotEqualTo(proto); } @Test public void testProtoWithAnnotationsAndJsonNames_fieldWithJsonNameAndCustomSerializedName() { ProtoWithAnnotationsAndJsonNames proto = ProtoWithAnnotationsAndJsonNames.newBuilder().setBoth("zzz").build(); String jsonPlain = "{\"both\":\"zzz\"}"; String jsonWithJsonName = "{\"ccc\":\"zzz\"}"; String jsonWithCustomName = "{\"ddd\":\"zzz\"}"; // the three different configs serialize to three different values assertThat(GSON_PLAIN.toJson(proto)).isEqualTo(jsonPlain); assertThat(GSON_WITH_JSON_NAME.toJson(proto)).isEqualTo(jsonWithJsonName); assertThat(GSON_WITH_SERIALIZED_NAME.toJson(proto)).isEqualTo(jsonWithCustomName); // the case where both configs are enabled will prefer the custom annotation assertThat(GSON_WITH_SERIALIZED_NAME_AND_JSON_NAME.toJson(proto)) .isEqualTo(GSON_WITH_SERIALIZED_NAME.toJson(proto)); } private static String roundTrip(Gson jsonToProto, Gson protoToJson, String json) { return protoToJson.toJson(jsonToProto.fromJson(json, ProtoWithAnnotationsAndJsonNames.class)); } private static ProtoWithAnnotationsAndJsonNames roundTrip( Gson protoToJson, Gson jsonToProto, ProtoWithAnnotationsAndJsonNames proto) { return jsonToProto.fromJson(protoToJson.toJson(proto), ProtoWithAnnotationsAndJsonNames.class); } } ================================================ FILE: proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithAnnotationsTest.java ================================================ /* * 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 org.junit.Assert.assertThrows; 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.protobuf.GeneratedMessage; import org.junit.Before; import org.junit.Test; /** * Functional tests for protocol buffers using annotations for field names and enum values. * * @author Emmanuel Cron */ public class ProtosWithAnnotationsTest { private Gson gson; private Gson gsonWithEnumNumbers; private Gson gsonWithLowerHyphen; @Before public void setUp() throws Exception { ProtoTypeAdapter.Builder protoTypeAdapter = ProtoTypeAdapter.newBuilder() .setEnumSerialization(EnumSerialization.NAME) .addSerializedNameExtension(Annotations.serializedName) .addSerializedEnumValueExtension(Annotations.serializedValue); gson = new GsonBuilder() .registerTypeHierarchyAdapter(GeneratedMessage.class, protoTypeAdapter.build()) .create(); gsonWithEnumNumbers = new GsonBuilder() .registerTypeHierarchyAdapter( GeneratedMessage.class, protoTypeAdapter.setEnumSerialization(EnumSerialization.NUMBER).build()) .create(); gsonWithLowerHyphen = new GsonBuilder() .registerTypeHierarchyAdapter( GeneratedMessage.class, protoTypeAdapter .setFieldNameSerializationFormat( CaseFormat.LOWER_UNDERSCORE, CaseFormat.LOWER_HYPHEN) .build()) .create(); } @Test 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(InnerMessage.Type.TEXT) .addData( InnerMessage.Data.newBuilder() .setData("OFIN8e9fhwoeh8((⁹8efywoih") .setHeight(665)) .addData(InnerMessage.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" + "}]}}"); } @Test public void testProtoWithAnnotations_deserializeUnknownEnumValue() { String json = String.format("{ %n" + " \"content\":\"UNKNOWN\"%n" + "}"); InnerMessage proto = gson.fromJson(json, InnerMessage.class); assertThat(proto.getContent()).isEqualTo(InnerMessage.Type.UNKNOWN); } @Test public void testProtoWithAnnotations_deserializeUnrecognizedEnumValue() { String json = String.format("{ %n" + " \"content\":\"UNRECOGNIZED\"%n" + "}"); var e = assertThrows(JsonParseException.class, () -> gson.fromJson(json, InnerMessage.class)); assertThat(e).hasMessageThat().isEqualTo("Error while parsing proto"); assertThat(e).hasCauseThat().hasMessageThat().isEqualTo("Unrecognized enum name: UNRECOGNIZED"); } @Test public void testProtoWithAnnotations_deserializeWithEnumNumbers() { String json = String.format("{ %n" + " \"content\":\"0\"%n" + "}"); InnerMessage proto = gsonWithEnumNumbers.fromJson(json, InnerMessage.class); assertThat(proto.getContent()).isEqualTo(InnerMessage.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(InnerMessage.Type.IMAGE); rebuilt = gsonWithEnumNumbers.toJson(proto); assertThat(rebuilt).isEqualTo("{\"content\":2}"); } @Test public void testProtoWithAnnotations_deserializeUnrecognizedEnumNumber() { String json = String.format("{ %n" + " \"content\":\"99\"%n" + "}"); var e = assertThrows( JsonParseException.class, () -> gsonWithEnumNumbers.fromJson(json, InnerMessage.class)); assertThat(e).hasMessageThat().isEqualTo("Error while parsing proto"); assertThat(e).hasCauseThat().hasMessageThat().isEqualTo("Unrecognized enum value: 99"); } @Test 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(InnerMessage.Type.IMAGE) .addData(InnerMessage.Data.newBuilder().setData("data$$").setWidth(200)) .addData(InnerMessage.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); } } ================================================ FILE: proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithComplexAndRepeatedFieldsTest.java ================================================ /* * 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 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.GeneratedMessage; import org.junit.Before; import org.junit.Test; /** * Functional tests for protocol buffers using complex and repeated fields * * @author Inderjeet Singh */ public class ProtosWithComplexAndRepeatedFieldsTest { private Gson gson; private Gson upperCamelGson; @Before public void setUp() throws Exception { gson = new GsonBuilder() .registerTypeHierarchyAdapter( GeneratedMessage.class, ProtoTypeAdapter.newBuilder() .setEnumSerialization(EnumSerialization.NUMBER) .build()) .create(); upperCamelGson = new GsonBuilder() .registerTypeHierarchyAdapter( GeneratedMessage.class, ProtoTypeAdapter.newBuilder() .setFieldNameSerializationFormat( CaseFormat.LOWER_UNDERSCORE, CaseFormat.UPPER_CAMEL) .build()) .create(); } @Test 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); assertThat(json).isEqualTo("{\"numbers\":[2,3],\"simples\":[{\"msg\":\"foo\"},{\"count\":3}]}"); } @Test public void testDeserializeRepeatedFieldsProto() { String json = "{numbers:[4,6],simples:[{msg:'bar'},{count:7}]}"; ProtoWithRepeatedFields proto = gson.fromJson(json, ProtoWithRepeatedFields.class); assertThat(proto.getNumbers(0)).isEqualTo(4); assertThat(proto.getNumbers(1)).isEqualTo(6); assertThat(proto.getSimples(0).getMsg()).isEqualTo("bar"); assertThat(proto.getSimples(1).getCount()).isEqualTo(7); } @Test public void testSerializeDifferentCaseFormat() { ProtoWithDifferentCaseFormat proto = ProtoWithDifferentCaseFormat.newBuilder() .setAnotherField("foo") .addNameThatTestsCaseFormat("bar") .build(); JsonObject json = upperCamelGson.toJsonTree(proto).getAsJsonObject(); assertThat(json.get("AnotherField").getAsString()).isEqualTo("foo"); assertThat(json.get("NameThatTestsCaseFormat").getAsJsonArray().get(0).getAsString()) .isEqualTo("bar"); } @Test public void testDeserializeDifferentCaseFormat() { String json = "{NameThatTestsCaseFormat:['bar'],AnotherField:'foo'}"; ProtoWithDifferentCaseFormat proto = upperCamelGson.fromJson(json, ProtoWithDifferentCaseFormat.class); assertThat(proto.getAnotherField()).isEqualTo("foo"); assertThat(proto.getNameThatTestsCaseFormat(0)).isEqualTo("bar"); } } ================================================ FILE: proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithPrimitiveTypesTest.java ================================================ /* * 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 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.GeneratedMessage; import org.junit.Before; import org.junit.Test; public class ProtosWithPrimitiveTypesTest { private Gson gson; @Before public void setUp() throws Exception { gson = new GsonBuilder() .registerTypeHierarchyAdapter( GeneratedMessage.class, ProtoTypeAdapter.newBuilder() .setEnumSerialization(EnumSerialization.NUMBER) .build()) .create(); } @Test public void testSerializeEmptyProto() { SimpleProto proto = SimpleProto.newBuilder().build(); String json = gson.toJson(proto); assertThat(json).isEqualTo("{}"); } @Test public void testDeserializeEmptyProto() { SimpleProto proto = gson.fromJson("{}", SimpleProto.class); assertThat(proto.hasCount()).isFalse(); assertThat(proto.hasMsg()).isFalse(); } @Test public void testSerializeProto() { SimpleProto proto = SimpleProto.newBuilder().setCount(3).setMsg("foo").build(); String json = gson.toJson(proto); assertThat(json).isEqualTo("{\"msg\":\"foo\",\"count\":3}"); } @Test public void testDeserializeProto() { SimpleProto proto = gson.fromJson("{msg:'foo',count:3}", SimpleProto.class); assertThat(proto.getMsg()).isEqualTo("foo"); assertThat(proto.getCount()).isEqualTo(3); } @Test public void testDeserializeWithExplicitNullValue() { SimpleProto proto = gson.fromJson("{msg:'foo',count:null}", SimpleProto.class); assertThat(proto.getMsg()).isEqualTo("foo"); assertThat(proto.getCount()).isEqualTo(0); } } ================================================ FILE: proto/src/test/protobuf/annotations.proto ================================================ // // 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; } ================================================ FILE: proto/src/test/protobuf/bag.proto ================================================ // // 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; } message ProtoWithAnnotationsAndJsonNames { optional string neither = 1; optional string json_name_only = 2 [json_name = "aaa"]; optional string annotation_only = 3 [(serialized_name) = "bbb"]; optional string both = 4 [json_name = "ccc", (serialized_name) = "ddd"]; } ================================================ FILE: test-graal-native-image/README.md ================================================ # test-graal-native-image This Maven module contains integration tests for using Gson in a GraalVM Native Image. Execution requires using GraalVM as JDK, and can be quite resource intensive. Native Image tests are therefore not enabled by default and the tests are only executed as regular unit tests. To run Native Image tests, make sure your `PATH` and `JAVA_HOME` environment variables point to GraalVM and then run: ``` mvn clean test --activate-profiles native-image-test ``` Technically it would also be possible to directly configure Native Image test execution for the `gson` module instead of having this separate Maven module. However, maintaining the reflection metadata for the unit tests would be quite cumbersome and would hinder future changes to the `gson` unit tests because many of them just happen to use reflection, without all of them being relevant for Native Image testing. ## Reflection metadata Native Image creation requires configuring which class members are accessed using reflection, see the [GraalVM documentation](https://www.graalvm.org/jdk21/reference-manual/native-image/metadata/#specifying-reflection-metadata-in-json). The file [`reflect-config.json`](./src/test/resources/META-INF/native-image/reflect-config.json) contains this reflection metadata. You can also run with `-Dagent=true` to let the Maven plugin automatically generate a metadata file, see the [plugin documentation](https://graalvm.github.io/native-build-tools/latest/maven-plugin.html#agent-support-running-tests). ================================================ FILE: test-graal-native-image/pom.xml ================================================ 4.0.0 com.google.code.gson gson-parent 2.13.3-SNAPSHOT test-graal-native-image Test: GraalVM Native Image 11 **/Java17* true org.junit junit-bom 6.0.3 pom import com.google.code.gson gson ${project.parent.version} org.junit.jupiter junit-jupiter test org.junit.platform junit-platform-launcher test com.google.truth truth test org.apache.maven.plugins maven-jar-plugin true org.apache.maven.plugins maven-compiler-plugin default-testCompile test-compile testCompile ${excludeTestCompilation} JDK17 [17,) 17 native-image-test false org.graalvm.buildtools native-maven-plugin 0.11.4 true test-native test true -H:+ReportExceptionStackTraces --initialize-at-build-time=org.junit.jupiter.engine.discovery.MethodSegmentResolver ================================================ FILE: test-graal-native-image/src/test/java/com/google/gson/native_test/Java17RecordReflectionTest.java ================================================ /* * Copyright (C) 2023 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.native_test; import static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; import org.junit.jupiter.api.Test; class Java17RecordReflectionTest { public record PublicRecord(int i) {} @Test void testPublicRecord() { Gson gson = new Gson(); PublicRecord r = gson.fromJson("{\"i\":1}", PublicRecord.class); assertThat(r.i).isEqualTo(1); } // Private record has implicit private canonical constructor private record PrivateRecord(int i) {} @Test void testPrivateRecord() { Gson gson = new Gson(); PrivateRecord r = gson.fromJson("{\"i\":1}", PrivateRecord.class); assertThat(r.i).isEqualTo(1); } @Test void testLocalRecord() { record LocalRecordDeserialization(int i) {} Gson gson = new Gson(); LocalRecordDeserialization r = gson.fromJson("{\"i\":1}", LocalRecordDeserialization.class); assertThat(r.i).isEqualTo(1); } @Test void testLocalRecordSerialization() { record LocalRecordSerialization(int i) {} Gson gson = new Gson(); assertThat(gson.toJson(new LocalRecordSerialization(1))).isEqualTo("{\"i\":1}"); } private record RecordWithSerializedName(@SerializedName("custom-name") int i) {} @Test void testSerializedName() { Gson gson = new Gson(); RecordWithSerializedName r = gson.fromJson("{\"custom-name\":1}", RecordWithSerializedName.class); assertThat(r.i).isEqualTo(1); assertThat(gson.toJson(new RecordWithSerializedName(2))).isEqualTo("{\"custom-name\":2}"); } private record RecordWithCustomConstructor(int i) { @SuppressWarnings("unused") RecordWithCustomConstructor { i += 5; } } @Test void testCustomConstructor() { Gson gson = new Gson(); RecordWithCustomConstructor r = gson.fromJson("{\"i\":1}", RecordWithCustomConstructor.class); assertThat(r.i).isEqualTo(6); } private record RecordWithCustomAccessor(int i) { @SuppressWarnings("UnusedMethod") @Override public int i() { return i + 5; } } @Test void testCustomAccessor() { Gson gson = new Gson(); assertThat(gson.toJson(new RecordWithCustomAccessor(2))).isEqualTo("{\"i\":7}"); } @JsonAdapter(RecordWithCustomClassAdapter.CustomAdapter.class) private record RecordWithCustomClassAdapter(int i) { private static class CustomAdapter extends TypeAdapter { @Override public RecordWithCustomClassAdapter read(JsonReader in) throws IOException { return new RecordWithCustomClassAdapter(in.nextInt() + 5); } @Override public void write(JsonWriter out, RecordWithCustomClassAdapter value) throws IOException { out.value(value.i + 6); } } } @Test void testCustomClassAdapter() { Gson gson = new Gson(); RecordWithCustomClassAdapter r = gson.fromJson("1", RecordWithCustomClassAdapter.class); assertThat(r.i).isEqualTo(6); assertThat(gson.toJson(new RecordWithCustomClassAdapter(1))).isEqualTo("7"); } private record RecordWithCustomFieldAdapter( @JsonAdapter(RecordWithCustomFieldAdapter.CustomAdapter.class) int i) { private static class CustomAdapter extends TypeAdapter { @Override public Integer read(JsonReader in) throws IOException { return in.nextInt() + 5; } @Override public void write(JsonWriter out, Integer value) throws IOException { out.value(value + 6); } } } @Test void testCustomFieldAdapter() { Gson gson = new Gson(); RecordWithCustomFieldAdapter r = gson.fromJson("{\"i\":1}", RecordWithCustomFieldAdapter.class); assertThat(r.i).isEqualTo(6); assertThat(gson.toJson(new RecordWithCustomFieldAdapter(1))).isEqualTo("{\"i\":7}"); } private record RecordWithRegisteredAdapter(int i) {} @Test void testCustomAdapter() { Gson gson = new GsonBuilder() .registerTypeAdapter( RecordWithRegisteredAdapter.class, new TypeAdapter() { @Override public RecordWithRegisteredAdapter read(JsonReader in) throws IOException { return new RecordWithRegisteredAdapter(in.nextInt() + 5); } @Override public void write(JsonWriter out, RecordWithRegisteredAdapter value) throws IOException { out.value(value.i + 6); } }) .create(); RecordWithRegisteredAdapter r = gson.fromJson("1", RecordWithRegisteredAdapter.class); assertThat(r.i).isEqualTo(6); assertThat(gson.toJson(new RecordWithRegisteredAdapter(1))).isEqualTo("7"); } } ================================================ FILE: test-graal-native-image/src/test/java/com/google/gson/native_test/ReflectionTest.java ================================================ /* * Copyright (C) 2023 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.native_test; import static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.InstanceCreator; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; 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.List; import org.junit.jupiter.api.Test; class ReflectionTest { private static class ClassWithDefaultConstructor { private int i; } @Test void testDefaultConstructor() { Gson gson = new Gson(); ClassWithDefaultConstructor c = gson.fromJson("{\"i\":1}", ClassWithDefaultConstructor.class); assertThat(c.i).isEqualTo(1); } private static class ClassWithCustomDefaultConstructor { private int i; private ClassWithCustomDefaultConstructor() { i = 1; } } @Test void testCustomDefaultConstructor() { Gson gson = new Gson(); ClassWithCustomDefaultConstructor c = gson.fromJson("{\"i\":2}", ClassWithCustomDefaultConstructor.class); assertThat(c.i).isEqualTo(2); c = gson.fromJson("{}", ClassWithCustomDefaultConstructor.class); assertThat(c.i).isEqualTo(1); } private static class ClassWithoutDefaultConstructor { private int i = -1; // Explicit constructor with args to remove implicit no-args default constructor private ClassWithoutDefaultConstructor(int i) { this.i = i; } } /** * Tests deserializing a class without default constructor. * *

This should use JDK Unsafe, and would normally require specifying {@code "unsafeAllocated": * true} in the reflection metadata for GraalVM, though for some reason it also seems to work * without it? Possibly because GraalVM seems to have special support for Gson, see its class * {@code com.oracle.svm.thirdparty.gson.GsonFeature}. */ @Test void testClassWithoutDefaultConstructor() { Gson gson = new Gson(); ClassWithoutDefaultConstructor c = gson.fromJson("{\"i\":1}", ClassWithoutDefaultConstructor.class); assertThat(c.i).isEqualTo(1); c = gson.fromJson("{}", ClassWithoutDefaultConstructor.class); // Class is instantiated with JDK Unsafe, therefore field keeps its default value instead of // assigned -1 assertThat(c.i).isEqualTo(0); } @Test void testInstanceCreator() { Gson gson = new GsonBuilder() .registerTypeAdapter( ClassWithoutDefaultConstructor.class, new InstanceCreator() { @Override public ClassWithoutDefaultConstructor createInstance(Type type) { return new ClassWithoutDefaultConstructor(-2); } }) .create(); ClassWithoutDefaultConstructor c = gson.fromJson("{\"i\":1}", ClassWithoutDefaultConstructor.class); assertThat(c.i).isEqualTo(1); c = gson.fromJson("{}", ClassWithoutDefaultConstructor.class); // Uses default value specified by InstanceCreator assertThat(c.i).isEqualTo(-2); } private static class ClassWithFinalField { // Initialize with value which is not inlined by compiler private final int i = nonConstant(); private static int nonConstant() { return "a".length(); // = 1 } } @Test void testFinalField() { Gson gson = new Gson(); ClassWithFinalField c = gson.fromJson("{\"i\":2}", ClassWithFinalField.class); assertThat(c.i).isEqualTo(2); c = gson.fromJson("{}", ClassWithFinalField.class); assertThat(c.i).isEqualTo(1); } private static class ClassWithSerializedName { @SerializedName("custom-name") private int i; } @Test void testSerializedName() { Gson gson = new Gson(); ClassWithSerializedName c = gson.fromJson("{\"custom-name\":1}", ClassWithSerializedName.class); assertThat(c.i).isEqualTo(1); c = new ClassWithSerializedName(); c.i = 2; assertThat(gson.toJson(c)).isEqualTo("{\"custom-name\":2}"); } @JsonAdapter(ClassWithCustomClassAdapter.CustomAdapter.class) private static class ClassWithCustomClassAdapter { private static class CustomAdapter extends TypeAdapter { @Override public ClassWithCustomClassAdapter read(JsonReader in) throws IOException { return new ClassWithCustomClassAdapter(in.nextInt() + 5); } @Override public void write(JsonWriter out, ClassWithCustomClassAdapter value) throws IOException { out.value(value.i + 6); } } private int i; private ClassWithCustomClassAdapter(int i) { this.i = i; } } @Test void testCustomClassAdapter() { Gson gson = new Gson(); ClassWithCustomClassAdapter c = gson.fromJson("1", ClassWithCustomClassAdapter.class); assertThat(c.i).isEqualTo(6); assertThat(gson.toJson(new ClassWithCustomClassAdapter(1))).isEqualTo("7"); } private static class ClassWithCustomFieldAdapter { private static class CustomAdapter extends TypeAdapter { @Override public Integer read(JsonReader in) throws IOException { return in.nextInt() + 5; } @Override public void write(JsonWriter out, Integer value) throws IOException { out.value(value + 6); } } @JsonAdapter(ClassWithCustomFieldAdapter.CustomAdapter.class) private int i; private ClassWithCustomFieldAdapter(int i) { this.i = i; } private ClassWithCustomFieldAdapter() { this(-1); } } @Test void testCustomFieldAdapter() { Gson gson = new Gson(); ClassWithCustomFieldAdapter c = gson.fromJson("{\"i\":1}", ClassWithCustomFieldAdapter.class); assertThat(c.i).isEqualTo(6); assertThat(gson.toJson(new ClassWithCustomFieldAdapter(1))).isEqualTo("{\"i\":7}"); } private static class ClassWithRegisteredAdapter { private int i; private ClassWithRegisteredAdapter(int i) { this.i = i; } } @Test void testCustomAdapter() { Gson gson = new GsonBuilder() .registerTypeAdapter( ClassWithRegisteredAdapter.class, new TypeAdapter() { @Override public ClassWithRegisteredAdapter read(JsonReader in) throws IOException { return new ClassWithRegisteredAdapter(in.nextInt() + 5); } @Override public void write(JsonWriter out, ClassWithRegisteredAdapter value) throws IOException { out.value(value.i + 6); } }) .create(); ClassWithRegisteredAdapter c = gson.fromJson("1", ClassWithRegisteredAdapter.class); assertThat(c.i).isEqualTo(6); assertThat(gson.toJson(new ClassWithRegisteredAdapter(1))).isEqualTo("7"); } @Test void testGenerics() { Gson gson = new Gson(); List list = gson.fromJson("[{\"i\":1}]", new TypeToken>() {}); assertThat(list).hasSize(1); assertThat(list.get(0).i).isEqualTo(1); @SuppressWarnings("unchecked") List list2 = (List) gson.fromJson( "[{\"i\":1}]", TypeToken.getParameterized(List.class, ClassWithDefaultConstructor.class)); assertThat(list2).hasSize(1); assertThat(list2.get(0).i).isEqualTo(1); } } ================================================ FILE: test-graal-native-image/src/test/resources/META-INF/native-image/reflect-config.json ================================================ [ { "name":"com.google.gson.native_test.ReflectionTest$ClassWithDefaultConstructor", "allDeclaredFields":true, "allDeclaredConstructors": true }, { "name":"com.google.gson.native_test.ReflectionTest$ClassWithCustomDefaultConstructor", "allDeclaredFields":true, "allDeclaredConstructors": true }, { "name":"com.google.gson.native_test.ReflectionTest$ClassWithoutDefaultConstructor", "allDeclaredFields":true, "allDeclaredConstructors": true }, { "name":"com.google.gson.native_test.ReflectionTest$ClassWithFinalField", "allDeclaredFields":true, "allDeclaredConstructors": true }, { "name":"com.google.gson.native_test.ReflectionTest$ClassWithSerializedName", "allDeclaredFields":true, "allDeclaredConstructors": true }, { "name":"com.google.gson.native_test.ReflectionTest$ClassWithCustomFieldAdapter", "allDeclaredFields":true, "allDeclaredConstructors": true }, { "name":"com.google.gson.native_test.ReflectionTest$ClassWithCustomClassAdapter$CustomAdapter", "allDeclaredConstructors": true }, { "name":"com.google.gson.native_test.ReflectionTest$ClassWithCustomFieldAdapter$CustomAdapter", "allDeclaredConstructors": true }, { "name":"com.google.gson.native_test.Java17RecordReflectionTest$PublicRecord", "allDeclaredFields":true, "allPublicMethods": true, "allDeclaredConstructors": true }, { "name":"com.google.gson.native_test.Java17RecordReflectionTest$PrivateRecord", "allDeclaredFields":true, "allPublicMethods": true, "allDeclaredConstructors": true }, { "name":"com.google.gson.native_test.Java17RecordReflectionTest$RecordWithSerializedName", "allDeclaredFields":true, "allPublicMethods": true, "allDeclaredConstructors": true }, { "name":"com.google.gson.native_test.Java17RecordReflectionTest$RecordWithCustomConstructor", "allDeclaredFields":true, "allPublicMethods": true, "allDeclaredConstructors": true }, { "name":"com.google.gson.native_test.Java17RecordReflectionTest$RecordWithCustomAccessor", "allDeclaredFields":true, "allPublicMethods": true, "allDeclaredConstructors": true }, { "name":"com.google.gson.native_test.Java17RecordReflectionTest$RecordWithCustomFieldAdapter", "allDeclaredFields":true, "allPublicMethods": true, "allDeclaredConstructors": true }, { "name":"com.google.gson.native_test.Java17RecordReflectionTest$1LocalRecordDeserialization", "allDeclaredFields":true, "allPublicMethods": true, "allDeclaredConstructors": true }, { "name":"com.google.gson.native_test.Java17RecordReflectionTest$1LocalRecordSerialization", "allDeclaredFields":true, "allPublicMethods": true, "allDeclaredConstructors": true }, { "name":"com.google.gson.native_test.Java17RecordReflectionTest$RecordWithCustomClassAdapter$CustomAdapter", "allDeclaredConstructors": true }, { "name":"com.google.gson.native_test.Java17RecordReflectionTest$RecordWithCustomFieldAdapter$CustomAdapter", "allDeclaredConstructors": true } ] ================================================ FILE: test-jpms/README.md ================================================ # test-jpms This Maven module contains tests to verify that Gson's `module-info.class` which is used by the Java Platform Module System (JPMS) works properly and can be used by other projects. The module declaration file `src/test/java/module-info.java` uses Gson's module. This is a separate Maven module to test Gson's final JAR instead of just the compiled classes. ================================================ FILE: test-jpms/pom.xml ================================================ 4.0.0 com.google.code.gson gson-parent 2.13.3-SNAPSHOT test-jpms Test: Java Platform Module System (JPMS) 11 ${maven.compiler.release} true com.google.code.gson gson ${project.parent.version} junit junit test com.google.truth truth test ================================================ FILE: test-jpms/src/main/java/module-info.java ================================================ /* * Copyright (C) 2024 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. */ /** * Dummy module to prevent Maven Compiler Plugin from failing if {@code module-info.java} exists * only in test sources: * *

* * Can't compile test sources when main sources are missing a module descriptor * *
*/ module com.google.gson.dummy {} ================================================ FILE: test-jpms/src/test/java/com/google/gson/jpms_test/ExportedPackagesTest.java ================================================ /* * Copyright (C) 2024 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.jpms_test; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import java.io.IOException; import java.io.StringReader; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InaccessibleObjectException; import java.lang.reflect.Modifier; import java.util.Arrays; import org.junit.Test; /** * Verifies that Gson's {@code module-info.class} properly 'exports' all its packages containing * public API. */ public class ExportedPackagesTest { /** Tests package {@code com.google.gson} */ @Test public void testMainPackage() { Gson gson = new Gson(); assertThat(gson.toJson(1)).isEqualTo("1"); } /** Tests package {@code com.google.gson.annotations} */ @Test public void testAnnotationsPackage() throws Exception { class Annotated { @SerializedName("custom-name") @SuppressWarnings("UnusedVariable") int i; } Field field = Annotated.class.getDeclaredField("i"); SerializedName annotation = field.getAnnotation(SerializedName.class); assertThat(annotation.value()).isEqualTo("custom-name"); } /** Tests package {@code com.google.gson.reflect} */ @Test public void testReflectPackage() { var typeToken = TypeToken.get(String.class); assertThat(typeToken.getRawType()).isEqualTo(String.class); } /** Tests package {@code com.google.gson.stream} */ @Test public void testStreamPackage() throws IOException { JsonReader jsonReader = new JsonReader(new StringReader("2")); assertThat(jsonReader.nextInt()).isEqualTo(2); } /** Verifies that Gson packages are only 'exported' but not 'opened' for reflection. */ @Test public void testReflectionInternalField() throws Exception { Gson gson = new Gson(); // Get an arbitrary non-public instance field Field field = Arrays.stream(Gson.class.getDeclaredFields()) .filter( f -> !Modifier.isStatic(f.getModifiers()) && !Modifier.isPublic(f.getModifiers())) .findFirst() .get(); assertThrows(InaccessibleObjectException.class, () -> field.setAccessible(true)); assertThrows(IllegalAccessException.class, () -> field.get(gson)); } @Test public void testInaccessiblePackage() throws Exception { // Note: In case this class is renamed / removed, can change this to any other internal class Class internalClass = Class.forName("com.google.gson.internal.LinkedTreeMap"); assertThat(Modifier.isPublic(internalClass.getModifiers())).isTrue(); // Get the public constructor Constructor constructor = internalClass.getConstructor(); assertThrows(InaccessibleObjectException.class, () -> constructor.setAccessible(true)); assertThrows(IllegalAccessException.class, () -> constructor.newInstance()); } } ================================================ FILE: test-jpms/src/test/java/com/google/gson/jpms_test/ModuleTest.java ================================================ /* * Copyright (C) 2024 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.jpms_test; import static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import java.lang.module.ModuleDescriptor; import java.lang.module.ModuleDescriptor.Exports; import java.lang.module.ModuleDescriptor.Requires; import java.net.URL; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.Test; /** * Verifies that this test project is properly set up and has a module descriptor, and checks Gson's * module descriptor. */ public class ModuleTest { @Test public void testOwnModule() { Module module = getClass().getModule(); assertThat(module.getName()).isEqualTo("com.google.gson.jpms_test"); } @Test public void testGsonModule() { // Verify that this test actually loads the final Gson JAR, and not only compiled classes // Note: This might fail when run from the IDE, but should succeed when run with Maven from // command line URL gsonLocation = Gson.class.getProtectionDomain().getCodeSource().getLocation(); assertThat(gsonLocation.getPath()).containsMatch("gson/target/gson-[^/]+\\.jar"); Module module = Gson.class.getModule(); ModuleDescriptor moduleDescriptor = module.getDescriptor(); assertThat(moduleDescriptor.name()).isEqualTo("com.google.gson"); // Permit `Modifier.SYNTHETIC`; current versions of Moditect seem to set that assertThat(moduleDescriptor.modifiers()) .containsNoneOf( ModuleDescriptor.Modifier.AUTOMATIC, ModuleDescriptor.Modifier.MANDATED, ModuleDescriptor.Modifier.OPEN); // Should have implicitly included the Maven project version assertThat(moduleDescriptor.rawVersion()).isPresent(); Set moduleRequires = moduleDescriptor.requires(); assertThat(getModuleDependencies(moduleRequires)) .containsExactly("com.google.errorprone.annotations", "java.sql", "jdk.unsupported"); assertThat(getTransitiveModuleDependencies(moduleRequires)).isEmpty(); assertThat(getOptionalModuleDependencies(moduleRequires)) .containsExactly("com.google.errorprone.annotations", "java.sql", "jdk.unsupported"); Set packageExports = moduleDescriptor.exports(); assertThat(packageExports.stream().map(Exports::source)) .containsExactly( "com.google.gson", "com.google.gson.annotations", "com.google.gson.reflect", "com.google.gson.stream"); // Gson currently does not export packages to specific modules only assertThat(packageExports.stream().filter(Exports::isQualified)).isEmpty(); // Gson does not allow access to its implementation details using reflection assertThat(moduleDescriptor.opens()).isEmpty(); // Gson currently does not use or provide any services assertThat(moduleDescriptor.uses()).isEmpty(); assertThat(moduleDescriptor.provides()).isEmpty(); // Gson has no main class assertThat(moduleDescriptor.mainClass()).isEmpty(); } private static Stream filterImplicitRequires(Set requires) { return requires.stream() .filter( r -> !r.modifiers().contains(Requires.Modifier.MANDATED) && !r.modifiers().contains(Requires.Modifier.SYNTHETIC)); } private static Set getModuleDependencies(Set requires) { return filterImplicitRequires(requires).map(Requires::name).collect(Collectors.toSet()); } private static Set getTransitiveModuleDependencies(Set requires) { return filterImplicitRequires(requires) .filter(r -> r.modifiers().contains(Requires.Modifier.TRANSITIVE)) .map(Requires::name) .collect(Collectors.toSet()); } private static Set getOptionalModuleDependencies(Set requires) { return filterImplicitRequires(requires) .filter(r -> r.modifiers().contains(Requires.Modifier.STATIC)) .map(Requires::name) .collect(Collectors.toSet()); } } ================================================ FILE: test-jpms/src/test/java/com/google/gson/jpms_test/ReflectionInaccessibleTest.java ================================================ /* * Copyright (C) 2024 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.jpms_test; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import com.google.gson.Gson; import com.google.gson.JsonIOException; import org.junit.Test; /** * Verifies that Gson cannot use reflection for classes in a package if it has not been 'opened' to * the Gson module in the {@code module-info.java} of the project. */ public class ReflectionInaccessibleTest { private static class MyClass { @SuppressWarnings("unused") int i; } @Test public void testDeserialization() { Gson gson = new Gson(); var e = assertThrows(JsonIOException.class, () -> gson.fromJson("{\"i\":1}", MyClass.class)); assertThat(e) .hasMessageThat() .isEqualTo( "Failed making field '" + MyClass.class.getName() + "#i' accessible; either increase its visibility or write a custom TypeAdapter for" + " its declaring type.\n" + "See https://github.com/google/gson/blob/main/Troubleshooting.md#reflection-inaccessible-to-module-gson"); } @Test public void testSerialization() { Gson gson = new Gson(); MyClass obj = new MyClass(); obj.i = 1; var e = assertThrows(JsonIOException.class, () -> gson.toJson(obj)); assertThat(e) .hasMessageThat() .isEqualTo( "Failed making field '" + MyClass.class.getName() + "#i' accessible; either increase its visibility or write a custom TypeAdapter for" + " its declaring type.\n" + "See https://github.com/google/gson/blob/main/Troubleshooting.md#reflection-inaccessible-to-module-gson"); } } ================================================ FILE: test-jpms/src/test/java/com/google/gson/jpms_test/opened/ReflectionTest.java ================================================ /* * Copyright (C) 2024 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. */ // This package is opened for reflection, see `module-info.java` package com.google.gson.jpms_test.opened; import static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import org.junit.Test; /** * Verifies that Gson can use reflection for classes in a package if it has been 'opened' to the * Gson module in the {@code module-info.java} of the project. */ public class ReflectionTest { private static class MyClass { int i; } @Test public void testDeserialization() { Gson gson = new Gson(); MyClass deserialized = gson.fromJson("{\"i\":1}", MyClass.class); assertThat(deserialized.i).isEqualTo(1); } @Test public void testSerialization() { Gson gson = new Gson(); MyClass obj = new MyClass(); obj.i = 1; String serialized = gson.toJson(obj); assertThat(serialized).isEqualTo("{\"i\":1}"); } } ================================================ FILE: test-jpms/src/test/java/module-info.java ================================================ /* * Copyright (C) 2024 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. */ @SuppressWarnings("requires-automatic") // for automatic module names for 'junit' and 'truth' module com.google.gson.jpms_test { requires com.google.gson; // Test dependencies requires junit; requires truth; // has no proper module name yet, see https://github.com/google/truth/issues/605 opens com.google.gson.jpms_test to junit; opens com.google.gson.jpms_test.opened to junit, com.google.gson; } ================================================ FILE: test-shrinker/README.md ================================================ # test-shrinker This Maven module contains integration tests which check the behavior of Gson when used in combination with code shrinking and obfuscation tools, such as ProGuard or R8. The code which is shrunken is under `src/main/java`; it should not contain any important assertions in case the code shrinking tools affect these assertions in any way. The test code under `src/test/java` executes the shrunken and obfuscated JAR and verifies that it behaves as expected. The tests might be a bit brittle, especially the R8 test setup. Future ProGuard and R8 versions might cause the tests to behave differently. In case tests fail the ProGuard and R8 mapping files created in the `target` directory can help with debugging. If necessary rewrite tests or even remove them if they cannot be implemented anymore for newer ProGuard or R8 versions. **Important:** Because execution of the code shrinking tools is performed during the Maven build, trying to directly run the integration tests from the IDE might not work, or might use stale results if you changed the configuration in between. Run `mvn clean verify` before trying to run the integration tests from the IDE. ================================================ FILE: test-shrinker/common.pro ================================================ ### Common rules for ProGuard and R8 ### Should only contains rules needed specifically for the integration test; ### any general rules which are relevant for all users should not be here but in `META-INF/proguard` of Gson -allowaccessmodification # On Windows mixed case class names might cause problems -dontusemixedcaseclassnames # Ignore notes about duplicate JDK classes -dontnote module-info,jdk.internal.** # Keep test entrypoints -keep class com.example.Main { public static void runTests(...); } -keep class com.example.NoSerializedNameMain { public static java.lang.String runTestNoArgsConstructor(); public static java.lang.String runTestNoJdkUnsafe(); public static java.lang.String runTestHasArgsConstructor(); } ### Test data setup # Keep fields without annotations which should be preserved -keepclassmembers class com.example.ClassWithNamedFields { !transient ; } -keepclassmembernames class com.example.ClassWithExposeAnnotation { ; } -keepclassmembernames class com.example.ClassWithJsonAdapterAnnotation { ** f; } -keepclassmembernames class com.example.ClassWithVersionAnnotations { ; } # Keep the name of the class to allow using reflection to check if this class still exists # after shrinking -keepnames class com.example.UnusedClass ================================================ FILE: test-shrinker/pom.xml ================================================ 4.0.0 com.google.code.gson gson-parent 2.13.3-SNAPSHOT test-shrinker Test: Code shrinking (ProGuard / R8) 8 true google https://maven.google.com com.google.code.gson gson ${project.parent.version} junit junit test com.google.truth truth test com.github.wvengen proguard-maven-plugin 2.7.0 package proguard com.guardsquare proguard-base 7.8.2 com.guardsquare proguard-core 9.3.0 true ${project.basedir}/proguard.pro ${java.home}/jmods/java.base.jmod ${java.home}/jmods/java.sql.jmod ${java.home}/jmods/java.compiler.jmod true proguard-output.jar org.apache.maven.plugins maven-shade-plugin 3.6.1 package shade false false *:* META-INF/MANIFEST.MF META-INF/versions/9/module-info.class org.codehaus.mojo exec-maven-plugin 3.6.3 r8 package java false false true com.android.tools r8 com.android.tools.r8.R8 --release --classfile --lib${java.home} --pg-conf${project.basedir}/r8.pro --pg-map-output${project.build.directory}/r8_map.txt --output${project.build.directory}/r8-output.jar ${project.build.directory}/${project.build.finalName}.jar com.android.tools r8 9.0.32 org.apache.maven.plugins maven-failsafe-plugin integration-test verify ================================================ FILE: test-shrinker/proguard.pro ================================================ # Include common rules -include common.pro ### ProGuard specific rules # Unlike R8, ProGuard does not perform aggressive optimization which makes classes abstract, # therefore for ProGuard can successfully perform deserialization, and for that need to # preserve the field names -keepclassmembernames class com.example.NoSerializedNameMain$TestClassNoArgsConstructor { ; } -keepclassmembernames class com.example.NoSerializedNameMain$TestClassNotAbstract { ; } -keepclassmembernames class com.example.NoSerializedNameMain$TestClassHasArgsConstructor { ; } ================================================ FILE: test-shrinker/r8.pro ================================================ # Include common rules -include common.pro ### The following rules are needed for R8 in "full mode", which performs more aggressive optimizations than ProGuard ### See https://r8.googlesource.com/r8/+/refs/heads/main/compatibility-faq.md#r8-full-mode # For classes with generic type parameter R8 in "full mode" requires to have a keep rule to # preserve the generic signature -keep,allowshrinking,allowoptimization,allowobfuscation,allowaccessmodification class com.example.GenericClasses$GenericClass -keep,allowshrinking,allowoptimization,allowobfuscation,allowaccessmodification class com.example.GenericClasses$GenericUsingGenericClass # Don't obfuscate class name, to check it in exception message -keep,allowshrinking,allowoptimization class com.example.NoSerializedNameMain$TestClassNoArgsConstructor -keep,allowshrinking,allowoptimization class com.example.NoSerializedNameMain$TestClassHasArgsConstructor # This rule has the side-effect that R8 still removes the no-args constructor, but does not make the class abstract -keep class com.example.NoSerializedNameMain$TestClassNotAbstract { @com.google.gson.annotations.SerializedName ; } # Keep enum constants which are not explicitly used in code -keepclassmembers class com.example.EnumClass { ** SECOND; } ================================================ FILE: test-shrinker/src/main/java/com/example/ClassWithAdapter.java ================================================ package com.example; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; @JsonAdapter(ClassWithAdapter.Adapter.class) public class ClassWithAdapter { static class Adapter extends TypeAdapter { @Override public ClassWithAdapter read(JsonReader in) throws IOException { in.beginObject(); String name = in.nextName(); if (!name.equals("custom")) { throw new IllegalArgumentException("Unexpected name: " + name); } int i = in.nextInt(); in.endObject(); return new ClassWithAdapter(i); } @Override public void write(JsonWriter out, ClassWithAdapter value) throws IOException { out.beginObject(); out.name("custom"); out.value(value.i); out.endObject(); } } public Integer i; public ClassWithAdapter(int i) { this.i = i; } @Override public String toString() { return "ClassWithAdapter[" + i + "]"; } } ================================================ FILE: test-shrinker/src/main/java/com/example/ClassWithExposeAnnotation.java ================================================ package com.example; import com.google.gson.annotations.Expose; /** Uses {@link Expose} annotation. */ public class ClassWithExposeAnnotation { @Expose int i; int i2; } ================================================ FILE: test-shrinker/src/main/java/com/example/ClassWithHasArgsConstructor.java ================================================ package com.example; import com.google.gson.annotations.SerializedName; /** Class without no-args constructor, but with field annotated with {@link SerializedName}. */ public class ClassWithHasArgsConstructor { @SerializedName("myField") public int i; // Specify explicit constructor with args to remove implicit no-args default constructor public ClassWithHasArgsConstructor(int i) { this.i = i; } } ================================================ FILE: test-shrinker/src/main/java/com/example/ClassWithJsonAdapterAnnotation.java ================================================ package com.example; 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.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; 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; /** Uses {@link JsonAdapter} annotation on fields. */ public class ClassWithJsonAdapterAnnotation { // For this field don't use @SerializedName and ignore it for deserialization // Has custom ProGuard rule to keep the field name @JsonAdapter(value = Adapter.class, nullSafe = false) DummyClass f; @SerializedName("f1") @JsonAdapter(Adapter.class) DummyClass f1; @SerializedName("f2") @JsonAdapter(Factory.class) DummyClass f2; @SerializedName("f3") @JsonAdapter(Serializer.class) DummyClass f3; @SerializedName("f4") @JsonAdapter(Deserializer.class) DummyClass f4; public ClassWithJsonAdapterAnnotation() {} // Note: R8 seems to make this constructor the no-args constructor and initialize fields // by default; currently this is not visible in the deserialization test because the JSON data // contains values for all fields; but it is noticeable once the JSON data is missing fields public ClassWithJsonAdapterAnnotation(int i1, int i2, int i3, int i4) { f1 = new DummyClass(Integer.toString(i1)); f2 = new DummyClass(Integer.toString(i2)); f3 = new DummyClass(Integer.toString(i3)); f4 = new DummyClass(Integer.toString(i4)); // Note: Deliberately don't initialize field `f` here to not refer to it anywhere in code } @Override public String toString() { return "ClassWithJsonAdapterAnnotation[f1=" + f1 + ", f2=" + f2 + ", f3=" + f3 + ", f4=" + f4 + "]"; } static class Adapter extends TypeAdapter { @Override public DummyClass read(JsonReader in) throws IOException { return new DummyClass("adapter-" + in.nextInt()); } @Override public void write(JsonWriter out, DummyClass value) throws IOException { out.value("adapter-" + value); } } static class Factory implements TypeAdapterFactory { @Override public TypeAdapter create(Gson gson, TypeToken type) { // the code below is not type-safe, but does not matter for this test @SuppressWarnings("unchecked") TypeAdapter r = (TypeAdapter) new TypeAdapter() { @Override public DummyClass read(JsonReader in) throws IOException { return new DummyClass("factory-" + in.nextInt()); } @Override public void write(JsonWriter out, DummyClass value) throws IOException { out.value("factory-" + value.s); } }; return r; } } static class Serializer implements JsonSerializer { @Override public JsonElement serialize(DummyClass src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive("serializer-" + src.s); } } static class Deserializer implements JsonDeserializer { @Override public DummyClass deserialize( JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return new DummyClass("deserializer-" + json.getAsInt()); } } // Use this separate class mainly to work around incorrect delegation behavior for JsonSerializer // and JsonDeserializer used with @JsonAdapter, see https://github.com/google/gson/issues/1783 static class DummyClass { @SerializedName("s") String s; DummyClass(String s) { this.s = s; } @Override public String toString() { return s; } } } ================================================ FILE: test-shrinker/src/main/java/com/example/ClassWithNamedFields.java ================================================ package com.example; public class ClassWithNamedFields { public int myField; public short notAccessedField = -1; public ClassWithNamedFields(int i) { myField = i; } } ================================================ FILE: test-shrinker/src/main/java/com/example/ClassWithNoArgsConstructor.java ================================================ package com.example; import com.google.gson.annotations.SerializedName; /** Class with no-args constructor and with field annotated with {@link SerializedName}. */ public class ClassWithNoArgsConstructor { @SerializedName("myField") public int i; public ClassWithNoArgsConstructor() { i = -3; } } ================================================ FILE: test-shrinker/src/main/java/com/example/ClassWithSerializedName.java ================================================ package com.example; import com.google.gson.annotations.SerializedName; public class ClassWithSerializedName { @SerializedName("myField") public int i; @SerializedName("notAccessed") public short notAccessedField = -1; public ClassWithSerializedName(int i) { this.i = i; } } ================================================ FILE: test-shrinker/src/main/java/com/example/ClassWithUnreferencedHasArgsConstructor.java ================================================ package com.example; import com.google.gson.annotations.SerializedName; /** * Class without no-args constructor, but with field annotated with {@link SerializedName}. The * constructor should not be used in the code, but this shouldn't lead to R8 concluding that values * of the type are not constructible and therefore must be null. */ public class ClassWithUnreferencedHasArgsConstructor { @SerializedName("myField") public int i; // Specify explicit constructor with args to remove implicit no-args default constructor public ClassWithUnreferencedHasArgsConstructor(int i) { this.i = i; } } ================================================ FILE: test-shrinker/src/main/java/com/example/ClassWithUnreferencedNoArgsConstructor.java ================================================ package com.example; import com.google.gson.annotations.SerializedName; /** * Class with no-args constructor and with field annotated with {@link SerializedName}. The * constructor should not be used in the code, but this shouldn't lead to R8 concluding that values * of the type are not constructible and therefore must be null. */ public class ClassWithUnreferencedNoArgsConstructor { @SerializedName("myField") public int i; public ClassWithUnreferencedNoArgsConstructor() { i = -3; } } ================================================ FILE: test-shrinker/src/main/java/com/example/ClassWithVersionAnnotations.java ================================================ package com.example; import com.google.gson.annotations.Since; import com.google.gson.annotations.Until; /** Uses {@link Since} and {@link Until} annotations. */ public class ClassWithVersionAnnotations { @Since(1) int i1; @Until(1) // will be ignored with GsonBuilder.setVersion(1) int i2; @Since(2) // will be ignored with GsonBuilder.setVersion(1) int i3; @Until(2) int i4; } ================================================ FILE: test-shrinker/src/main/java/com/example/EnumClass.java ================================================ package com.example; public enum EnumClass { FIRST, SECOND } ================================================ FILE: test-shrinker/src/main/java/com/example/EnumClassWithSerializedName.java ================================================ package com.example; import com.google.gson.annotations.SerializedName; public enum EnumClassWithSerializedName { @SerializedName("one") FIRST, @SerializedName("two") SECOND } ================================================ FILE: test-shrinker/src/main/java/com/example/GenericClasses.java ================================================ package com.example; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; public class GenericClasses { private GenericClasses() {} static class GenericClass { @SerializedName("t") T t; @Override public String toString() { return "{t=" + t + "}"; } } static class UsingGenericClass { @SerializedName("g") GenericClass g; @Override public String toString() { return "{g=" + g + "}"; } } static class GenericUsingGenericClass { @SerializedName("g") GenericClass g; @Override public String toString() { return "{g=" + g + "}"; } } @JsonAdapter(DummyClass.Adapter.class) static class DummyClass { String s; DummyClass(String s) { this.s = s; } @Override public String toString() { return s; } static class Adapter extends TypeAdapter { @Override public DummyClass read(JsonReader in) throws IOException { return new DummyClass("read-" + in.nextInt()); } @Override public void write(JsonWriter out, DummyClass value) throws IOException { throw new UnsupportedOperationException(); } } } } ================================================ FILE: test-shrinker/src/main/java/com/example/InterfaceWithImplementation.java ================================================ package com.example; import com.google.gson.annotations.SerializedName; /** Interface whose implementation class is only referenced for deserialization */ public interface InterfaceWithImplementation { String getValue(); // Implementation class which is only referenced in `TypeToken`, but nowhere else public static class Implementation implements InterfaceWithImplementation { public Implementation() {} @SerializedName("s") public String s; @Override public String getValue() { return s; } } } ================================================ FILE: test-shrinker/src/main/java/com/example/Main.java ================================================ package com.example; import static com.example.TestExecutor.same; import com.example.GenericClasses.DummyClass; import com.example.GenericClasses.GenericClass; import com.example.GenericClasses.GenericUsingGenericClass; import com.example.GenericClasses.UsingGenericClass; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import java.util.Arrays; import java.util.List; import java.util.function.BiConsumer; import java.util.function.Supplier; public class Main { private Main() {} /** * Main entrypoint, called by {@code ShrinkingIT.test()}. * *

To be safe let all tests put their output to the consumer and let integration test verify * it; don't perform any relevant assertions in this code because code shrinkers could affect it. * * @param outputConsumer consumes the test output: {@code name, content} pairs */ public static void runTests(BiConsumer outputConsumer) { // Create the TypeToken instances on demand because creation of them can fail when // generic signatures were erased testTypeTokenWriteRead( outputConsumer, "anonymous", () -> new TypeToken>() {}); testTypeTokenWriteRead( outputConsumer, "manual", () -> TypeToken.getParameterized(List.class, ClassWithAdapter.class)); testNamedFields(outputConsumer); testSerializedName(outputConsumer); testConstructorNoArgs(outputConsumer); testConstructorHasArgs(outputConsumer); testUnreferencedConstructorNoArgs(outputConsumer); testUnreferencedConstructorHasArgs(outputConsumer); testNoJdkUnsafe(outputConsumer); testEnum(outputConsumer); testEnumSerializedName(outputConsumer); testExposeAnnotation(outputConsumer); testVersionAnnotations(outputConsumer); testJsonAdapterAnnotation(outputConsumer); testGenericClasses(outputConsumer); testDeserializingInterfaceImpl(outputConsumer); } private static void testTypeTokenWriteRead( BiConsumer outputConsumer, String description, Supplier> typeTokenSupplier) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); TestExecutor.run( outputConsumer, "Write: TypeToken " + description, () -> gson.toJson(Arrays.asList(new ClassWithAdapter(1)), typeTokenSupplier.get().getType())); TestExecutor.run( outputConsumer, "Read: TypeToken " + description, () -> { Object deserialized = gson.fromJson("[{\"custom\": 3}]", typeTokenSupplier.get()); return deserialized.toString(); }); } /** * Calls {@link Gson#toJson}, but (hopefully) in a way which prevents code shrinkers from * understanding that reflection is used for {@code obj}. */ private static String toJson(Gson gson, Object obj) { return gson.toJson(same(obj)); } /** * Calls {@link Gson#fromJson}, but (hopefully) in a way which prevents code shrinkers from * understanding that reflection is used for {@code c}. */ private static T fromJson(Gson gson, String json, Class c) { return gson.fromJson(json, same(c)); } private static void testNamedFields(BiConsumer outputConsumer) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); TestExecutor.run( outputConsumer, "Write: Named fields", () -> toJson(gson, new ClassWithNamedFields(2))); TestExecutor.run( outputConsumer, "Read: Named fields", () -> { ClassWithNamedFields deserialized = fromJson(gson, "{\"myField\": 3}", ClassWithNamedFields.class); return Integer.toString(deserialized.myField); }); } private static void testSerializedName(BiConsumer outputConsumer) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); TestExecutor.run( outputConsumer, "Write: SerializedName", () -> toJson(gson, new ClassWithSerializedName(2))); TestExecutor.run( outputConsumer, "Read: SerializedName", () -> { ClassWithSerializedName deserialized = fromJson(gson, "{\"myField\": 3}", ClassWithSerializedName.class); return Integer.toString(deserialized.i); }); } private static void testConstructorNoArgs(BiConsumer outputConsumer) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); TestExecutor.run( outputConsumer, "Write: No args constructor", () -> toJson(gson, new ClassWithNoArgsConstructor())); TestExecutor.run( outputConsumer, "Read: No args constructor; initial constructor value", () -> { ClassWithNoArgsConstructor deserialized = fromJson(gson, "{}", ClassWithNoArgsConstructor.class); return Integer.toString(deserialized.i); }); TestExecutor.run( outputConsumer, "Read: No args constructor; custom value", () -> { ClassWithNoArgsConstructor deserialized = fromJson(gson, "{\"myField\": 3}", ClassWithNoArgsConstructor.class); return Integer.toString(deserialized.i); }); } private static void testConstructorHasArgs(BiConsumer outputConsumer) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); TestExecutor.run( outputConsumer, "Write: Constructor with args", () -> toJson(gson, new ClassWithHasArgsConstructor(2))); // This most likely relies on JDK Unsafe (unless the shrinker rewrites the constructor in some // way) TestExecutor.run( outputConsumer, "Read: Constructor with args", () -> { ClassWithHasArgsConstructor deserialized = fromJson(gson, "{\"myField\": 3}", ClassWithHasArgsConstructor.class); return Integer.toString(deserialized.i); }); } private static void testUnreferencedConstructorNoArgs(BiConsumer outputConsumer) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); // No write because we're not referencing this class's constructor. // This runs the no-args constructor. TestExecutor.run( outputConsumer, "Read: Unreferenced no args constructor; initial constructor value", () -> { ClassWithUnreferencedNoArgsConstructor deserialized = fromJson(gson, "{}", ClassWithUnreferencedNoArgsConstructor.class); return Integer.toString(deserialized.i); }); TestExecutor.run( outputConsumer, "Read: Unreferenced no args constructor; custom value", () -> { ClassWithUnreferencedNoArgsConstructor deserialized = fromJson(gson, "{\"myField\": 3}", ClassWithUnreferencedNoArgsConstructor.class); return Integer.toString(deserialized.i); }); } private static void testUnreferencedConstructorHasArgs( BiConsumer outputConsumer) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); // No write because we're not referencing this class's constructor. // This most likely relies on JDK Unsafe (unless the shrinker rewrites the constructor in some // way) TestExecutor.run( outputConsumer, "Read: Unreferenced constructor with args", () -> { ClassWithUnreferencedHasArgsConstructor deserialized = fromJson(gson, "{\"myField\": 3}", ClassWithUnreferencedHasArgsConstructor.class); return Integer.toString(deserialized.i); }); } private static void testNoJdkUnsafe(BiConsumer outputConsumer) { Gson gson = new GsonBuilder().disableJdkUnsafe().create(); TestExecutor.run( outputConsumer, "Read: No JDK Unsafe; initial constructor value", () -> { ClassWithNoArgsConstructor deserialized = fromJson(gson, "{}", ClassWithNoArgsConstructor.class); return Integer.toString(deserialized.i); }); TestExecutor.run( outputConsumer, "Read: No JDK Unsafe; custom value", () -> { ClassWithNoArgsConstructor deserialized = fromJson(gson, "{\"myField\": 3}", ClassWithNoArgsConstructor.class); return Integer.toString(deserialized.i); }); } private static void testEnum(BiConsumer outputConsumer) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); TestExecutor.run(outputConsumer, "Write: Enum", () -> toJson(gson, EnumClass.FIRST)); TestExecutor.run( outputConsumer, "Read: Enum", () -> fromJson(gson, "\"SECOND\"", EnumClass.class).toString()); } private static void testEnumSerializedName(BiConsumer outputConsumer) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); TestExecutor.run( outputConsumer, "Write: Enum SerializedName", () -> toJson(gson, EnumClassWithSerializedName.FIRST)); TestExecutor.run( outputConsumer, "Read: Enum SerializedName", () -> fromJson(gson, "\"two\"", EnumClassWithSerializedName.class).toString()); } private static void testExposeAnnotation(BiConsumer outputConsumer) { Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); TestExecutor.run( outputConsumer, "Write: @Expose", () -> toJson(gson, new ClassWithExposeAnnotation())); } private static void testVersionAnnotations(BiConsumer outputConsumer) { Gson gson = new GsonBuilder().setVersion(1).create(); TestExecutor.run( outputConsumer, "Write: Version annotations", () -> toJson(gson, new ClassWithVersionAnnotations())); } private static void testJsonAdapterAnnotation(BiConsumer outputConsumer) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); TestExecutor.run( outputConsumer, "Write: JsonAdapter on fields", () -> toJson(gson, new ClassWithJsonAdapterAnnotation(1, 2, 3, 4))); String json = "{\"f1\": 1, \"f2\": 2, \"f3\": {\"s\": \"3\"}, \"f4\": 4}"; TestExecutor.run( outputConsumer, "Read: JsonAdapter on fields", () -> fromJson(gson, json, ClassWithJsonAdapterAnnotation.class).toString()); } private static void testGenericClasses(BiConsumer outputConsumer) { Gson gson = new Gson(); TestExecutor.run( outputConsumer, "Read: Generic TypeToken", () -> gson.fromJson("{\"t\": 1}", new TypeToken>() {}).toString()); TestExecutor.run( outputConsumer, "Read: Using Generic", () -> fromJson(gson, "{\"g\": {\"t\": 1}}", UsingGenericClass.class).toString()); TestExecutor.run( outputConsumer, "Read: Using Generic TypeToken", () -> gson.fromJson( "{\"g\": {\"t\": 1}}", new TypeToken>() {}) .toString()); } private static void testDeserializingInterfaceImpl(BiConsumer outputConsumer) { Gson gson = new Gson(); TestExecutor.run( outputConsumer, "Read: Interface implementation", () -> { try { // Use the interface type here List list = gson.fromJson( "[{\"s\": \"value\"}]", // This is the only place where the implementation class is referenced new TypeToken>() {}); return list.get(0).getValue(); } catch (ClassCastException e) { // TODO: R8 causes exception, see https://github.com/google/gson/issues/2658 return "ClassCastException"; } }); } } ================================================ FILE: test-shrinker/src/main/java/com/example/NoSerializedNameMain.java ================================================ package com.example; import static com.example.TestExecutor.same; import com.google.gson.Gson; import com.google.gson.GsonBuilder; /** * Covers cases of classes which don't use {@code @SerializedName} on their fields, and are * therefore not matched by the default {@code gson.pro} rules. */ public class NoSerializedNameMain { private NoSerializedNameMain() {} static class TestClassNoArgsConstructor { // Has a no-args default constructor. public String s; } // R8 test rule in r8.pro for this class still removes no-args constructor, but doesn't make class // abstract static class TestClassNotAbstract { public String s; } static class TestClassHasArgsConstructor { public String s; // Specify explicit constructor with args to remove implicit no-args default constructor public TestClassHasArgsConstructor(String s) { this.s = s; } } /** Main entrypoint, called by {@code ShrinkingIT.testNoSerializedName_NoArgsConstructor()}. */ public static String runTestNoArgsConstructor() { TestClassNoArgsConstructor deserialized = new Gson().fromJson("{\"s\":\"value\"}", same(TestClassNoArgsConstructor.class)); return deserialized.s; } /** * Main entrypoint, called by {@code * ShrinkingIT.testNoSerializedName_NoArgsConstructorNoJdkUnsafe()}. */ public static String runTestNoJdkUnsafe() { Gson gson = new GsonBuilder().disableJdkUnsafe().create(); TestClassNotAbstract deserialized = gson.fromJson("{\"s\": \"value\"}", same(TestClassNotAbstract.class)); return deserialized.s; } /** Main entrypoint, called by {@code ShrinkingIT.testNoSerializedName_HasArgsConstructor()}. */ public static String runTestHasArgsConstructor() { TestClassHasArgsConstructor deserialized = new Gson().fromJson("{\"s\":\"value\"}", same(TestClassHasArgsConstructor.class)); return deserialized.s; } } ================================================ FILE: test-shrinker/src/main/java/com/example/TestExecutor.java ================================================ package com.example; import java.util.Optional; import java.util.function.BiConsumer; import java.util.function.Supplier; public class TestExecutor { private TestExecutor() {} /** * Helper method for running individual tests. In case of an exception wraps it and includes the * {@code name} of the test to make debugging issues with the obfuscated JARs a bit easier. */ public static void run( BiConsumer outputConsumer, String name, Supplier resultSupplier) { String result; try { result = resultSupplier.get(); } catch (Throwable t) { throw new RuntimeException("Test failed: " + name, t); } outputConsumer.accept(name, result); } /** * Returns {@code t}, but in a way which (hopefully) prevents code shrinkers from simplifying * this. */ public static T same(T t) { // This is essentially `return t`, but contains some redundant code to try // prevent the code shrinkers from simplifying this return Optional.of(t) .map(v -> Optional.of(v).get()) .orElseThrow(() -> new AssertionError("unreachable")); } } ================================================ FILE: test-shrinker/src/main/java/com/example/UnusedClass.java ================================================ package com.example; import com.google.gson.annotations.SerializedName; /** * Class with no-args constructor and field annotated with {@code @SerializedName}, but which is not * actually used anywhere in the code. * *

The default ProGuard rules should not keep this class. */ public class UnusedClass { public UnusedClass() {} @SerializedName("i") public int i; } ================================================ FILE: test-shrinker/src/test/java/com/google/gson/it/ShrinkingIT.java ================================================ /* * Copyright (C) 2023 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.it; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import static org.junit.Assert.fail; import static org.junit.Assume.assumeFalse; import com.example.UnusedClass; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.function.BiConsumer; import org.junit.Before; 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; /** Integration test verifying behavior of shrunken and obfuscated JARs. */ @SuppressWarnings("MemberName") // class name must end with 'IT' for Maven Failsafe Plugin @RunWith(Parameterized.class) public class ShrinkingIT { // These JAR files are prepared by the Maven build public static final Path PROGUARD_RESULT_PATH = Paths.get("target/proguard-output.jar"); public static final Path R8_RESULT_PATH = Paths.get("target/r8-output.jar"); @Parameters(name = "{index}: {0}") public static List jarsToTest() { return Arrays.asList(PROGUARD_RESULT_PATH, R8_RESULT_PATH); } @Parameter public Path jarToTest; @Before public void verifyJarExists() { if (!Files.isRegularFile(jarToTest)) { fail("JAR file " + jarToTest + " does not exist; run this test with `mvn clean verify`"); } } /** Returns whether the test is currently running for ProGuard, instead of R8 */ private boolean isTestingProGuard() { return jarToTest.equals(PROGUARD_RESULT_PATH); } @FunctionalInterface interface TestAction { void run(Class c) throws Exception; } private void runTest(String className, TestAction testAction) throws Exception { // Use bootstrap class loader; load all custom classes from JAR and not // from dependencies of this test ClassLoader classLoader = null; // Load the shrunken and obfuscated JARs with a separate class loader, then load // the main test class from it and let the test action invoke its test methods try (URLClassLoader loader = new URLClassLoader(new URL[] {jarToTest.toUri().toURL()}, classLoader)) { Class c = loader.loadClass(className); testAction.run(c); } } @Test public void test() throws Exception { StringBuilder output = new StringBuilder(); runTest( "com.example.Main", c -> { Method m = c.getMethod("runTests", BiConsumer.class); m.invoke( null, (BiConsumer) (name, content) -> output.append(name + "\n" + content + "\n===\n")); }); assertThat(output.toString()) .isEqualTo( String.join( "\n", "Write: TypeToken anonymous", "[", " {", " \"custom\": 1", " }", "]", "===", "Read: TypeToken anonymous", "[ClassWithAdapter[3]]", "===", "Write: TypeToken manual", "[", " {", " \"custom\": 1", " }", "]", "===", "Read: TypeToken manual", "[ClassWithAdapter[3]]", "===", "Write: Named fields", "{", " \"myField\": 2,", " \"notAccessedField\": -1", "}", "===", "Read: Named fields", "3", "===", "Write: SerializedName", "{", " \"myField\": 2,", " \"notAccessed\": -1", "}", "===", "Read: SerializedName", "3", "===", "Write: No args constructor", "{", " \"myField\": -3", "}", "===", "Read: No args constructor; initial constructor value", "-3", "===", "Read: No args constructor; custom value", "3", "===", "Write: Constructor with args", "{", " \"myField\": 2", "}", "===", "Read: Constructor with args", "3", "===", "Read: Unreferenced no args constructor; initial constructor value", "-3", "===", "Read: Unreferenced no args constructor; custom value", "3", "===", "Read: Unreferenced constructor with args", "3", "===", "Read: No JDK Unsafe; initial constructor value", "-3", "===", "Read: No JDK Unsafe; custom value", "3", "===", "Write: Enum", "\"FIRST\"", "===", "Read: Enum", "SECOND", "===", "Write: Enum SerializedName", "\"one\"", "===", "Read: Enum SerializedName", "SECOND", "===", "Write: @Expose", "{\"i\":0}", "===", "Write: Version annotations", "{\"i1\":0,\"i4\":0}", "===", "Write: JsonAdapter on fields", "{", " \"f\": \"adapter-null\",", " \"f1\": \"adapter-1\",", " \"f2\": \"factory-2\",", " \"f3\": \"serializer-3\",", // For f4 only a JsonDeserializer is registered, so serialization falls back to // reflection " \"f4\": {", " \"s\": \"4\"", " }", "}", "===", "Read: JsonAdapter on fields", // For f3 only a JsonSerializer is registered, so for deserialization value is read // as is using reflection "ClassWithJsonAdapterAnnotation[f1=adapter-1, f2=factory-2, f3=3," + " f4=deserializer-4]", "===", "Read: Generic TypeToken", "{t=read-1}", "===", "Read: Using Generic", "{g={t=read-1}}", "===", "Read: Using Generic TypeToken", "{g={t=read-1}}", "===", "Read: Interface implementation", // TODO: Currently only works for ProGuard but not R8 isTestingProGuard() ? "value" : "ClassCastException", "===", "")); } @Test public void testNoSerializedName_NoArgsConstructor() throws Exception { runTest( "com.example.NoSerializedNameMain", c -> { Method m = c.getMethod("runTestNoArgsConstructor"); if (isTestingProGuard()) { Object result = m.invoke(null); assertThat(result).isEqualTo("value"); } else { // R8 performs more aggressive optimizations Exception e = assertThrows(InvocationTargetException.class, () -> m.invoke(null)); assertThat(e) .hasCauseThat() .hasMessageThat() .isEqualTo( "Abstract classes can't be instantiated! Adjust the R8 configuration or" + " register an InstanceCreator or a TypeAdapter for this type. Class name:" + " com.example.NoSerializedNameMain$TestClassNoArgsConstructor\n" + "See https://github.com/google/gson/blob/main/Troubleshooting.md#r8-abstract-class"); } }); } @Test public void testNoSerializedName_NoArgsConstructorNoJdkUnsafe() throws Exception { runTest( "com.example.NoSerializedNameMain", c -> { Method m = c.getMethod("runTestNoJdkUnsafe"); if (isTestingProGuard()) { Object result = m.invoke(null); assertThat(result).isEqualTo("value"); } else { // R8 performs more aggressive optimizations Exception e = assertThrows(InvocationTargetException.class, () -> m.invoke(null)); assertThat(e) .hasCauseThat() .hasMessageThat() .isEqualTo( "Unable to create instance of class" + " com.example.NoSerializedNameMain$TestClassNotAbstract; 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. Or adjust your R8 configuration to keep" + " the no-args constructor of the class."); } }); } @Test public void testNoSerializedName_HasArgsConstructor() throws Exception { runTest( "com.example.NoSerializedNameMain", c -> { Method m = c.getMethod("runTestHasArgsConstructor"); if (isTestingProGuard()) { Object result = m.invoke(null); assertThat(result).isEqualTo("value"); } else { // R8 performs more aggressive optimizations Exception e = assertThrows(InvocationTargetException.class, () -> m.invoke(null)); assertThat(e) .hasCauseThat() .hasMessageThat() .isEqualTo( "Abstract classes can't be instantiated! Adjust the R8 configuration or" + " register an InstanceCreator or a TypeAdapter for this type. Class name:" + " com.example.NoSerializedNameMain$TestClassHasArgsConstructor\n" + "See https://github.com/google/gson/blob/main/Troubleshooting.md#r8-abstract-class"); } }); } @Test public void testUnusedClassRemoved() throws Exception { // For some reason this test only works for R8 but not for ProGuard; ProGuard keeps the unused // class assumeFalse(isTestingProGuard()); String className = UnusedClass.class.getName(); ClassNotFoundException e = assertThrows( ClassNotFoundException.class, () -> { runTest( className, c -> { fail("Class should have been removed during shrinking: " + c); }); }); assertThat(e).hasMessageThat().contains(className); } }