gson-comments/gson/src/main/java/com/google/gson/Gson.java

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

1530 lines
67 KiB
Java
Raw Permalink Normal View History

2008-09-01 05:13:32 +02:00
/*
* 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.JsonAdapter;
Down to 22 failing tests. Consolidated all of the different code paths that we use to construct instances. We now have an ObjectConstructor class that knows what type it constructs; this means that we don't need to ever do reflection to lookup a constructor at construction time. Cleaned up some buggy type adapters, particularly around handling of null. Removed dead code for object graph navigation. Moved some classes into 'internal' so they are visible to the 'bind' subpackage. Turned some TypeAdapterFactory/TypeAdapter pairs inside out so that the TypeAdapter is now the inner class. This is necessary so that the factories can take parameters. Added an API to request the 'next' type adapter for a type. This allows type adapters to compose other type adapters. We're using this in two places: - where the user has excluded a type from serialization but not deserialization, we need to use the "default" deserialization but interpose null on serialization. We create a type adapter that delegates for one and returns null for the other. - similarly when a DOM type serializer is registered but no deserializer, or vice versa. This is the biggest change to the MiniGson core. For backwards compatibility, return null for the empty string. Simplify JsonSerializationContext/JsonDeserializationContext to simply call through to GSON. SerializeDefault is currently unsupported. More useful error messages when calling getAsBoolean on a JsonNull. Remove currently unused MemoryRefStack. We might need this back again, though wiring it back in will be much more difficult because we don't interject ourselves between the users' various type adapters.
2011-09-11 09:04:56 +02:00
import com.google.gson.internal.ConstructorConstructor;
2023-09-19 20:14:48 +02:00
import com.google.gson.internal.DefaultConfig;
import com.google.gson.internal.Excluder;
import com.google.gson.internal.GsonBuildConfig;
import com.google.gson.internal.LazilyParsedNumber;
Down to 22 failing tests. Consolidated all of the different code paths that we use to construct instances. We now have an ObjectConstructor class that knows what type it constructs; this means that we don't need to ever do reflection to lookup a constructor at construction time. Cleaned up some buggy type adapters, particularly around handling of null. Removed dead code for object graph navigation. Moved some classes into 'internal' so they are visible to the 'bind' subpackage. Turned some TypeAdapterFactory/TypeAdapter pairs inside out so that the TypeAdapter is now the inner class. This is necessary so that the factories can take parameters. Added an API to request the 'next' type adapter for a type. This allows type adapters to compose other type adapters. We're using this in two places: - where the user has excluded a type from serialization but not deserialization, we need to use the "default" deserialization but interpose null on serialization. We create a type adapter that delegates for one and returns null for the other. - similarly when a DOM type serializer is registered but no deserializer, or vice versa. This is the biggest change to the MiniGson core. For backwards compatibility, return null for the empty string. Simplify JsonSerializationContext/JsonDeserializationContext to simply call through to GSON. SerializeDefault is currently unsupported. More useful error messages when calling getAsBoolean on a JsonNull. Remove currently unused MemoryRefStack. We might need this back again, though wiring it back in will be much more difficult because we don't interject ourselves between the users' various type adapters.
2011-09-11 09:04:56 +02:00
import com.google.gson.internal.Primitives;
import com.google.gson.internal.Streams;
import com.google.gson.internal.bind.ArrayTypeAdapter;
Down to 22 failing tests. Consolidated all of the different code paths that we use to construct instances. We now have an ObjectConstructor class that knows what type it constructs; this means that we don't need to ever do reflection to lookup a constructor at construction time. Cleaned up some buggy type adapters, particularly around handling of null. Removed dead code for object graph navigation. Moved some classes into 'internal' so they are visible to the 'bind' subpackage. Turned some TypeAdapterFactory/TypeAdapter pairs inside out so that the TypeAdapter is now the inner class. This is necessary so that the factories can take parameters. Added an API to request the 'next' type adapter for a type. This allows type adapters to compose other type adapters. We're using this in two places: - where the user has excluded a type from serialization but not deserialization, we need to use the "default" deserialization but interpose null on serialization. We create a type adapter that delegates for one and returns null for the other. - similarly when a DOM type serializer is registered but no deserializer, or vice versa. This is the biggest change to the MiniGson core. For backwards compatibility, return null for the empty string. Simplify JsonSerializationContext/JsonDeserializationContext to simply call through to GSON. SerializeDefault is currently unsupported. More useful error messages when calling getAsBoolean on a JsonNull. Remove currently unused MemoryRefStack. We might need this back again, though wiring it back in will be much more difficult because we don't interject ourselves between the users' various type adapters.
2011-09-11 09:04:56 +02:00
import com.google.gson.internal.bind.CollectionTypeAdapterFactory;
import com.google.gson.internal.bind.DefaultDateTypeAdapter;
2014-03-26 18:59:54 +01:00
import com.google.gson.internal.bind.JsonAdapterAnnotationTypeAdapterFactory;
2023-01-21 14:27:59 +01:00
import com.google.gson.stream.JsonTreeReader;
import com.google.gson.stream.JsonTreeWriter;
Down to 22 failing tests. Consolidated all of the different code paths that we use to construct instances. We now have an ObjectConstructor class that knows what type it constructs; this means that we don't need to ever do reflection to lookup a constructor at construction time. Cleaned up some buggy type adapters, particularly around handling of null. Removed dead code for object graph navigation. Moved some classes into 'internal' so they are visible to the 'bind' subpackage. Turned some TypeAdapterFactory/TypeAdapter pairs inside out so that the TypeAdapter is now the inner class. This is necessary so that the factories can take parameters. Added an API to request the 'next' type adapter for a type. This allows type adapters to compose other type adapters. We're using this in two places: - where the user has excluded a type from serialization but not deserialization, we need to use the "default" deserialization but interpose null on serialization. We create a type adapter that delegates for one and returns null for the other. - similarly when a DOM type serializer is registered but no deserializer, or vice versa. This is the biggest change to the MiniGson core. For backwards compatibility, return null for the empty string. Simplify JsonSerializationContext/JsonDeserializationContext to simply call through to GSON. SerializeDefault is currently unsupported. More useful error messages when calling getAsBoolean on a JsonNull. Remove currently unused MemoryRefStack. We might need this back again, though wiring it back in will be much more difficult because we don't interject ourselves between the users' various type adapters.
2011-09-11 09:04:56 +02:00
import com.google.gson.internal.bind.MapTypeAdapterFactory;
import com.google.gson.internal.bind.NumberTypeAdapter;
2011-09-09 05:31:16 +02:00
import com.google.gson.internal.bind.ObjectTypeAdapter;
Down to 22 failing tests. Consolidated all of the different code paths that we use to construct instances. We now have an ObjectConstructor class that knows what type it constructs; this means that we don't need to ever do reflection to lookup a constructor at construction time. Cleaned up some buggy type adapters, particularly around handling of null. Removed dead code for object graph navigation. Moved some classes into 'internal' so they are visible to the 'bind' subpackage. Turned some TypeAdapterFactory/TypeAdapter pairs inside out so that the TypeAdapter is now the inner class. This is necessary so that the factories can take parameters. Added an API to request the 'next' type adapter for a type. This allows type adapters to compose other type adapters. We're using this in two places: - where the user has excluded a type from serialization but not deserialization, we need to use the "default" deserialization but interpose null on serialization. We create a type adapter that delegates for one and returns null for the other. - similarly when a DOM type serializer is registered but no deserializer, or vice versa. This is the biggest change to the MiniGson core. For backwards compatibility, return null for the empty string. Simplify JsonSerializationContext/JsonDeserializationContext to simply call through to GSON. SerializeDefault is currently unsupported. More useful error messages when calling getAsBoolean on a JsonNull. Remove currently unused MemoryRefStack. We might need this back again, though wiring it back in will be much more difficult because we don't interject ourselves between the users' various type adapters.
2011-09-11 09:04:56 +02:00
import com.google.gson.internal.bind.ReflectiveTypeAdapterFactory;
import com.google.gson.internal.bind.SerializationDelegatingTypeAdapter;
import com.google.gson.internal.bind.TypeAdapters;
2020-05-09 17:37:21 +02:00
import com.google.gson.internal.sql.SqlTypesSupport;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import com.google.gson.stream.MalformedJsonException;
import java.io.EOFException;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicLongArray;
2008-09-01 05:13:32 +02:00
/**
* 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.
2008-09-01 05:13:32 +02:00
*
* <p>You can create a Gson instance by invoking {@code new Gson()} if the default configuration is
* all you need. You can also use {@link GsonBuilder} to build a Gson instance with various
* configuration options such as versioning support, pretty printing, custom newline, custom indent,
* custom {@link JsonSerializer}s, {@link JsonDeserializer}s, and {@link InstanceCreator}s.
2008-09-01 05:13:32 +02:00
*
* <p>Here is an example of how Gson is used for a simple Class:
*
* <pre>
* Gson gson = new Gson(); // Or use new GsonBuilder().create();
* MyType target = new MyType();
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* String json = gson.toJson(target); // serializes target to JSON
2008-09-01 05:13:32 +02:00
* MyType target2 = gson.fromJson(json, MyType.class); // deserializes json into target2
* </pre>
2008-09-01 05:13:32 +02:00
*
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* <p>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<MyType>}) 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:
*
2008-09-01 05:13:32 +02:00
* <pre>
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* TypeToken&lt;List&lt;MyType&gt;&gt; listType = new TypeToken&lt;List&lt;MyType&gt;&gt;() {};
* List&lt;MyType&gt; target = new LinkedList&lt;MyType&gt;();
* target.add(new MyType(1, "abc"));
2008-09-01 05:13:32 +02:00
*
* Gson gson = new Gson();
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* // 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&lt;MyType&gt; target2 = gson.fromJson(json, listType);
* </pre>
2008-09-01 05:13:32 +02:00
*
* <p>See the <a href="https://github.com/google/gson/blob/main/UserGuide.md">Gson User Guide</a>
2008-09-01 05:13:32 +02:00
* for a more complete set of examples.
*
Strict mode for JSON parsing, contributed by @marten-voorberg. (#2437) * Strict mode for JSON parsing (#2323) * Feat #6: Add strict flag to Gson and GsonBuilder * Test #2: Add failing tests for capitalized keywords * Feat #2: JsonReader does not read (partially) capitalized keywords if strict mode is used * Feat #3: Added implementation and tests for JSONReader not accepting specific escape sequence representing in strict mode * Test #3: Simplify test cases by removing unnecessary array * Feat #3: Improve error by including the illegal character * Feat #5: JsonReader does not allow unespaced control flow characters in strict mode * Test #5: Test unespaced control flow characters in strict mode * Feat #4: Disallow espaced newline character in strict mode * Test #4: Add tests for (dis)allowing newline character depensding on strictness * Test #5: Test case for unescaped control char in non-strict mode * Test #2: Simplify test cases * Feat #13: Change leniency API to Strictness enum in JsonReader, Gson, and GsonBuilder * Feat #15: Change JsonWriter API to also use Strictness * Test #15: Test Strictness in JsonWriter API * Doc #15: Add and update documentation for Strictness in JsonWriter API * refactor #12: Fixed typos and empty catch brackets in tests * refactor #12: Resolved importing wildcards, made some lines adhere to Google java style * #5 Add test case for unescaped control characters * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue --------- Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * Doc #17: Add and change javadoc of public methods * Doc #17: Update JavaDoc in JsonReader and Strictness * Doc #17: Update JavaDoc in Gson and GsonBuilder * Test #34: Add tests for setting strictness through GsonBuilder * Fix: Add Fix broken test * Fix: Invalid JavaDoc in Gson.java * Doc #17: update outdated javadoc * #37: Resolve more PR feedback * Fix #37: Resolve various PR comments * Fix #37: Resolve various PR comments * Refactor #35: Refactor JsonReader#peekKeyword to reduce the amount of strictness checks (#39) * Doc #40: Update JavaDoc based on PR feedback * Doc #40: Update old RFC in GsonBuilder documentation * Doc #40: Fix formatting error in JavaDoc * Doc #40: Add tests for setting strictness and lenient to JsonReaderTest * Test #43: Changed tests to make use of assertThrows * test #43: Changed tests to make use of assertThrows as per feedback * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * test #43: Resolve PR recommendations * Test #43: Mini change to TC * Test #43: Mini change to TC --------- Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * doc #46: Resolved comments in main PR * Feat #45: Change Gson.fromJson and Gson.toJson to be strict when the provided writer/reader is strict * Fix #45: Small type * Update gson/src/test/java/com/google/gson/stream/JsonReaderTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Update gson/src/main/java/com/google/gson/GsonBuilder.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Fix #45: Resolve various comments by eamonmcmanus * Strictness mode follow-up * Update Troubleshooting.md and Gson default lenient mode documentation * Always use GSON strictness when set. * Rename Strictness.DEFAULT to Strictness.LEGACY_STRICT * Update JavaDoc with new strictness functionality * Replace default with legacy strict for JsonReader javadoc * Add JSONReader test cases for U2028 and U2029 * Refactor JSONReader#peekKeyWord() based on @eamonmcmanus's suggestion * Deprecate setLenient in favor of setStrictness --------- Co-authored-by: Carl Peterson <unknown> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Strictness follow-up (#2408) * Strictness mode follow-up - Remove mentions of `null` Gson strictness; this is an implementation detail - Fix incorrect / outdated documentation - Reduce links to RFC; if there is already a link to it in a previous sentence don't link to it again - Extend and update tests - Minor punctuation changes in documentation for consistency * Deprecate `setLenient` methods * `strictness2` fixes & improvements (#2456) * Adjust ProGuard default rules and shrinking tests (#2420) * Adjust ProGuard default rules and shrinking tests * Adjust comment * Add shrinking test for class without no-args constructor; improve docs * Improve Unsafe mention in Troubleshooting Guide * Improve comment for `-if class *` * Bump com.google.guava:guava from 32.0.1-jre to 32.1.1-jre (#2444) Bumps [com.google.guava:guava](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Bump com.google.guava:guava-testlib from 32.0.1-jre to 32.1.1-jre (#2443) Bumps [com.google.guava:guava-testlib](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava-testlib dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Support non-generic type for `TypeToken.getParameterized` for legacy reasons (#2447) This partially restores the behavior before a589ef20087b4b0f1ec3048d3ceaef1eedccd09d, except that back then for a non-generic type a bogus `TypeToken(ParameterizedType)` was created, whereas now a `TypeToken(Class)` is created instead. * Fixed Typo in GsonBuilder.java (#2449) * Make date-formatting tests less fragile with regular expressions. (#2450) * Make date-formatting tests less fragile with regular expressions. This is not great. We should really ensure that formatted dates are the same regardless of JDK version. There is code that attempts to do that but it is not really effective. So for now we fudge around the differences by using regular expressions to paper over the differences. * Temporarily add test-debugging code. * Another attempt at debugging a test failure. * Fix pattern in assertion. * Modification in test cases (#2454) * Fixed Typo in GsonBuilder.java * Suggestions on Test cases * Modified test cases using assertThrows method (JUnit) * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/GsonTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> --------- Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Minor follow-up changes --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Éamonn McManus <emcmanus@google.com> Co-authored-by: Wonil <cwi5525@naver.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Marten <martenvoorberg@gmail.com> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Wonil <cwi5525@naver.com>
2023-07-30 18:20:32 +02:00
* <h2 id="default-lenient">JSON Strictness handling</h2>
*
* For legacy reasons most of the {@code Gson} methods allow JSON data which does not comply with
Strict mode for JSON parsing, contributed by @marten-voorberg. (#2437) * Strict mode for JSON parsing (#2323) * Feat #6: Add strict flag to Gson and GsonBuilder * Test #2: Add failing tests for capitalized keywords * Feat #2: JsonReader does not read (partially) capitalized keywords if strict mode is used * Feat #3: Added implementation and tests for JSONReader not accepting specific escape sequence representing in strict mode * Test #3: Simplify test cases by removing unnecessary array * Feat #3: Improve error by including the illegal character * Feat #5: JsonReader does not allow unespaced control flow characters in strict mode * Test #5: Test unespaced control flow characters in strict mode * Feat #4: Disallow espaced newline character in strict mode * Test #4: Add tests for (dis)allowing newline character depensding on strictness * Test #5: Test case for unescaped control char in non-strict mode * Test #2: Simplify test cases * Feat #13: Change leniency API to Strictness enum in JsonReader, Gson, and GsonBuilder * Feat #15: Change JsonWriter API to also use Strictness * Test #15: Test Strictness in JsonWriter API * Doc #15: Add and update documentation for Strictness in JsonWriter API * refactor #12: Fixed typos and empty catch brackets in tests * refactor #12: Resolved importing wildcards, made some lines adhere to Google java style * #5 Add test case for unescaped control characters * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue --------- Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * Doc #17: Add and change javadoc of public methods * Doc #17: Update JavaDoc in JsonReader and Strictness * Doc #17: Update JavaDoc in Gson and GsonBuilder * Test #34: Add tests for setting strictness through GsonBuilder * Fix: Add Fix broken test * Fix: Invalid JavaDoc in Gson.java * Doc #17: update outdated javadoc * #37: Resolve more PR feedback * Fix #37: Resolve various PR comments * Fix #37: Resolve various PR comments * Refactor #35: Refactor JsonReader#peekKeyword to reduce the amount of strictness checks (#39) * Doc #40: Update JavaDoc based on PR feedback * Doc #40: Update old RFC in GsonBuilder documentation * Doc #40: Fix formatting error in JavaDoc * Doc #40: Add tests for setting strictness and lenient to JsonReaderTest * Test #43: Changed tests to make use of assertThrows * test #43: Changed tests to make use of assertThrows as per feedback * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * test #43: Resolve PR recommendations * Test #43: Mini change to TC * Test #43: Mini change to TC --------- Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * doc #46: Resolved comments in main PR * Feat #45: Change Gson.fromJson and Gson.toJson to be strict when the provided writer/reader is strict * Fix #45: Small type * Update gson/src/test/java/com/google/gson/stream/JsonReaderTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Update gson/src/main/java/com/google/gson/GsonBuilder.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Fix #45: Resolve various comments by eamonmcmanus * Strictness mode follow-up * Update Troubleshooting.md and Gson default lenient mode documentation * Always use GSON strictness when set. * Rename Strictness.DEFAULT to Strictness.LEGACY_STRICT * Update JavaDoc with new strictness functionality * Replace default with legacy strict for JsonReader javadoc * Add JSONReader test cases for U2028 and U2029 * Refactor JSONReader#peekKeyWord() based on @eamonmcmanus's suggestion * Deprecate setLenient in favor of setStrictness --------- Co-authored-by: Carl Peterson <unknown> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Strictness follow-up (#2408) * Strictness mode follow-up - Remove mentions of `null` Gson strictness; this is an implementation detail - Fix incorrect / outdated documentation - Reduce links to RFC; if there is already a link to it in a previous sentence don't link to it again - Extend and update tests - Minor punctuation changes in documentation for consistency * Deprecate `setLenient` methods * `strictness2` fixes & improvements (#2456) * Adjust ProGuard default rules and shrinking tests (#2420) * Adjust ProGuard default rules and shrinking tests * Adjust comment * Add shrinking test for class without no-args constructor; improve docs * Improve Unsafe mention in Troubleshooting Guide * Improve comment for `-if class *` * Bump com.google.guava:guava from 32.0.1-jre to 32.1.1-jre (#2444) Bumps [com.google.guava:guava](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Bump com.google.guava:guava-testlib from 32.0.1-jre to 32.1.1-jre (#2443) Bumps [com.google.guava:guava-testlib](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava-testlib dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Support non-generic type for `TypeToken.getParameterized` for legacy reasons (#2447) This partially restores the behavior before a589ef20087b4b0f1ec3048d3ceaef1eedccd09d, except that back then for a non-generic type a bogus `TypeToken(ParameterizedType)` was created, whereas now a `TypeToken(Class)` is created instead. * Fixed Typo in GsonBuilder.java (#2449) * Make date-formatting tests less fragile with regular expressions. (#2450) * Make date-formatting tests less fragile with regular expressions. This is not great. We should really ensure that formatted dates are the same regardless of JDK version. There is code that attempts to do that but it is not really effective. So for now we fudge around the differences by using regular expressions to paper over the differences. * Temporarily add test-debugging code. * Another attempt at debugging a test failure. * Fix pattern in assertion. * Modification in test cases (#2454) * Fixed Typo in GsonBuilder.java * Suggestions on Test cases * Modified test cases using assertThrows method (JUnit) * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/GsonTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> --------- Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Minor follow-up changes --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Éamonn McManus <emcmanus@google.com> Co-authored-by: Wonil <cwi5525@naver.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Marten <martenvoorberg@gmail.com> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Wonil <cwi5525@naver.com>
2023-07-30 18:20:32 +02:00
* 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)}.
*
Strict mode for JSON parsing, contributed by @marten-voorberg. (#2437) * Strict mode for JSON parsing (#2323) * Feat #6: Add strict flag to Gson and GsonBuilder * Test #2: Add failing tests for capitalized keywords * Feat #2: JsonReader does not read (partially) capitalized keywords if strict mode is used * Feat #3: Added implementation and tests for JSONReader not accepting specific escape sequence representing in strict mode * Test #3: Simplify test cases by removing unnecessary array * Feat #3: Improve error by including the illegal character * Feat #5: JsonReader does not allow unespaced control flow characters in strict mode * Test #5: Test unespaced control flow characters in strict mode * Feat #4: Disallow espaced newline character in strict mode * Test #4: Add tests for (dis)allowing newline character depensding on strictness * Test #5: Test case for unescaped control char in non-strict mode * Test #2: Simplify test cases * Feat #13: Change leniency API to Strictness enum in JsonReader, Gson, and GsonBuilder * Feat #15: Change JsonWriter API to also use Strictness * Test #15: Test Strictness in JsonWriter API * Doc #15: Add and update documentation for Strictness in JsonWriter API * refactor #12: Fixed typos and empty catch brackets in tests * refactor #12: Resolved importing wildcards, made some lines adhere to Google java style * #5 Add test case for unescaped control characters * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue --------- Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * Doc #17: Add and change javadoc of public methods * Doc #17: Update JavaDoc in JsonReader and Strictness * Doc #17: Update JavaDoc in Gson and GsonBuilder * Test #34: Add tests for setting strictness through GsonBuilder * Fix: Add Fix broken test * Fix: Invalid JavaDoc in Gson.java * Doc #17: update outdated javadoc * #37: Resolve more PR feedback * Fix #37: Resolve various PR comments * Fix #37: Resolve various PR comments * Refactor #35: Refactor JsonReader#peekKeyword to reduce the amount of strictness checks (#39) * Doc #40: Update JavaDoc based on PR feedback * Doc #40: Update old RFC in GsonBuilder documentation * Doc #40: Fix formatting error in JavaDoc * Doc #40: Add tests for setting strictness and lenient to JsonReaderTest * Test #43: Changed tests to make use of assertThrows * test #43: Changed tests to make use of assertThrows as per feedback * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * test #43: Resolve PR recommendations * Test #43: Mini change to TC * Test #43: Mini change to TC --------- Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * doc #46: Resolved comments in main PR * Feat #45: Change Gson.fromJson and Gson.toJson to be strict when the provided writer/reader is strict * Fix #45: Small type * Update gson/src/test/java/com/google/gson/stream/JsonReaderTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Update gson/src/main/java/com/google/gson/GsonBuilder.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Fix #45: Resolve various comments by eamonmcmanus * Strictness mode follow-up * Update Troubleshooting.md and Gson default lenient mode documentation * Always use GSON strictness when set. * Rename Strictness.DEFAULT to Strictness.LEGACY_STRICT * Update JavaDoc with new strictness functionality * Replace default with legacy strict for JsonReader javadoc * Add JSONReader test cases for U2028 and U2029 * Refactor JSONReader#peekKeyWord() based on @eamonmcmanus's suggestion * Deprecate setLenient in favor of setStrictness --------- Co-authored-by: Carl Peterson <unknown> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Strictness follow-up (#2408) * Strictness mode follow-up - Remove mentions of `null` Gson strictness; this is an implementation detail - Fix incorrect / outdated documentation - Reduce links to RFC; if there is already a link to it in a previous sentence don't link to it again - Extend and update tests - Minor punctuation changes in documentation for consistency * Deprecate `setLenient` methods * `strictness2` fixes & improvements (#2456) * Adjust ProGuard default rules and shrinking tests (#2420) * Adjust ProGuard default rules and shrinking tests * Adjust comment * Add shrinking test for class without no-args constructor; improve docs * Improve Unsafe mention in Troubleshooting Guide * Improve comment for `-if class *` * Bump com.google.guava:guava from 32.0.1-jre to 32.1.1-jre (#2444) Bumps [com.google.guava:guava](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Bump com.google.guava:guava-testlib from 32.0.1-jre to 32.1.1-jre (#2443) Bumps [com.google.guava:guava-testlib](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava-testlib dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Support non-generic type for `TypeToken.getParameterized` for legacy reasons (#2447) This partially restores the behavior before a589ef20087b4b0f1ec3048d3ceaef1eedccd09d, except that back then for a non-generic type a bogus `TypeToken(ParameterizedType)` was created, whereas now a `TypeToken(Class)` is created instead. * Fixed Typo in GsonBuilder.java (#2449) * Make date-formatting tests less fragile with regular expressions. (#2450) * Make date-formatting tests less fragile with regular expressions. This is not great. We should really ensure that formatted dates are the same regardless of JDK version. There is code that attempts to do that but it is not really effective. So for now we fudge around the differences by using regular expressions to paper over the differences. * Temporarily add test-debugging code. * Another attempt at debugging a test failure. * Fix pattern in assertion. * Modification in test cases (#2454) * Fixed Typo in GsonBuilder.java * Suggestions on Test cases * Modified test cases using assertThrows method (JUnit) * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/GsonTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> --------- Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Minor follow-up changes --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Éamonn McManus <emcmanus@google.com> Co-authored-by: Wonil <cwi5525@naver.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Marten <martenvoorberg@gmail.com> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Wonil <cwi5525@naver.com>
2023-07-30 18:20:32 +02:00
* <p>For older Gson versions, which don't have the strictness mode API, the following workarounds
* can be used:
*
* <h3>Serialization</h3>
*
* <ol>
* <li>Use {@link #getAdapter(Class)} to obtain the adapter for the type to be serialized
* <li>When using an existing {@code JsonWriter}, manually apply the writer settings of this
* {@code Gson} instance listed by {@link #newJsonWriter(Writer)}.<br>
* Otherwise, when not using an existing {@code JsonWriter}, use {@link
* #newJsonWriter(Writer)} to construct one.
* <li>Call {@link TypeAdapter#write(JsonWriter, Object)}
* </ol>
*
* <h3>Deserialization</h3>
*
* <ol>
* <li>Use {@link #getAdapter(Class)} to obtain the adapter for the type to be deserialized
* <li>When using an existing {@code JsonReader}, manually apply the reader settings of this
* {@code Gson} instance listed by {@link #newJsonReader(Reader)}.<br>
* Otherwise, when not using an existing {@code JsonReader}, use {@link
* #newJsonReader(Reader)} to construct one.
* <li>Call {@link TypeAdapter#read(JsonReader)}
* <li>Call {@link JsonReader#peek()} and verify that the result is {@link JsonToken#END_DOCUMENT}
* to make sure there is no trailing data
* </ol>
*
Strict mode for JSON parsing, contributed by @marten-voorberg. (#2437) * Strict mode for JSON parsing (#2323) * Feat #6: Add strict flag to Gson and GsonBuilder * Test #2: Add failing tests for capitalized keywords * Feat #2: JsonReader does not read (partially) capitalized keywords if strict mode is used * Feat #3: Added implementation and tests for JSONReader not accepting specific escape sequence representing in strict mode * Test #3: Simplify test cases by removing unnecessary array * Feat #3: Improve error by including the illegal character * Feat #5: JsonReader does not allow unespaced control flow characters in strict mode * Test #5: Test unespaced control flow characters in strict mode * Feat #4: Disallow espaced newline character in strict mode * Test #4: Add tests for (dis)allowing newline character depensding on strictness * Test #5: Test case for unescaped control char in non-strict mode * Test #2: Simplify test cases * Feat #13: Change leniency API to Strictness enum in JsonReader, Gson, and GsonBuilder * Feat #15: Change JsonWriter API to also use Strictness * Test #15: Test Strictness in JsonWriter API * Doc #15: Add and update documentation for Strictness in JsonWriter API * refactor #12: Fixed typos and empty catch brackets in tests * refactor #12: Resolved importing wildcards, made some lines adhere to Google java style * #5 Add test case for unescaped control characters * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue --------- Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * Doc #17: Add and change javadoc of public methods * Doc #17: Update JavaDoc in JsonReader and Strictness * Doc #17: Update JavaDoc in Gson and GsonBuilder * Test #34: Add tests for setting strictness through GsonBuilder * Fix: Add Fix broken test * Fix: Invalid JavaDoc in Gson.java * Doc #17: update outdated javadoc * #37: Resolve more PR feedback * Fix #37: Resolve various PR comments * Fix #37: Resolve various PR comments * Refactor #35: Refactor JsonReader#peekKeyword to reduce the amount of strictness checks (#39) * Doc #40: Update JavaDoc based on PR feedback * Doc #40: Update old RFC in GsonBuilder documentation * Doc #40: Fix formatting error in JavaDoc * Doc #40: Add tests for setting strictness and lenient to JsonReaderTest * Test #43: Changed tests to make use of assertThrows * test #43: Changed tests to make use of assertThrows as per feedback * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * test #43: Resolve PR recommendations * Test #43: Mini change to TC * Test #43: Mini change to TC --------- Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * doc #46: Resolved comments in main PR * Feat #45: Change Gson.fromJson and Gson.toJson to be strict when the provided writer/reader is strict * Fix #45: Small type * Update gson/src/test/java/com/google/gson/stream/JsonReaderTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Update gson/src/main/java/com/google/gson/GsonBuilder.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Fix #45: Resolve various comments by eamonmcmanus * Strictness mode follow-up * Update Troubleshooting.md and Gson default lenient mode documentation * Always use GSON strictness when set. * Rename Strictness.DEFAULT to Strictness.LEGACY_STRICT * Update JavaDoc with new strictness functionality * Replace default with legacy strict for JsonReader javadoc * Add JSONReader test cases for U2028 and U2029 * Refactor JSONReader#peekKeyWord() based on @eamonmcmanus's suggestion * Deprecate setLenient in favor of setStrictness --------- Co-authored-by: Carl Peterson <unknown> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Strictness follow-up (#2408) * Strictness mode follow-up - Remove mentions of `null` Gson strictness; this is an implementation detail - Fix incorrect / outdated documentation - Reduce links to RFC; if there is already a link to it in a previous sentence don't link to it again - Extend and update tests - Minor punctuation changes in documentation for consistency * Deprecate `setLenient` methods * `strictness2` fixes & improvements (#2456) * Adjust ProGuard default rules and shrinking tests (#2420) * Adjust ProGuard default rules and shrinking tests * Adjust comment * Add shrinking test for class without no-args constructor; improve docs * Improve Unsafe mention in Troubleshooting Guide * Improve comment for `-if class *` * Bump com.google.guava:guava from 32.0.1-jre to 32.1.1-jre (#2444) Bumps [com.google.guava:guava](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Bump com.google.guava:guava-testlib from 32.0.1-jre to 32.1.1-jre (#2443) Bumps [com.google.guava:guava-testlib](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava-testlib dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Support non-generic type for `TypeToken.getParameterized` for legacy reasons (#2447) This partially restores the behavior before a589ef20087b4b0f1ec3048d3ceaef1eedccd09d, except that back then for a non-generic type a bogus `TypeToken(ParameterizedType)` was created, whereas now a `TypeToken(Class)` is created instead. * Fixed Typo in GsonBuilder.java (#2449) * Make date-formatting tests less fragile with regular expressions. (#2450) * Make date-formatting tests less fragile with regular expressions. This is not great. We should really ensure that formatted dates are the same regardless of JDK version. There is code that attempts to do that but it is not really effective. So for now we fudge around the differences by using regular expressions to paper over the differences. * Temporarily add test-debugging code. * Another attempt at debugging a test failure. * Fix pattern in assertion. * Modification in test cases (#2454) * Fixed Typo in GsonBuilder.java * Suggestions on Test cases * Modified test cases using assertThrows method (JUnit) * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/GsonTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> --------- Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Minor follow-up changes --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Éamonn McManus <emcmanus@google.com> Co-authored-by: Wonil <cwi5525@naver.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Marten <martenvoorberg@gmail.com> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Wonil <cwi5525@naver.com>
2023-07-30 18:20:32 +02:00
* 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.
*
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* @see TypeToken
2008-09-01 05:13:32 +02:00
* @author Inderjeet Singh
* @author Joel Leitch
* @author Jesse Wilson
2008-09-01 05:13:32 +02:00
*/
public final class Gson {
/**
* 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.
*
* <p>The map stores the type adapters for ongoing {@code getAdapter} calls, with the type token
* provided to {@code getAdapter} as key and either {@code FutureTypeAdapter} or a regular {@code
* TypeAdapter} as value.
*/
Fix error prone warnings (#2316) * Fix `OperatorPrecedence` warn in `JsonWriter#close` * Fix `ReferenceEquality` warn in `LinkedTreeMap#replaceInParent` * Fix `UnnecessaryParentheses` warn in `LinkedTreeMap#replaceInParent` * Fix `ReferenceEquality` warn in `LinkedTreeMap#hasNext` * Fix `ReferenceEquality` warn in `LinkedTreeMap#nextNode` * Adds `error_prone_annotations` to the `pom.xml` of `gson` * Fix `InlineMeSuggester` warns in `JsonParser` * Fix `UnnecessaryParentheses` warns in `ConstructorConstructor#newDefaultImplementationConstructor` * Fix `ThreadLocalUsage` warn in `Gson` * Fix `JdkObsolete` warn in `GsonBuilder` * Fix `ReferenceEquality` warn in `LazilyParsedNumber#equals` * Fix `OperatorPrecedence` warn in `TreeTypeAdapter#create` * Fix `OperatorPrecedence` warn in `ArrayTypeAdapter` * Fix `UnnecessaryParentheses` warn in `TypeAdapters` * Adds `-XepExcludedPaths` flag to ErrorProne plugin to exclude tests and proto path * Fix `ClassNewInstance` warn in `InterceptorAdapter` * Fix `ThreadLocalUsage` warn in `GraphAdapterBuilder` * Fix `JdkObsolete` warn in `GraphAdapterBuilder` * Revert "Adds `error_prone_annotations` to the `pom.xml` of `gson`" This reverts commit 14af14dfa23b46a54f4855a70ccf2b0a2cdc3e3f. * Revert "Fix `InlineMeSuggester` warns in `JsonParser`" This reverts commit 095bfd517e06510e4cc9cc6b1aac58ad9bf3038a. * Adds `@SuppressWarnings("ThreadLocalUsage")` * Fix `OperatorPrecedence` in `JsonWriter` * Revert "Fix `ReferenceEquality` warn in `LinkedTreeMap#nextNode`" This reverts commit 387746c7f7e3d0943c8f80501f5d9c3710f4862e. * Adds `@SuppressWarnings("ReferenceEquality")` * Adds `guava-testlib` to the gson `pom.xml` * `@SuppressWarnings("TruthSelfEquals")` removed to use `EqualsTester()`
2023-02-15 14:18:43 +01:00
@SuppressWarnings("ThreadLocalUsage")
private final ThreadLocal<Map<TypeToken<?>, TypeAdapter<?>>> threadLocalAdapterResults =
new ThreadLocal<>();
private final ConcurrentMap<TypeToken<?>, TypeAdapter<?>> typeTokenCache =
new ConcurrentHashMap<>();
Down to 22 failing tests. Consolidated all of the different code paths that we use to construct instances. We now have an ObjectConstructor class that knows what type it constructs; this means that we don't need to ever do reflection to lookup a constructor at construction time. Cleaned up some buggy type adapters, particularly around handling of null. Removed dead code for object graph navigation. Moved some classes into 'internal' so they are visible to the 'bind' subpackage. Turned some TypeAdapterFactory/TypeAdapter pairs inside out so that the TypeAdapter is now the inner class. This is necessary so that the factories can take parameters. Added an API to request the 'next' type adapter for a type. This allows type adapters to compose other type adapters. We're using this in two places: - where the user has excluded a type from serialization but not deserialization, we need to use the "default" deserialization but interpose null on serialization. We create a type adapter that delegates for one and returns null for the other. - similarly when a DOM type serializer is registered but no deserializer, or vice versa. This is the biggest change to the MiniGson core. For backwards compatibility, return null for the empty string. Simplify JsonSerializationContext/JsonDeserializationContext to simply call through to GSON. SerializeDefault is currently unsupported. More useful error messages when calling getAsBoolean on a JsonNull. Remove currently unused MemoryRefStack. We might need this back again, though wiring it back in will be much more difficult because we don't interject ourselves between the users' various type adapters.
2011-09-11 09:04:56 +02:00
private final ConstructorConstructor constructorConstructor;
2016-06-15 01:34:34 +02:00
private final JsonAdapterAnnotationTypeAdapterFactory jsonAdapterFactory;
final List<TypeAdapterFactory> factories;
final Excluder excluder;
final FieldNamingStrategy fieldNamingStrategy;
final Map<Type, InstanceCreator<?>> instanceCreators;
final boolean serializeNulls;
final boolean complexMapKeySerialization;
2021-04-21 08:31:23 +02:00
final boolean duplicateMapKeyDeserialization;
final boolean generateNonExecutableJson;
final boolean htmlSafe;
final FormattingStyle formattingStyle;
Strict mode for JSON parsing, contributed by @marten-voorberg. (#2437) * Strict mode for JSON parsing (#2323) * Feat #6: Add strict flag to Gson and GsonBuilder * Test #2: Add failing tests for capitalized keywords * Feat #2: JsonReader does not read (partially) capitalized keywords if strict mode is used * Feat #3: Added implementation and tests for JSONReader not accepting specific escape sequence representing in strict mode * Test #3: Simplify test cases by removing unnecessary array * Feat #3: Improve error by including the illegal character * Feat #5: JsonReader does not allow unespaced control flow characters in strict mode * Test #5: Test unespaced control flow characters in strict mode * Feat #4: Disallow espaced newline character in strict mode * Test #4: Add tests for (dis)allowing newline character depensding on strictness * Test #5: Test case for unescaped control char in non-strict mode * Test #2: Simplify test cases * Feat #13: Change leniency API to Strictness enum in JsonReader, Gson, and GsonBuilder * Feat #15: Change JsonWriter API to also use Strictness * Test #15: Test Strictness in JsonWriter API * Doc #15: Add and update documentation for Strictness in JsonWriter API * refactor #12: Fixed typos and empty catch brackets in tests * refactor #12: Resolved importing wildcards, made some lines adhere to Google java style * #5 Add test case for unescaped control characters * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue --------- Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * Doc #17: Add and change javadoc of public methods * Doc #17: Update JavaDoc in JsonReader and Strictness * Doc #17: Update JavaDoc in Gson and GsonBuilder * Test #34: Add tests for setting strictness through GsonBuilder * Fix: Add Fix broken test * Fix: Invalid JavaDoc in Gson.java * Doc #17: update outdated javadoc * #37: Resolve more PR feedback * Fix #37: Resolve various PR comments * Fix #37: Resolve various PR comments * Refactor #35: Refactor JsonReader#peekKeyword to reduce the amount of strictness checks (#39) * Doc #40: Update JavaDoc based on PR feedback * Doc #40: Update old RFC in GsonBuilder documentation * Doc #40: Fix formatting error in JavaDoc * Doc #40: Add tests for setting strictness and lenient to JsonReaderTest * Test #43: Changed tests to make use of assertThrows * test #43: Changed tests to make use of assertThrows as per feedback * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * test #43: Resolve PR recommendations * Test #43: Mini change to TC * Test #43: Mini change to TC --------- Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * doc #46: Resolved comments in main PR * Feat #45: Change Gson.fromJson and Gson.toJson to be strict when the provided writer/reader is strict * Fix #45: Small type * Update gson/src/test/java/com/google/gson/stream/JsonReaderTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Update gson/src/main/java/com/google/gson/GsonBuilder.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Fix #45: Resolve various comments by eamonmcmanus * Strictness mode follow-up * Update Troubleshooting.md and Gson default lenient mode documentation * Always use GSON strictness when set. * Rename Strictness.DEFAULT to Strictness.LEGACY_STRICT * Update JavaDoc with new strictness functionality * Replace default with legacy strict for JsonReader javadoc * Add JSONReader test cases for U2028 and U2029 * Refactor JSONReader#peekKeyWord() based on @eamonmcmanus's suggestion * Deprecate setLenient in favor of setStrictness --------- Co-authored-by: Carl Peterson <unknown> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Strictness follow-up (#2408) * Strictness mode follow-up - Remove mentions of `null` Gson strictness; this is an implementation detail - Fix incorrect / outdated documentation - Reduce links to RFC; if there is already a link to it in a previous sentence don't link to it again - Extend and update tests - Minor punctuation changes in documentation for consistency * Deprecate `setLenient` methods * `strictness2` fixes & improvements (#2456) * Adjust ProGuard default rules and shrinking tests (#2420) * Adjust ProGuard default rules and shrinking tests * Adjust comment * Add shrinking test for class without no-args constructor; improve docs * Improve Unsafe mention in Troubleshooting Guide * Improve comment for `-if class *` * Bump com.google.guava:guava from 32.0.1-jre to 32.1.1-jre (#2444) Bumps [com.google.guava:guava](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Bump com.google.guava:guava-testlib from 32.0.1-jre to 32.1.1-jre (#2443) Bumps [com.google.guava:guava-testlib](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava-testlib dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Support non-generic type for `TypeToken.getParameterized` for legacy reasons (#2447) This partially restores the behavior before a589ef20087b4b0f1ec3048d3ceaef1eedccd09d, except that back then for a non-generic type a bogus `TypeToken(ParameterizedType)` was created, whereas now a `TypeToken(Class)` is created instead. * Fixed Typo in GsonBuilder.java (#2449) * Make date-formatting tests less fragile with regular expressions. (#2450) * Make date-formatting tests less fragile with regular expressions. This is not great. We should really ensure that formatted dates are the same regardless of JDK version. There is code that attempts to do that but it is not really effective. So for now we fudge around the differences by using regular expressions to paper over the differences. * Temporarily add test-debugging code. * Another attempt at debugging a test failure. * Fix pattern in assertion. * Modification in test cases (#2454) * Fixed Typo in GsonBuilder.java * Suggestions on Test cases * Modified test cases using assertThrows method (JUnit) * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/GsonTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> --------- Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Minor follow-up changes --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Éamonn McManus <emcmanus@google.com> Co-authored-by: Wonil <cwi5525@naver.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Marten <martenvoorberg@gmail.com> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Wonil <cwi5525@naver.com>
2023-07-30 18:20:32 +02:00
final Strictness strictness;
2022-05-17 21:20:10 +02:00
final boolean omitQuotes;
final boolean serializeSpecialFloatingPointValues;
final boolean useJdkUnsafe;
final String datePattern;
final int dateStyle;
final int timeStyle;
final LongSerializationPolicy longSerializationPolicy;
final List<TypeAdapterFactory> builderFactories;
final List<TypeAdapterFactory> builderHierarchyFactories;
final ToNumberStrategy objectToNumberStrategy;
final ToNumberStrategy numberToNumberStrategy;
final List<ReflectionAccessFilter> reflectionFilters;
2008-09-01 05:13:32 +02:00
/**
* Constructs a Gson object with default configuration. The default configuration has the
* following settings:
*
2008-09-01 05:13:32 +02:00
* <ul>
Perform minor code clean-up (#2544) * Perform minor code clean-up Notable changes: - Replace most usages of `<code>` with `{@code ...}` in Javadoc - Add proper summary sentence to `GsonBuilder.enableComplexMapKeySerialization` - Extend documentation for `GsonBuilder.setDateFormat` methods - Fix `TypeToken.isAssignableFrom(Type)` throwing AssertionError in some cases Maybe the method should not throw an exception in the first place, but it might not matter much since it is deprecated already anyway. - Remove outdated `throws NumberFormatException` from internal `JsonReader.nextQuotedValue`; the behavior had been changed by 85ebaf7c3553a5d5c058fd6067824a7c5258d07f - Fix incorrect documentation on JsonScope fields - Fix unit tests having 'expected' and 'actual' switched - Use dedicated Truth methods instead of `isTrue()` / `isFalse()` - Use common helper methods in JsonWriterTest to avoid duplication * Implement `toString()` for ReflectionAccessFilter constants * Address most of the review comments * Add comment about `source.scm.tag=HEAD` warning Actually it looks like the warning is not actually caused by usage of `HEAD` as value, but rather because the project has a snapshot version during development (which is expected though), see https://github.com/apache/maven-artifact-plugin/blob/maven-artifact-plugin-3.5.0/src/main/java/org/apache/maven/plugins/artifact/buildinfo/BuildInfoWriter.java#L140 But this is not a problem either since during release a non-snapshot version is used.
2023-11-19 18:01:19 +01:00
* <li>The JSON generated by {@code toJson} methods is in compact representation. This means
* that all the unneeded white-space is removed. You can change this behavior with {@link
* GsonBuilder#setPrettyPrinting()}.
* <li>When the JSON generated contains more than one line, the kind of newline and indent to
* use can be configured with {@link GsonBuilder#setFormattingStyle(FormattingStyle)}.
2008-09-01 05:13:32 +02:00
* <li>The generated JSON omits all the fields that are null. Note that nulls in arrays are kept
* as is since an array is an ordered list. Moreover, if a field is not null, but its
* generated JSON is empty, the field is kept. You can configure Gson to serialize null
* values by setting {@link GsonBuilder#serializeNulls()}.
* <li>Gson provides default serialization and deserialization for Enums, {@link Map}, {@link
* java.net.URL}, {@link java.net.URI}, {@link java.util.Locale}, {@link java.util.Date},
* {@link java.math.BigDecimal}, and {@link java.math.BigInteger} classes. If you would
* prefer to change the default representation, you can do so by registering a type adapter
* through {@link GsonBuilder#registerTypeAdapter(Type, Object)}.
* <li>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
2008-09-01 05:13:32 +02:00
* GsonBuilder#setDateFormat(String)}.
* <li>By default, Gson ignores the {@link com.google.gson.annotations.Expose} annotation. You
* can enable Gson to serialize/deserialize only those fields marked with this annotation
* through {@link GsonBuilder#excludeFieldsWithoutExposeAnnotation()}.
* <li>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)}.
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* <li>The default field naming policy for the output JSON is same as in Java. So, a Java class
Perform minor code clean-up (#2544) * Perform minor code clean-up Notable changes: - Replace most usages of `<code>` with `{@code ...}` in Javadoc - Add proper summary sentence to `GsonBuilder.enableComplexMapKeySerialization` - Extend documentation for `GsonBuilder.setDateFormat` methods - Fix `TypeToken.isAssignableFrom(Type)` throwing AssertionError in some cases Maybe the method should not throw an exception in the first place, but it might not matter much since it is deprecated already anyway. - Remove outdated `throws NumberFormatException` from internal `JsonReader.nextQuotedValue`; the behavior had been changed by 85ebaf7c3553a5d5c058fd6067824a7c5258d07f - Fix incorrect documentation on JsonScope fields - Fix unit tests having 'expected' and 'actual' switched - Use dedicated Truth methods instead of `isTrue()` / `isFalse()` - Use common helper methods in JsonWriterTest to avoid duplication * Implement `toString()` for ReflectionAccessFilter constants * Address most of the review comments * Add comment about `source.scm.tag=HEAD` warning Actually it looks like the warning is not actually caused by usage of `HEAD` as value, but rather because the project has a snapshot version during development (which is expected though), see https://github.com/apache/maven-artifact-plugin/blob/maven-artifact-plugin-3.5.0/src/main/java/org/apache/maven/plugins/artifact/buildinfo/BuildInfoWriter.java#L140 But this is not a problem either since during release a non-snapshot version is used.
2023-11-19 18:01:19 +01:00
* field {@code versionNumber} will be output as {@code "versionNumber"} in JSON. The same
* rules are applied for mapping incoming JSON to the Java classes. You can change this
* policy through {@link GsonBuilder#setFieldNamingPolicy(FieldNamingPolicy)}.
* <li>By default, Gson excludes {@code transient} or {@code static} fields from consideration
* for serialization and deserialization. You can change this behavior through {@link
* GsonBuilder#excludeFieldsWithModifiers(int...)}.
Strict mode for JSON parsing, contributed by @marten-voorberg. (#2437) * Strict mode for JSON parsing (#2323) * Feat #6: Add strict flag to Gson and GsonBuilder * Test #2: Add failing tests for capitalized keywords * Feat #2: JsonReader does not read (partially) capitalized keywords if strict mode is used * Feat #3: Added implementation and tests for JSONReader not accepting specific escape sequence representing in strict mode * Test #3: Simplify test cases by removing unnecessary array * Feat #3: Improve error by including the illegal character * Feat #5: JsonReader does not allow unespaced control flow characters in strict mode * Test #5: Test unespaced control flow characters in strict mode * Feat #4: Disallow espaced newline character in strict mode * Test #4: Add tests for (dis)allowing newline character depensding on strictness * Test #5: Test case for unescaped control char in non-strict mode * Test #2: Simplify test cases * Feat #13: Change leniency API to Strictness enum in JsonReader, Gson, and GsonBuilder * Feat #15: Change JsonWriter API to also use Strictness * Test #15: Test Strictness in JsonWriter API * Doc #15: Add and update documentation for Strictness in JsonWriter API * refactor #12: Fixed typos and empty catch brackets in tests * refactor #12: Resolved importing wildcards, made some lines adhere to Google java style * #5 Add test case for unescaped control characters * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue --------- Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * Doc #17: Add and change javadoc of public methods * Doc #17: Update JavaDoc in JsonReader and Strictness * Doc #17: Update JavaDoc in Gson and GsonBuilder * Test #34: Add tests for setting strictness through GsonBuilder * Fix: Add Fix broken test * Fix: Invalid JavaDoc in Gson.java * Doc #17: update outdated javadoc * #37: Resolve more PR feedback * Fix #37: Resolve various PR comments * Fix #37: Resolve various PR comments * Refactor #35: Refactor JsonReader#peekKeyword to reduce the amount of strictness checks (#39) * Doc #40: Update JavaDoc based on PR feedback * Doc #40: Update old RFC in GsonBuilder documentation * Doc #40: Fix formatting error in JavaDoc * Doc #40: Add tests for setting strictness and lenient to JsonReaderTest * Test #43: Changed tests to make use of assertThrows * test #43: Changed tests to make use of assertThrows as per feedback * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * test #43: Resolve PR recommendations * Test #43: Mini change to TC * Test #43: Mini change to TC --------- Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * doc #46: Resolved comments in main PR * Feat #45: Change Gson.fromJson and Gson.toJson to be strict when the provided writer/reader is strict * Fix #45: Small type * Update gson/src/test/java/com/google/gson/stream/JsonReaderTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Update gson/src/main/java/com/google/gson/GsonBuilder.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Fix #45: Resolve various comments by eamonmcmanus * Strictness mode follow-up * Update Troubleshooting.md and Gson default lenient mode documentation * Always use GSON strictness when set. * Rename Strictness.DEFAULT to Strictness.LEGACY_STRICT * Update JavaDoc with new strictness functionality * Replace default with legacy strict for JsonReader javadoc * Add JSONReader test cases for U2028 and U2029 * Refactor JSONReader#peekKeyWord() based on @eamonmcmanus's suggestion * Deprecate setLenient in favor of setStrictness --------- Co-authored-by: Carl Peterson <unknown> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Strictness follow-up (#2408) * Strictness mode follow-up - Remove mentions of `null` Gson strictness; this is an implementation detail - Fix incorrect / outdated documentation - Reduce links to RFC; if there is already a link to it in a previous sentence don't link to it again - Extend and update tests - Minor punctuation changes in documentation for consistency * Deprecate `setLenient` methods * `strictness2` fixes & improvements (#2456) * Adjust ProGuard default rules and shrinking tests (#2420) * Adjust ProGuard default rules and shrinking tests * Adjust comment * Add shrinking test for class without no-args constructor; improve docs * Improve Unsafe mention in Troubleshooting Guide * Improve comment for `-if class *` * Bump com.google.guava:guava from 32.0.1-jre to 32.1.1-jre (#2444) Bumps [com.google.guava:guava](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Bump com.google.guava:guava-testlib from 32.0.1-jre to 32.1.1-jre (#2443) Bumps [com.google.guava:guava-testlib](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava-testlib dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Support non-generic type for `TypeToken.getParameterized` for legacy reasons (#2447) This partially restores the behavior before a589ef20087b4b0f1ec3048d3ceaef1eedccd09d, except that back then for a non-generic type a bogus `TypeToken(ParameterizedType)` was created, whereas now a `TypeToken(Class)` is created instead. * Fixed Typo in GsonBuilder.java (#2449) * Make date-formatting tests less fragile with regular expressions. (#2450) * Make date-formatting tests less fragile with regular expressions. This is not great. We should really ensure that formatted dates are the same regardless of JDK version. There is code that attempts to do that but it is not really effective. So for now we fudge around the differences by using regular expressions to paper over the differences. * Temporarily add test-debugging code. * Another attempt at debugging a test failure. * Fix pattern in assertion. * Modification in test cases (#2454) * Fixed Typo in GsonBuilder.java * Suggestions on Test cases * Modified test cases using assertThrows method (JUnit) * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/GsonTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> --------- Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Minor follow-up changes --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Éamonn McManus <emcmanus@google.com> Co-authored-by: Wonil <cwi5525@naver.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Marten <martenvoorberg@gmail.com> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Wonil <cwi5525@naver.com>
2023-07-30 18:20:32 +02:00
* <li>No explicit strictness is set. You can change this by calling {@link
* GsonBuilder#setStrictness(Strictness)}.
2008-09-01 05:13:32 +02:00
* </ul>
*/
public Gson() {
this(
Excluder.DEFAULT,
Merge remote-tracking branch 'origin/main' # Conflicts: # .github/ISSUE_TEMPLATE/config.yml # .github/dependabot.yml # .github/pull_request_template.md # .github/workflows/build.yml # .github/workflows/check-android-compatibility.yml # .github/workflows/check-api-compatibility.yml # .github/workflows/cifuzz.yml # .github/workflows/codeql-analysis.yml # extras/pom.xml # extras/src/main/java/com/google/gson/extras/examples/rawcollections/RawCollectionsExample.java # extras/src/main/java/com/google/gson/graph/GraphAdapterBuilder.java # extras/src/main/java/com/google/gson/interceptors/Intercept.java # extras/src/main/java/com/google/gson/interceptors/InterceptorFactory.java # extras/src/main/java/com/google/gson/interceptors/JsonPostDeserializer.java # extras/src/main/java/com/google/gson/typeadapters/PostConstructAdapterFactory.java # extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java # extras/src/main/java/com/google/gson/typeadapters/UtcDateTypeAdapter.java # extras/src/test/java/com/google/gson/graph/GraphAdapterBuilderTest.java # extras/src/test/java/com/google/gson/interceptors/InterceptorTest.java # extras/src/test/java/com/google/gson/typeadapters/PostConstructAdapterFactoryTest.java # extras/src/test/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactoryTest.java # extras/src/test/java/com/google/gson/typeadapters/UtcDateTypeAdapterTest.java # graal-native-image-test/pom.xml # graal-native-image-test/src/test/java/com/google/gson/native_test/Java17RecordReflectionTest.java # graal-native-image-test/src/test/java/com/google/gson/native_test/ReflectionTest.java # gson/pom.xml # gson/src/main/java/com/google/gson/Gson.java # gson/src/main/java/com/google/gson/GsonBuilder.java # gson/src/main/java/com/google/gson/JsonParser.java # gson/src/main/java/com/google/gson/internal/LinkedTreeMap.java # gson/src/main/java/com/google/gson/internal/bind/DateTypeAdapter.java # gson/src/main/java/com/google/gson/internal/bind/DefaultDateTypeAdapter.java # gson/src/main/java/com/google/gson/internal/bind/MapTypeAdapterFactory.java # gson/src/main/java/com/google/gson/internal/bind/TypeAdapters.java # gson/src/main/java/com/google/gson/stream/JsonReader.java # gson/src/main/java/com/google/gson/stream/JsonTreeWriter.java # gson/src/main/java/com/google/gson/stream/JsonWriter.java # gson/src/test/java/com/google/gson/CommentsTest.java # gson/src/test/java/com/google/gson/GsonTest.java # gson/src/test/java/com/google/gson/MixedStreamTest.java # gson/src/test/java/com/google/gson/ToNumberPolicyTest.java # gson/src/test/java/com/google/gson/functional/ArrayTest.java # gson/src/test/java/com/google/gson/functional/ConcurrencyTest.java # gson/src/test/java/com/google/gson/functional/CustomDeserializerTest.java # gson/src/test/java/com/google/gson/functional/CustomTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/DefaultTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/EnumWithObfuscatedTest.java # gson/src/test/java/com/google/gson/functional/ExposeFieldsTest.java # gson/src/test/java/com/google/gson/functional/FormattingStyleTest.java # gson/src/test/java/com/google/gson/functional/InstanceCreatorTest.java # gson/src/test/java/com/google/gson/functional/InternationalizationTest.java # gson/src/test/java/com/google/gson/functional/Java17RecordTest.java # gson/src/test/java/com/google/gson/functional/JavaUtilConcurrentAtomicTest.java # gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnClassesTest.java # gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnFieldsTest.java # gson/src/test/java/com/google/gson/functional/JsonParserTest.java # gson/src/test/java/com/google/gson/functional/NullObjectAndFieldTest.java # gson/src/test/java/com/google/gson/functional/ObjectTest.java # gson/src/test/java/com/google/gson/functional/PrimitiveTest.java # gson/src/test/java/com/google/gson/functional/ReflectionAccessTest.java # gson/src/test/java/com/google/gson/functional/StreamingTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/TreeTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/TypeAdapterPrecedenceTest.java # gson/src/test/java/com/google/gson/internal/bind/Java17ReflectiveTypeAdapterFactoryTest.java # gson/src/test/java/com/google/gson/internal/bind/JsonTreeReaderTest.java # gson/src/test/java/com/google/gson/internal/bind/JsonTreeWriterTest.java # gson/src/test/java/com/google/gson/internal/reflect/Java17ReflectionHelperTest.java # gson/src/test/java/com/google/gson/stream/JsonReaderTest.java # metrics/pom.xml # metrics/src/main/java/com/google/gson/metrics/BagOfPrimitives.java # metrics/src/main/java/com/google/gson/metrics/BagOfPrimitivesDeserializationBenchmark.java # metrics/src/main/java/com/google/gson/metrics/CollectionsDeserializationBenchmark.java # metrics/src/main/java/com/google/gson/metrics/NonUploadingCaliperRunner.java # metrics/src/main/java/com/google/gson/metrics/ParseBenchmark.java # metrics/src/main/java/com/google/gson/metrics/SerializationBenchmark.java # pom.xml # proto/pom.xml # proto/src/main/java/com/google/gson/protobuf/ProtoTypeAdapter.java # proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithAnnotationsTest.java # proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithComplexAndRepeatedFieldsTest.java # proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithPrimitiveTypesTest.java # shrinker-test/pom.xml # shrinker-test/src/main/java/com/example/ClassWithExposeAnnotation.java # shrinker-test/src/main/java/com/example/ClassWithHasArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithJsonAdapterAnnotation.java # shrinker-test/src/main/java/com/example/ClassWithNoArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithUnreferencedHasArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithUnreferencedNoArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithVersionAnnotations.java # shrinker-test/src/main/java/com/example/GenericClasses.java # shrinker-test/src/main/java/com/example/Main.java # shrinker-test/src/main/java/com/example/NoSerializedNameMain.java # shrinker-test/src/main/java/com/example/TestExecutor.java # shrinker-test/src/main/java/com/example/UnusedClass.java # shrinker-test/src/test/java/com/google/gson/it/ShrinkingIT.java
2024-03-12 12:56:07 +01:00
DefaultConfig.DEFAULT_FIELD_NAMING_STRATEGY,
Collections.<Type, InstanceCreator<?>>emptyMap(),
Merge remote-tracking branch 'origin/main' # Conflicts: # .github/ISSUE_TEMPLATE/config.yml # .github/dependabot.yml # .github/pull_request_template.md # .github/workflows/build.yml # .github/workflows/check-android-compatibility.yml # .github/workflows/check-api-compatibility.yml # .github/workflows/cifuzz.yml # .github/workflows/codeql-analysis.yml # extras/pom.xml # extras/src/main/java/com/google/gson/extras/examples/rawcollections/RawCollectionsExample.java # extras/src/main/java/com/google/gson/graph/GraphAdapterBuilder.java # extras/src/main/java/com/google/gson/interceptors/Intercept.java # extras/src/main/java/com/google/gson/interceptors/InterceptorFactory.java # extras/src/main/java/com/google/gson/interceptors/JsonPostDeserializer.java # extras/src/main/java/com/google/gson/typeadapters/PostConstructAdapterFactory.java # extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java # extras/src/main/java/com/google/gson/typeadapters/UtcDateTypeAdapter.java # extras/src/test/java/com/google/gson/graph/GraphAdapterBuilderTest.java # extras/src/test/java/com/google/gson/interceptors/InterceptorTest.java # extras/src/test/java/com/google/gson/typeadapters/PostConstructAdapterFactoryTest.java # extras/src/test/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactoryTest.java # extras/src/test/java/com/google/gson/typeadapters/UtcDateTypeAdapterTest.java # graal-native-image-test/pom.xml # graal-native-image-test/src/test/java/com/google/gson/native_test/Java17RecordReflectionTest.java # graal-native-image-test/src/test/java/com/google/gson/native_test/ReflectionTest.java # gson/pom.xml # gson/src/main/java/com/google/gson/Gson.java # gson/src/main/java/com/google/gson/GsonBuilder.java # gson/src/main/java/com/google/gson/JsonParser.java # gson/src/main/java/com/google/gson/internal/LinkedTreeMap.java # gson/src/main/java/com/google/gson/internal/bind/DateTypeAdapter.java # gson/src/main/java/com/google/gson/internal/bind/DefaultDateTypeAdapter.java # gson/src/main/java/com/google/gson/internal/bind/MapTypeAdapterFactory.java # gson/src/main/java/com/google/gson/internal/bind/TypeAdapters.java # gson/src/main/java/com/google/gson/stream/JsonReader.java # gson/src/main/java/com/google/gson/stream/JsonTreeWriter.java # gson/src/main/java/com/google/gson/stream/JsonWriter.java # gson/src/test/java/com/google/gson/CommentsTest.java # gson/src/test/java/com/google/gson/GsonTest.java # gson/src/test/java/com/google/gson/MixedStreamTest.java # gson/src/test/java/com/google/gson/ToNumberPolicyTest.java # gson/src/test/java/com/google/gson/functional/ArrayTest.java # gson/src/test/java/com/google/gson/functional/ConcurrencyTest.java # gson/src/test/java/com/google/gson/functional/CustomDeserializerTest.java # gson/src/test/java/com/google/gson/functional/CustomTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/DefaultTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/EnumWithObfuscatedTest.java # gson/src/test/java/com/google/gson/functional/ExposeFieldsTest.java # gson/src/test/java/com/google/gson/functional/FormattingStyleTest.java # gson/src/test/java/com/google/gson/functional/InstanceCreatorTest.java # gson/src/test/java/com/google/gson/functional/InternationalizationTest.java # gson/src/test/java/com/google/gson/functional/Java17RecordTest.java # gson/src/test/java/com/google/gson/functional/JavaUtilConcurrentAtomicTest.java # gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnClassesTest.java # gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnFieldsTest.java # gson/src/test/java/com/google/gson/functional/JsonParserTest.java # gson/src/test/java/com/google/gson/functional/NullObjectAndFieldTest.java # gson/src/test/java/com/google/gson/functional/ObjectTest.java # gson/src/test/java/com/google/gson/functional/PrimitiveTest.java # gson/src/test/java/com/google/gson/functional/ReflectionAccessTest.java # gson/src/test/java/com/google/gson/functional/StreamingTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/TreeTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/TypeAdapterPrecedenceTest.java # gson/src/test/java/com/google/gson/internal/bind/Java17ReflectiveTypeAdapterFactoryTest.java # gson/src/test/java/com/google/gson/internal/bind/JsonTreeReaderTest.java # gson/src/test/java/com/google/gson/internal/bind/JsonTreeWriterTest.java # gson/src/test/java/com/google/gson/internal/reflect/Java17ReflectionHelperTest.java # gson/src/test/java/com/google/gson/stream/JsonReaderTest.java # metrics/pom.xml # metrics/src/main/java/com/google/gson/metrics/BagOfPrimitives.java # metrics/src/main/java/com/google/gson/metrics/BagOfPrimitivesDeserializationBenchmark.java # metrics/src/main/java/com/google/gson/metrics/CollectionsDeserializationBenchmark.java # metrics/src/main/java/com/google/gson/metrics/NonUploadingCaliperRunner.java # metrics/src/main/java/com/google/gson/metrics/ParseBenchmark.java # metrics/src/main/java/com/google/gson/metrics/SerializationBenchmark.java # pom.xml # proto/pom.xml # proto/src/main/java/com/google/gson/protobuf/ProtoTypeAdapter.java # proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithAnnotationsTest.java # proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithComplexAndRepeatedFieldsTest.java # proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithPrimitiveTypesTest.java # shrinker-test/pom.xml # shrinker-test/src/main/java/com/example/ClassWithExposeAnnotation.java # shrinker-test/src/main/java/com/example/ClassWithHasArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithJsonAdapterAnnotation.java # shrinker-test/src/main/java/com/example/ClassWithNoArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithUnreferencedHasArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithUnreferencedNoArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithVersionAnnotations.java # shrinker-test/src/main/java/com/example/GenericClasses.java # shrinker-test/src/main/java/com/example/Main.java # shrinker-test/src/main/java/com/example/NoSerializedNameMain.java # shrinker-test/src/main/java/com/example/TestExecutor.java # shrinker-test/src/main/java/com/example/UnusedClass.java # shrinker-test/src/test/java/com/google/gson/it/ShrinkingIT.java
2024-03-12 12:56:07 +01:00
DefaultConfig.DEFAULT_SERIALIZE_NULLS,
DefaultConfig.DEFAULT_COMPLEX_MAP_KEYS,
DefaultConfig.DEFAULT_DUPLICATE_MAP_KEYS,
DefaultConfig.DEFAULT_JSON_NON_EXECUTABLE,
DefaultConfig.DEFAULT_ESCAPE_HTML,
DefaultConfig.DEFAULT_FORMATTING_STYLE,
Strictness.LENIENT,
DefaultConfig.DEFAULT_OMIT_QUOTES,
DefaultConfig.DEFAULT_SPECIALIZE_FLOAT_VALUES,
2022-05-17 21:20:10 +02:00
DefaultConfig.DEFAULT_USE_JDK_UNSAFE,
LongSerializationPolicy.DEFAULT,
Merge remote-tracking branch 'origin/main' # Conflicts: # .github/ISSUE_TEMPLATE/config.yml # .github/dependabot.yml # .github/pull_request_template.md # .github/workflows/build.yml # .github/workflows/check-android-compatibility.yml # .github/workflows/check-api-compatibility.yml # .github/workflows/cifuzz.yml # .github/workflows/codeql-analysis.yml # extras/pom.xml # extras/src/main/java/com/google/gson/extras/examples/rawcollections/RawCollectionsExample.java # extras/src/main/java/com/google/gson/graph/GraphAdapterBuilder.java # extras/src/main/java/com/google/gson/interceptors/Intercept.java # extras/src/main/java/com/google/gson/interceptors/InterceptorFactory.java # extras/src/main/java/com/google/gson/interceptors/JsonPostDeserializer.java # extras/src/main/java/com/google/gson/typeadapters/PostConstructAdapterFactory.java # extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java # extras/src/main/java/com/google/gson/typeadapters/UtcDateTypeAdapter.java # extras/src/test/java/com/google/gson/graph/GraphAdapterBuilderTest.java # extras/src/test/java/com/google/gson/interceptors/InterceptorTest.java # extras/src/test/java/com/google/gson/typeadapters/PostConstructAdapterFactoryTest.java # extras/src/test/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactoryTest.java # extras/src/test/java/com/google/gson/typeadapters/UtcDateTypeAdapterTest.java # graal-native-image-test/pom.xml # graal-native-image-test/src/test/java/com/google/gson/native_test/Java17RecordReflectionTest.java # graal-native-image-test/src/test/java/com/google/gson/native_test/ReflectionTest.java # gson/pom.xml # gson/src/main/java/com/google/gson/Gson.java # gson/src/main/java/com/google/gson/GsonBuilder.java # gson/src/main/java/com/google/gson/JsonParser.java # gson/src/main/java/com/google/gson/internal/LinkedTreeMap.java # gson/src/main/java/com/google/gson/internal/bind/DateTypeAdapter.java # gson/src/main/java/com/google/gson/internal/bind/DefaultDateTypeAdapter.java # gson/src/main/java/com/google/gson/internal/bind/MapTypeAdapterFactory.java # gson/src/main/java/com/google/gson/internal/bind/TypeAdapters.java # gson/src/main/java/com/google/gson/stream/JsonReader.java # gson/src/main/java/com/google/gson/stream/JsonTreeWriter.java # gson/src/main/java/com/google/gson/stream/JsonWriter.java # gson/src/test/java/com/google/gson/CommentsTest.java # gson/src/test/java/com/google/gson/GsonTest.java # gson/src/test/java/com/google/gson/MixedStreamTest.java # gson/src/test/java/com/google/gson/ToNumberPolicyTest.java # gson/src/test/java/com/google/gson/functional/ArrayTest.java # gson/src/test/java/com/google/gson/functional/ConcurrencyTest.java # gson/src/test/java/com/google/gson/functional/CustomDeserializerTest.java # gson/src/test/java/com/google/gson/functional/CustomTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/DefaultTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/EnumWithObfuscatedTest.java # gson/src/test/java/com/google/gson/functional/ExposeFieldsTest.java # gson/src/test/java/com/google/gson/functional/FormattingStyleTest.java # gson/src/test/java/com/google/gson/functional/InstanceCreatorTest.java # gson/src/test/java/com/google/gson/functional/InternationalizationTest.java # gson/src/test/java/com/google/gson/functional/Java17RecordTest.java # gson/src/test/java/com/google/gson/functional/JavaUtilConcurrentAtomicTest.java # gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnClassesTest.java # gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnFieldsTest.java # gson/src/test/java/com/google/gson/functional/JsonParserTest.java # gson/src/test/java/com/google/gson/functional/NullObjectAndFieldTest.java # gson/src/test/java/com/google/gson/functional/ObjectTest.java # gson/src/test/java/com/google/gson/functional/PrimitiveTest.java # gson/src/test/java/com/google/gson/functional/ReflectionAccessTest.java # gson/src/test/java/com/google/gson/functional/StreamingTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/TreeTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/TypeAdapterPrecedenceTest.java # gson/src/test/java/com/google/gson/internal/bind/Java17ReflectiveTypeAdapterFactoryTest.java # gson/src/test/java/com/google/gson/internal/bind/JsonTreeReaderTest.java # gson/src/test/java/com/google/gson/internal/bind/JsonTreeWriterTest.java # gson/src/test/java/com/google/gson/internal/reflect/Java17ReflectionHelperTest.java # gson/src/test/java/com/google/gson/stream/JsonReaderTest.java # metrics/pom.xml # metrics/src/main/java/com/google/gson/metrics/BagOfPrimitives.java # metrics/src/main/java/com/google/gson/metrics/BagOfPrimitivesDeserializationBenchmark.java # metrics/src/main/java/com/google/gson/metrics/CollectionsDeserializationBenchmark.java # metrics/src/main/java/com/google/gson/metrics/NonUploadingCaliperRunner.java # metrics/src/main/java/com/google/gson/metrics/ParseBenchmark.java # metrics/src/main/java/com/google/gson/metrics/SerializationBenchmark.java # pom.xml # proto/pom.xml # proto/src/main/java/com/google/gson/protobuf/ProtoTypeAdapter.java # proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithAnnotationsTest.java # proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithComplexAndRepeatedFieldsTest.java # proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithPrimitiveTypesTest.java # shrinker-test/pom.xml # shrinker-test/src/main/java/com/example/ClassWithExposeAnnotation.java # shrinker-test/src/main/java/com/example/ClassWithHasArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithJsonAdapterAnnotation.java # shrinker-test/src/main/java/com/example/ClassWithNoArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithUnreferencedHasArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithUnreferencedNoArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithVersionAnnotations.java # shrinker-test/src/main/java/com/example/GenericClasses.java # shrinker-test/src/main/java/com/example/Main.java # shrinker-test/src/main/java/com/example/NoSerializedNameMain.java # shrinker-test/src/main/java/com/example/TestExecutor.java # shrinker-test/src/main/java/com/example/UnusedClass.java # shrinker-test/src/test/java/com/google/gson/it/ShrinkingIT.java
2024-03-12 12:56:07 +01:00
DefaultConfig.DEFAULT_DATE_PATTERN,
DateFormat.DEFAULT,
DateFormat.DEFAULT,
Collections.<TypeAdapterFactory>emptyList(),
Collections.<TypeAdapterFactory>emptyList(),
Collections.<TypeAdapterFactory>emptyList(),
Merge remote-tracking branch 'origin/main' # Conflicts: # .github/ISSUE_TEMPLATE/config.yml # .github/dependabot.yml # .github/pull_request_template.md # .github/workflows/build.yml # .github/workflows/check-android-compatibility.yml # .github/workflows/check-api-compatibility.yml # .github/workflows/cifuzz.yml # .github/workflows/codeql-analysis.yml # extras/pom.xml # extras/src/main/java/com/google/gson/extras/examples/rawcollections/RawCollectionsExample.java # extras/src/main/java/com/google/gson/graph/GraphAdapterBuilder.java # extras/src/main/java/com/google/gson/interceptors/Intercept.java # extras/src/main/java/com/google/gson/interceptors/InterceptorFactory.java # extras/src/main/java/com/google/gson/interceptors/JsonPostDeserializer.java # extras/src/main/java/com/google/gson/typeadapters/PostConstructAdapterFactory.java # extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java # extras/src/main/java/com/google/gson/typeadapters/UtcDateTypeAdapter.java # extras/src/test/java/com/google/gson/graph/GraphAdapterBuilderTest.java # extras/src/test/java/com/google/gson/interceptors/InterceptorTest.java # extras/src/test/java/com/google/gson/typeadapters/PostConstructAdapterFactoryTest.java # extras/src/test/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactoryTest.java # extras/src/test/java/com/google/gson/typeadapters/UtcDateTypeAdapterTest.java # graal-native-image-test/pom.xml # graal-native-image-test/src/test/java/com/google/gson/native_test/Java17RecordReflectionTest.java # graal-native-image-test/src/test/java/com/google/gson/native_test/ReflectionTest.java # gson/pom.xml # gson/src/main/java/com/google/gson/Gson.java # gson/src/main/java/com/google/gson/GsonBuilder.java # gson/src/main/java/com/google/gson/JsonParser.java # gson/src/main/java/com/google/gson/internal/LinkedTreeMap.java # gson/src/main/java/com/google/gson/internal/bind/DateTypeAdapter.java # gson/src/main/java/com/google/gson/internal/bind/DefaultDateTypeAdapter.java # gson/src/main/java/com/google/gson/internal/bind/MapTypeAdapterFactory.java # gson/src/main/java/com/google/gson/internal/bind/TypeAdapters.java # gson/src/main/java/com/google/gson/stream/JsonReader.java # gson/src/main/java/com/google/gson/stream/JsonTreeWriter.java # gson/src/main/java/com/google/gson/stream/JsonWriter.java # gson/src/test/java/com/google/gson/CommentsTest.java # gson/src/test/java/com/google/gson/GsonTest.java # gson/src/test/java/com/google/gson/MixedStreamTest.java # gson/src/test/java/com/google/gson/ToNumberPolicyTest.java # gson/src/test/java/com/google/gson/functional/ArrayTest.java # gson/src/test/java/com/google/gson/functional/ConcurrencyTest.java # gson/src/test/java/com/google/gson/functional/CustomDeserializerTest.java # gson/src/test/java/com/google/gson/functional/CustomTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/DefaultTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/EnumWithObfuscatedTest.java # gson/src/test/java/com/google/gson/functional/ExposeFieldsTest.java # gson/src/test/java/com/google/gson/functional/FormattingStyleTest.java # gson/src/test/java/com/google/gson/functional/InstanceCreatorTest.java # gson/src/test/java/com/google/gson/functional/InternationalizationTest.java # gson/src/test/java/com/google/gson/functional/Java17RecordTest.java # gson/src/test/java/com/google/gson/functional/JavaUtilConcurrentAtomicTest.java # gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnClassesTest.java # gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnFieldsTest.java # gson/src/test/java/com/google/gson/functional/JsonParserTest.java # gson/src/test/java/com/google/gson/functional/NullObjectAndFieldTest.java # gson/src/test/java/com/google/gson/functional/ObjectTest.java # gson/src/test/java/com/google/gson/functional/PrimitiveTest.java # gson/src/test/java/com/google/gson/functional/ReflectionAccessTest.java # gson/src/test/java/com/google/gson/functional/StreamingTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/TreeTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/TypeAdapterPrecedenceTest.java # gson/src/test/java/com/google/gson/internal/bind/Java17ReflectiveTypeAdapterFactoryTest.java # gson/src/test/java/com/google/gson/internal/bind/JsonTreeReaderTest.java # gson/src/test/java/com/google/gson/internal/bind/JsonTreeWriterTest.java # gson/src/test/java/com/google/gson/internal/reflect/Java17ReflectionHelperTest.java # gson/src/test/java/com/google/gson/stream/JsonReaderTest.java # metrics/pom.xml # metrics/src/main/java/com/google/gson/metrics/BagOfPrimitives.java # metrics/src/main/java/com/google/gson/metrics/BagOfPrimitivesDeserializationBenchmark.java # metrics/src/main/java/com/google/gson/metrics/CollectionsDeserializationBenchmark.java # metrics/src/main/java/com/google/gson/metrics/NonUploadingCaliperRunner.java # metrics/src/main/java/com/google/gson/metrics/ParseBenchmark.java # metrics/src/main/java/com/google/gson/metrics/SerializationBenchmark.java # pom.xml # proto/pom.xml # proto/src/main/java/com/google/gson/protobuf/ProtoTypeAdapter.java # proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithAnnotationsTest.java # proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithComplexAndRepeatedFieldsTest.java # proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithPrimitiveTypesTest.java # shrinker-test/pom.xml # shrinker-test/src/main/java/com/example/ClassWithExposeAnnotation.java # shrinker-test/src/main/java/com/example/ClassWithHasArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithJsonAdapterAnnotation.java # shrinker-test/src/main/java/com/example/ClassWithNoArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithUnreferencedHasArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithUnreferencedNoArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithVersionAnnotations.java # shrinker-test/src/main/java/com/example/GenericClasses.java # shrinker-test/src/main/java/com/example/Main.java # shrinker-test/src/main/java/com/example/NoSerializedNameMain.java # shrinker-test/src/main/java/com/example/TestExecutor.java # shrinker-test/src/main/java/com/example/UnusedClass.java # shrinker-test/src/test/java/com/google/gson/it/ShrinkingIT.java
2024-03-12 12:56:07 +01:00
DefaultConfig.DEFAULT_OBJECT_TO_NUMBER_STRATEGY,
DefaultConfig.DEFAULT_NUMBER_TO_NUMBER_STRATEGY,
Collections.<ReflectionAccessFilter>emptyList());
2008-09-01 05:13:32 +02:00
}
Gson(
Excluder excluder,
FieldNamingStrategy fieldNamingStrategy,
Map<Type, InstanceCreator<?>> instanceCreators,
boolean serializeNulls,
boolean complexMapKeySerialization,
Merge remote-tracking branch 'origin/main' # Conflicts: # .github/ISSUE_TEMPLATE/config.yml # .github/dependabot.yml # .github/pull_request_template.md # .github/workflows/build.yml # .github/workflows/check-android-compatibility.yml # .github/workflows/check-api-compatibility.yml # .github/workflows/cifuzz.yml # .github/workflows/codeql-analysis.yml # extras/pom.xml # extras/src/main/java/com/google/gson/extras/examples/rawcollections/RawCollectionsExample.java # extras/src/main/java/com/google/gson/graph/GraphAdapterBuilder.java # extras/src/main/java/com/google/gson/interceptors/Intercept.java # extras/src/main/java/com/google/gson/interceptors/InterceptorFactory.java # extras/src/main/java/com/google/gson/interceptors/JsonPostDeserializer.java # extras/src/main/java/com/google/gson/typeadapters/PostConstructAdapterFactory.java # extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java # extras/src/main/java/com/google/gson/typeadapters/UtcDateTypeAdapter.java # extras/src/test/java/com/google/gson/graph/GraphAdapterBuilderTest.java # extras/src/test/java/com/google/gson/interceptors/InterceptorTest.java # extras/src/test/java/com/google/gson/typeadapters/PostConstructAdapterFactoryTest.java # extras/src/test/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactoryTest.java # extras/src/test/java/com/google/gson/typeadapters/UtcDateTypeAdapterTest.java # graal-native-image-test/pom.xml # graal-native-image-test/src/test/java/com/google/gson/native_test/Java17RecordReflectionTest.java # graal-native-image-test/src/test/java/com/google/gson/native_test/ReflectionTest.java # gson/pom.xml # gson/src/main/java/com/google/gson/Gson.java # gson/src/main/java/com/google/gson/GsonBuilder.java # gson/src/main/java/com/google/gson/JsonParser.java # gson/src/main/java/com/google/gson/internal/LinkedTreeMap.java # gson/src/main/java/com/google/gson/internal/bind/DateTypeAdapter.java # gson/src/main/java/com/google/gson/internal/bind/DefaultDateTypeAdapter.java # gson/src/main/java/com/google/gson/internal/bind/MapTypeAdapterFactory.java # gson/src/main/java/com/google/gson/internal/bind/TypeAdapters.java # gson/src/main/java/com/google/gson/stream/JsonReader.java # gson/src/main/java/com/google/gson/stream/JsonTreeWriter.java # gson/src/main/java/com/google/gson/stream/JsonWriter.java # gson/src/test/java/com/google/gson/CommentsTest.java # gson/src/test/java/com/google/gson/GsonTest.java # gson/src/test/java/com/google/gson/MixedStreamTest.java # gson/src/test/java/com/google/gson/ToNumberPolicyTest.java # gson/src/test/java/com/google/gson/functional/ArrayTest.java # gson/src/test/java/com/google/gson/functional/ConcurrencyTest.java # gson/src/test/java/com/google/gson/functional/CustomDeserializerTest.java # gson/src/test/java/com/google/gson/functional/CustomTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/DefaultTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/EnumWithObfuscatedTest.java # gson/src/test/java/com/google/gson/functional/ExposeFieldsTest.java # gson/src/test/java/com/google/gson/functional/FormattingStyleTest.java # gson/src/test/java/com/google/gson/functional/InstanceCreatorTest.java # gson/src/test/java/com/google/gson/functional/InternationalizationTest.java # gson/src/test/java/com/google/gson/functional/Java17RecordTest.java # gson/src/test/java/com/google/gson/functional/JavaUtilConcurrentAtomicTest.java # gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnClassesTest.java # gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnFieldsTest.java # gson/src/test/java/com/google/gson/functional/JsonParserTest.java # gson/src/test/java/com/google/gson/functional/NullObjectAndFieldTest.java # gson/src/test/java/com/google/gson/functional/ObjectTest.java # gson/src/test/java/com/google/gson/functional/PrimitiveTest.java # gson/src/test/java/com/google/gson/functional/ReflectionAccessTest.java # gson/src/test/java/com/google/gson/functional/StreamingTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/TreeTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/TypeAdapterPrecedenceTest.java # gson/src/test/java/com/google/gson/internal/bind/Java17ReflectiveTypeAdapterFactoryTest.java # gson/src/test/java/com/google/gson/internal/bind/JsonTreeReaderTest.java # gson/src/test/java/com/google/gson/internal/bind/JsonTreeWriterTest.java # gson/src/test/java/com/google/gson/internal/reflect/Java17ReflectionHelperTest.java # gson/src/test/java/com/google/gson/stream/JsonReaderTest.java # metrics/pom.xml # metrics/src/main/java/com/google/gson/metrics/BagOfPrimitives.java # metrics/src/main/java/com/google/gson/metrics/BagOfPrimitivesDeserializationBenchmark.java # metrics/src/main/java/com/google/gson/metrics/CollectionsDeserializationBenchmark.java # metrics/src/main/java/com/google/gson/metrics/NonUploadingCaliperRunner.java # metrics/src/main/java/com/google/gson/metrics/ParseBenchmark.java # metrics/src/main/java/com/google/gson/metrics/SerializationBenchmark.java # pom.xml # proto/pom.xml # proto/src/main/java/com/google/gson/protobuf/ProtoTypeAdapter.java # proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithAnnotationsTest.java # proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithComplexAndRepeatedFieldsTest.java # proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithPrimitiveTypesTest.java # shrinker-test/pom.xml # shrinker-test/src/main/java/com/example/ClassWithExposeAnnotation.java # shrinker-test/src/main/java/com/example/ClassWithHasArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithJsonAdapterAnnotation.java # shrinker-test/src/main/java/com/example/ClassWithNoArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithUnreferencedHasArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithUnreferencedNoArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithVersionAnnotations.java # shrinker-test/src/main/java/com/example/GenericClasses.java # shrinker-test/src/main/java/com/example/Main.java # shrinker-test/src/main/java/com/example/NoSerializedNameMain.java # shrinker-test/src/main/java/com/example/TestExecutor.java # shrinker-test/src/main/java/com/example/UnusedClass.java # shrinker-test/src/test/java/com/google/gson/it/ShrinkingIT.java
2024-03-12 12:56:07 +01:00
boolean duplicateMapKeyDeserialization,
boolean generateNonExecutableGson, boolean htmlSafe,
Strict mode for JSON parsing, contributed by @marten-voorberg. (#2437) * Strict mode for JSON parsing (#2323) * Feat #6: Add strict flag to Gson and GsonBuilder * Test #2: Add failing tests for capitalized keywords * Feat #2: JsonReader does not read (partially) capitalized keywords if strict mode is used * Feat #3: Added implementation and tests for JSONReader not accepting specific escape sequence representing in strict mode * Test #3: Simplify test cases by removing unnecessary array * Feat #3: Improve error by including the illegal character * Feat #5: JsonReader does not allow unespaced control flow characters in strict mode * Test #5: Test unespaced control flow characters in strict mode * Feat #4: Disallow espaced newline character in strict mode * Test #4: Add tests for (dis)allowing newline character depensding on strictness * Test #5: Test case for unescaped control char in non-strict mode * Test #2: Simplify test cases * Feat #13: Change leniency API to Strictness enum in JsonReader, Gson, and GsonBuilder * Feat #15: Change JsonWriter API to also use Strictness * Test #15: Test Strictness in JsonWriter API * Doc #15: Add and update documentation for Strictness in JsonWriter API * refactor #12: Fixed typos and empty catch brackets in tests * refactor #12: Resolved importing wildcards, made some lines adhere to Google java style * #5 Add test case for unescaped control characters * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue --------- Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * Doc #17: Add and change javadoc of public methods * Doc #17: Update JavaDoc in JsonReader and Strictness * Doc #17: Update JavaDoc in Gson and GsonBuilder * Test #34: Add tests for setting strictness through GsonBuilder * Fix: Add Fix broken test * Fix: Invalid JavaDoc in Gson.java * Doc #17: update outdated javadoc * #37: Resolve more PR feedback * Fix #37: Resolve various PR comments * Fix #37: Resolve various PR comments * Refactor #35: Refactor JsonReader#peekKeyword to reduce the amount of strictness checks (#39) * Doc #40: Update JavaDoc based on PR feedback * Doc #40: Update old RFC in GsonBuilder documentation * Doc #40: Fix formatting error in JavaDoc * Doc #40: Add tests for setting strictness and lenient to JsonReaderTest * Test #43: Changed tests to make use of assertThrows * test #43: Changed tests to make use of assertThrows as per feedback * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * test #43: Resolve PR recommendations * Test #43: Mini change to TC * Test #43: Mini change to TC --------- Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * doc #46: Resolved comments in main PR * Feat #45: Change Gson.fromJson and Gson.toJson to be strict when the provided writer/reader is strict * Fix #45: Small type * Update gson/src/test/java/com/google/gson/stream/JsonReaderTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Update gson/src/main/java/com/google/gson/GsonBuilder.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Fix #45: Resolve various comments by eamonmcmanus * Strictness mode follow-up * Update Troubleshooting.md and Gson default lenient mode documentation * Always use GSON strictness when set. * Rename Strictness.DEFAULT to Strictness.LEGACY_STRICT * Update JavaDoc with new strictness functionality * Replace default with legacy strict for JsonReader javadoc * Add JSONReader test cases for U2028 and U2029 * Refactor JSONReader#peekKeyWord() based on @eamonmcmanus's suggestion * Deprecate setLenient in favor of setStrictness --------- Co-authored-by: Carl Peterson <unknown> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Strictness follow-up (#2408) * Strictness mode follow-up - Remove mentions of `null` Gson strictness; this is an implementation detail - Fix incorrect / outdated documentation - Reduce links to RFC; if there is already a link to it in a previous sentence don't link to it again - Extend and update tests - Minor punctuation changes in documentation for consistency * Deprecate `setLenient` methods * `strictness2` fixes & improvements (#2456) * Adjust ProGuard default rules and shrinking tests (#2420) * Adjust ProGuard default rules and shrinking tests * Adjust comment * Add shrinking test for class without no-args constructor; improve docs * Improve Unsafe mention in Troubleshooting Guide * Improve comment for `-if class *` * Bump com.google.guava:guava from 32.0.1-jre to 32.1.1-jre (#2444) Bumps [com.google.guava:guava](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Bump com.google.guava:guava-testlib from 32.0.1-jre to 32.1.1-jre (#2443) Bumps [com.google.guava:guava-testlib](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava-testlib dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Support non-generic type for `TypeToken.getParameterized` for legacy reasons (#2447) This partially restores the behavior before a589ef20087b4b0f1ec3048d3ceaef1eedccd09d, except that back then for a non-generic type a bogus `TypeToken(ParameterizedType)` was created, whereas now a `TypeToken(Class)` is created instead. * Fixed Typo in GsonBuilder.java (#2449) * Make date-formatting tests less fragile with regular expressions. (#2450) * Make date-formatting tests less fragile with regular expressions. This is not great. We should really ensure that formatted dates are the same regardless of JDK version. There is code that attempts to do that but it is not really effective. So for now we fudge around the differences by using regular expressions to paper over the differences. * Temporarily add test-debugging code. * Another attempt at debugging a test failure. * Fix pattern in assertion. * Modification in test cases (#2454) * Fixed Typo in GsonBuilder.java * Suggestions on Test cases * Modified test cases using assertThrows method (JUnit) * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/GsonTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> --------- Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Minor follow-up changes --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Éamonn McManus <emcmanus@google.com> Co-authored-by: Wonil <cwi5525@naver.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Marten <martenvoorberg@gmail.com> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Wonil <cwi5525@naver.com>
2023-07-30 18:20:32 +02:00
FormattingStyle formattingStyle,
Strictness strictness,
Merge remote-tracking branch 'origin/main' # Conflicts: # .github/ISSUE_TEMPLATE/config.yml # .github/dependabot.yml # .github/pull_request_template.md # .github/workflows/build.yml # .github/workflows/check-android-compatibility.yml # .github/workflows/check-api-compatibility.yml # .github/workflows/cifuzz.yml # .github/workflows/codeql-analysis.yml # extras/pom.xml # extras/src/main/java/com/google/gson/extras/examples/rawcollections/RawCollectionsExample.java # extras/src/main/java/com/google/gson/graph/GraphAdapterBuilder.java # extras/src/main/java/com/google/gson/interceptors/Intercept.java # extras/src/main/java/com/google/gson/interceptors/InterceptorFactory.java # extras/src/main/java/com/google/gson/interceptors/JsonPostDeserializer.java # extras/src/main/java/com/google/gson/typeadapters/PostConstructAdapterFactory.java # extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java # extras/src/main/java/com/google/gson/typeadapters/UtcDateTypeAdapter.java # extras/src/test/java/com/google/gson/graph/GraphAdapterBuilderTest.java # extras/src/test/java/com/google/gson/interceptors/InterceptorTest.java # extras/src/test/java/com/google/gson/typeadapters/PostConstructAdapterFactoryTest.java # extras/src/test/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactoryTest.java # extras/src/test/java/com/google/gson/typeadapters/UtcDateTypeAdapterTest.java # graal-native-image-test/pom.xml # graal-native-image-test/src/test/java/com/google/gson/native_test/Java17RecordReflectionTest.java # graal-native-image-test/src/test/java/com/google/gson/native_test/ReflectionTest.java # gson/pom.xml # gson/src/main/java/com/google/gson/Gson.java # gson/src/main/java/com/google/gson/GsonBuilder.java # gson/src/main/java/com/google/gson/JsonParser.java # gson/src/main/java/com/google/gson/internal/LinkedTreeMap.java # gson/src/main/java/com/google/gson/internal/bind/DateTypeAdapter.java # gson/src/main/java/com/google/gson/internal/bind/DefaultDateTypeAdapter.java # gson/src/main/java/com/google/gson/internal/bind/MapTypeAdapterFactory.java # gson/src/main/java/com/google/gson/internal/bind/TypeAdapters.java # gson/src/main/java/com/google/gson/stream/JsonReader.java # gson/src/main/java/com/google/gson/stream/JsonTreeWriter.java # gson/src/main/java/com/google/gson/stream/JsonWriter.java # gson/src/test/java/com/google/gson/CommentsTest.java # gson/src/test/java/com/google/gson/GsonTest.java # gson/src/test/java/com/google/gson/MixedStreamTest.java # gson/src/test/java/com/google/gson/ToNumberPolicyTest.java # gson/src/test/java/com/google/gson/functional/ArrayTest.java # gson/src/test/java/com/google/gson/functional/ConcurrencyTest.java # gson/src/test/java/com/google/gson/functional/CustomDeserializerTest.java # gson/src/test/java/com/google/gson/functional/CustomTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/DefaultTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/EnumWithObfuscatedTest.java # gson/src/test/java/com/google/gson/functional/ExposeFieldsTest.java # gson/src/test/java/com/google/gson/functional/FormattingStyleTest.java # gson/src/test/java/com/google/gson/functional/InstanceCreatorTest.java # gson/src/test/java/com/google/gson/functional/InternationalizationTest.java # gson/src/test/java/com/google/gson/functional/Java17RecordTest.java # gson/src/test/java/com/google/gson/functional/JavaUtilConcurrentAtomicTest.java # gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnClassesTest.java # gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnFieldsTest.java # gson/src/test/java/com/google/gson/functional/JsonParserTest.java # gson/src/test/java/com/google/gson/functional/NullObjectAndFieldTest.java # gson/src/test/java/com/google/gson/functional/ObjectTest.java # gson/src/test/java/com/google/gson/functional/PrimitiveTest.java # gson/src/test/java/com/google/gson/functional/ReflectionAccessTest.java # gson/src/test/java/com/google/gson/functional/StreamingTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/TreeTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/TypeAdapterPrecedenceTest.java # gson/src/test/java/com/google/gson/internal/bind/Java17ReflectiveTypeAdapterFactoryTest.java # gson/src/test/java/com/google/gson/internal/bind/JsonTreeReaderTest.java # gson/src/test/java/com/google/gson/internal/bind/JsonTreeWriterTest.java # gson/src/test/java/com/google/gson/internal/reflect/Java17ReflectionHelperTest.java # gson/src/test/java/com/google/gson/stream/JsonReaderTest.java # metrics/pom.xml # metrics/src/main/java/com/google/gson/metrics/BagOfPrimitives.java # metrics/src/main/java/com/google/gson/metrics/BagOfPrimitivesDeserializationBenchmark.java # metrics/src/main/java/com/google/gson/metrics/CollectionsDeserializationBenchmark.java # metrics/src/main/java/com/google/gson/metrics/NonUploadingCaliperRunner.java # metrics/src/main/java/com/google/gson/metrics/ParseBenchmark.java # metrics/src/main/java/com/google/gson/metrics/SerializationBenchmark.java # pom.xml # proto/pom.xml # proto/src/main/java/com/google/gson/protobuf/ProtoTypeAdapter.java # proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithAnnotationsTest.java # proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithComplexAndRepeatedFieldsTest.java # proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithPrimitiveTypesTest.java # shrinker-test/pom.xml # shrinker-test/src/main/java/com/example/ClassWithExposeAnnotation.java # shrinker-test/src/main/java/com/example/ClassWithHasArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithJsonAdapterAnnotation.java # shrinker-test/src/main/java/com/example/ClassWithNoArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithUnreferencedHasArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithUnreferencedNoArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithVersionAnnotations.java # shrinker-test/src/main/java/com/example/GenericClasses.java # shrinker-test/src/main/java/com/example/Main.java # shrinker-test/src/main/java/com/example/NoSerializedNameMain.java # shrinker-test/src/main/java/com/example/TestExecutor.java # shrinker-test/src/main/java/com/example/UnusedClass.java # shrinker-test/src/test/java/com/google/gson/it/ShrinkingIT.java
2024-03-12 12:56:07 +01:00
boolean omitQuotes,
Strict mode for JSON parsing, contributed by @marten-voorberg. (#2437) * Strict mode for JSON parsing (#2323) * Feat #6: Add strict flag to Gson and GsonBuilder * Test #2: Add failing tests for capitalized keywords * Feat #2: JsonReader does not read (partially) capitalized keywords if strict mode is used * Feat #3: Added implementation and tests for JSONReader not accepting specific escape sequence representing in strict mode * Test #3: Simplify test cases by removing unnecessary array * Feat #3: Improve error by including the illegal character * Feat #5: JsonReader does not allow unespaced control flow characters in strict mode * Test #5: Test unespaced control flow characters in strict mode * Feat #4: Disallow espaced newline character in strict mode * Test #4: Add tests for (dis)allowing newline character depensding on strictness * Test #5: Test case for unescaped control char in non-strict mode * Test #2: Simplify test cases * Feat #13: Change leniency API to Strictness enum in JsonReader, Gson, and GsonBuilder * Feat #15: Change JsonWriter API to also use Strictness * Test #15: Test Strictness in JsonWriter API * Doc #15: Add and update documentation for Strictness in JsonWriter API * refactor #12: Fixed typos and empty catch brackets in tests * refactor #12: Resolved importing wildcards, made some lines adhere to Google java style * #5 Add test case for unescaped control characters * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue --------- Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * Doc #17: Add and change javadoc of public methods * Doc #17: Update JavaDoc in JsonReader and Strictness * Doc #17: Update JavaDoc in Gson and GsonBuilder * Test #34: Add tests for setting strictness through GsonBuilder * Fix: Add Fix broken test * Fix: Invalid JavaDoc in Gson.java * Doc #17: update outdated javadoc * #37: Resolve more PR feedback * Fix #37: Resolve various PR comments * Fix #37: Resolve various PR comments * Refactor #35: Refactor JsonReader#peekKeyword to reduce the amount of strictness checks (#39) * Doc #40: Update JavaDoc based on PR feedback * Doc #40: Update old RFC in GsonBuilder documentation * Doc #40: Fix formatting error in JavaDoc * Doc #40: Add tests for setting strictness and lenient to JsonReaderTest * Test #43: Changed tests to make use of assertThrows * test #43: Changed tests to make use of assertThrows as per feedback * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * test #43: Resolve PR recommendations * Test #43: Mini change to TC * Test #43: Mini change to TC --------- Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * doc #46: Resolved comments in main PR * Feat #45: Change Gson.fromJson and Gson.toJson to be strict when the provided writer/reader is strict * Fix #45: Small type * Update gson/src/test/java/com/google/gson/stream/JsonReaderTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Update gson/src/main/java/com/google/gson/GsonBuilder.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Fix #45: Resolve various comments by eamonmcmanus * Strictness mode follow-up * Update Troubleshooting.md and Gson default lenient mode documentation * Always use GSON strictness when set. * Rename Strictness.DEFAULT to Strictness.LEGACY_STRICT * Update JavaDoc with new strictness functionality * Replace default with legacy strict for JsonReader javadoc * Add JSONReader test cases for U2028 and U2029 * Refactor JSONReader#peekKeyWord() based on @eamonmcmanus's suggestion * Deprecate setLenient in favor of setStrictness --------- Co-authored-by: Carl Peterson <unknown> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Strictness follow-up (#2408) * Strictness mode follow-up - Remove mentions of `null` Gson strictness; this is an implementation detail - Fix incorrect / outdated documentation - Reduce links to RFC; if there is already a link to it in a previous sentence don't link to it again - Extend and update tests - Minor punctuation changes in documentation for consistency * Deprecate `setLenient` methods * `strictness2` fixes & improvements (#2456) * Adjust ProGuard default rules and shrinking tests (#2420) * Adjust ProGuard default rules and shrinking tests * Adjust comment * Add shrinking test for class without no-args constructor; improve docs * Improve Unsafe mention in Troubleshooting Guide * Improve comment for `-if class *` * Bump com.google.guava:guava from 32.0.1-jre to 32.1.1-jre (#2444) Bumps [com.google.guava:guava](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Bump com.google.guava:guava-testlib from 32.0.1-jre to 32.1.1-jre (#2443) Bumps [com.google.guava:guava-testlib](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava-testlib dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Support non-generic type for `TypeToken.getParameterized` for legacy reasons (#2447) This partially restores the behavior before a589ef20087b4b0f1ec3048d3ceaef1eedccd09d, except that back then for a non-generic type a bogus `TypeToken(ParameterizedType)` was created, whereas now a `TypeToken(Class)` is created instead. * Fixed Typo in GsonBuilder.java (#2449) * Make date-formatting tests less fragile with regular expressions. (#2450) * Make date-formatting tests less fragile with regular expressions. This is not great. We should really ensure that formatted dates are the same regardless of JDK version. There is code that attempts to do that but it is not really effective. So for now we fudge around the differences by using regular expressions to paper over the differences. * Temporarily add test-debugging code. * Another attempt at debugging a test failure. * Fix pattern in assertion. * Modification in test cases (#2454) * Fixed Typo in GsonBuilder.java * Suggestions on Test cases * Modified test cases using assertThrows method (JUnit) * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/GsonTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> --------- Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Minor follow-up changes --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Éamonn McManus <emcmanus@google.com> Co-authored-by: Wonil <cwi5525@naver.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Marten <martenvoorberg@gmail.com> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Wonil <cwi5525@naver.com>
2023-07-30 18:20:32 +02:00
boolean serializeSpecialFloatingPointValues,
boolean useJdkUnsafe,
LongSerializationPolicy longSerializationPolicy,
String datePattern,
int dateStyle,
int timeStyle,
List<TypeAdapterFactory> builderFactories,
List<TypeAdapterFactory> builderHierarchyFactories,
List<TypeAdapterFactory> factoriesToBeAdded,
ToNumberStrategy objectToNumberStrategy,
ToNumberStrategy numberToNumberStrategy,
List<ReflectionAccessFilter> reflectionFilters) {
this.excluder = excluder;
this.fieldNamingStrategy = fieldNamingStrategy;
this.instanceCreators = instanceCreators;
this.constructorConstructor =
new ConstructorConstructor(instanceCreators, useJdkUnsafe, reflectionFilters);
2008-09-01 05:13:32 +02:00
this.serializeNulls = serializeNulls;
this.complexMapKeySerialization = complexMapKeySerialization;
2021-04-21 08:31:23 +02:00
this.duplicateMapKeyDeserialization = duplicateMapKeyDeserialization;
this.generateNonExecutableJson = generateNonExecutableGson;
this.htmlSafe = htmlSafe;
this.formattingStyle = formattingStyle;
Strict mode for JSON parsing, contributed by @marten-voorberg. (#2437) * Strict mode for JSON parsing (#2323) * Feat #6: Add strict flag to Gson and GsonBuilder * Test #2: Add failing tests for capitalized keywords * Feat #2: JsonReader does not read (partially) capitalized keywords if strict mode is used * Feat #3: Added implementation and tests for JSONReader not accepting specific escape sequence representing in strict mode * Test #3: Simplify test cases by removing unnecessary array * Feat #3: Improve error by including the illegal character * Feat #5: JsonReader does not allow unespaced control flow characters in strict mode * Test #5: Test unespaced control flow characters in strict mode * Feat #4: Disallow espaced newline character in strict mode * Test #4: Add tests for (dis)allowing newline character depensding on strictness * Test #5: Test case for unescaped control char in non-strict mode * Test #2: Simplify test cases * Feat #13: Change leniency API to Strictness enum in JsonReader, Gson, and GsonBuilder * Feat #15: Change JsonWriter API to also use Strictness * Test #15: Test Strictness in JsonWriter API * Doc #15: Add and update documentation for Strictness in JsonWriter API * refactor #12: Fixed typos and empty catch brackets in tests * refactor #12: Resolved importing wildcards, made some lines adhere to Google java style * #5 Add test case for unescaped control characters * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue --------- Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * Doc #17: Add and change javadoc of public methods * Doc #17: Update JavaDoc in JsonReader and Strictness * Doc #17: Update JavaDoc in Gson and GsonBuilder * Test #34: Add tests for setting strictness through GsonBuilder * Fix: Add Fix broken test * Fix: Invalid JavaDoc in Gson.java * Doc #17: update outdated javadoc * #37: Resolve more PR feedback * Fix #37: Resolve various PR comments * Fix #37: Resolve various PR comments * Refactor #35: Refactor JsonReader#peekKeyword to reduce the amount of strictness checks (#39) * Doc #40: Update JavaDoc based on PR feedback * Doc #40: Update old RFC in GsonBuilder documentation * Doc #40: Fix formatting error in JavaDoc * Doc #40: Add tests for setting strictness and lenient to JsonReaderTest * Test #43: Changed tests to make use of assertThrows * test #43: Changed tests to make use of assertThrows as per feedback * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * test #43: Resolve PR recommendations * Test #43: Mini change to TC * Test #43: Mini change to TC --------- Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * doc #46: Resolved comments in main PR * Feat #45: Change Gson.fromJson and Gson.toJson to be strict when the provided writer/reader is strict * Fix #45: Small type * Update gson/src/test/java/com/google/gson/stream/JsonReaderTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Update gson/src/main/java/com/google/gson/GsonBuilder.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Fix #45: Resolve various comments by eamonmcmanus * Strictness mode follow-up * Update Troubleshooting.md and Gson default lenient mode documentation * Always use GSON strictness when set. * Rename Strictness.DEFAULT to Strictness.LEGACY_STRICT * Update JavaDoc with new strictness functionality * Replace default with legacy strict for JsonReader javadoc * Add JSONReader test cases for U2028 and U2029 * Refactor JSONReader#peekKeyWord() based on @eamonmcmanus's suggestion * Deprecate setLenient in favor of setStrictness --------- Co-authored-by: Carl Peterson <unknown> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Strictness follow-up (#2408) * Strictness mode follow-up - Remove mentions of `null` Gson strictness; this is an implementation detail - Fix incorrect / outdated documentation - Reduce links to RFC; if there is already a link to it in a previous sentence don't link to it again - Extend and update tests - Minor punctuation changes in documentation for consistency * Deprecate `setLenient` methods * `strictness2` fixes & improvements (#2456) * Adjust ProGuard default rules and shrinking tests (#2420) * Adjust ProGuard default rules and shrinking tests * Adjust comment * Add shrinking test for class without no-args constructor; improve docs * Improve Unsafe mention in Troubleshooting Guide * Improve comment for `-if class *` * Bump com.google.guava:guava from 32.0.1-jre to 32.1.1-jre (#2444) Bumps [com.google.guava:guava](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Bump com.google.guava:guava-testlib from 32.0.1-jre to 32.1.1-jre (#2443) Bumps [com.google.guava:guava-testlib](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava-testlib dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Support non-generic type for `TypeToken.getParameterized` for legacy reasons (#2447) This partially restores the behavior before a589ef20087b4b0f1ec3048d3ceaef1eedccd09d, except that back then for a non-generic type a bogus `TypeToken(ParameterizedType)` was created, whereas now a `TypeToken(Class)` is created instead. * Fixed Typo in GsonBuilder.java (#2449) * Make date-formatting tests less fragile with regular expressions. (#2450) * Make date-formatting tests less fragile with regular expressions. This is not great. We should really ensure that formatted dates are the same regardless of JDK version. There is code that attempts to do that but it is not really effective. So for now we fudge around the differences by using regular expressions to paper over the differences. * Temporarily add test-debugging code. * Another attempt at debugging a test failure. * Fix pattern in assertion. * Modification in test cases (#2454) * Fixed Typo in GsonBuilder.java * Suggestions on Test cases * Modified test cases using assertThrows method (JUnit) * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/GsonTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> --------- Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Minor follow-up changes --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Éamonn McManus <emcmanus@google.com> Co-authored-by: Wonil <cwi5525@naver.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Marten <martenvoorberg@gmail.com> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Wonil <cwi5525@naver.com>
2023-07-30 18:20:32 +02:00
this.strictness = strictness;
2022-05-17 21:20:10 +02:00
this.omitQuotes = omitQuotes;
this.serializeSpecialFloatingPointValues = serializeSpecialFloatingPointValues;
this.useJdkUnsafe = useJdkUnsafe;
this.longSerializationPolicy = longSerializationPolicy;
this.datePattern = datePattern;
this.dateStyle = dateStyle;
this.timeStyle = timeStyle;
this.builderFactories = builderFactories;
this.builderHierarchyFactories = builderHierarchyFactories;
this.objectToNumberStrategy = objectToNumberStrategy;
this.numberToNumberStrategy = numberToNumberStrategy;
this.reflectionFilters = reflectionFilters;
List<TypeAdapterFactory> factories = new ArrayList<>();
2011-11-23 14:39:06 +01:00
// built-in type adapters that cannot be overridden
factories.add(TypeAdapters.JSON_ELEMENT_FACTORY);
factories.add(ObjectTypeAdapter.getFactory(objectToNumberStrategy));
// the excluder must precede all adapters that handle user-defined types
factories.add(excluder);
// users' type adapters
factories.addAll(factoriesToBeAdded);
// type adapters for basic platform types
factories.add(TypeAdapters.STRING_FACTORY);
factories.add(TypeAdapters.INTEGER_FACTORY);
factories.add(TypeAdapters.BOOLEAN_FACTORY);
factories.add(TypeAdapters.BYTE_FACTORY);
factories.add(TypeAdapters.SHORT_FACTORY);
TypeAdapter<Number> longAdapter = longAdapter(longSerializationPolicy);
factories.add(TypeAdapters.newFactory(long.class, Long.class, longAdapter));
factories.add(
TypeAdapters.newFactory(
double.class, Double.class, doubleAdapter(serializeSpecialFloatingPointValues)));
factories.add(
TypeAdapters.newFactory(
float.class, Float.class, floatAdapter(serializeSpecialFloatingPointValues)));
factories.add(NumberTypeAdapter.getFactory(numberToNumberStrategy));
2015-11-05 23:03:51 +01:00
factories.add(TypeAdapters.ATOMIC_INTEGER_FACTORY);
factories.add(TypeAdapters.ATOMIC_BOOLEAN_FACTORY);
factories.add(TypeAdapters.newFactory(AtomicLong.class, atomicLongAdapter(longAdapter)));
factories.add(
TypeAdapters.newFactory(AtomicLongArray.class, atomicLongArrayAdapter(longAdapter)));
2015-11-05 23:03:51 +01:00
factories.add(TypeAdapters.ATOMIC_INTEGER_ARRAY_FACTORY);
factories.add(TypeAdapters.CHARACTER_FACTORY);
factories.add(TypeAdapters.STRING_BUILDER_FACTORY);
factories.add(TypeAdapters.STRING_BUFFER_FACTORY);
factories.add(TypeAdapters.newFactory(BigDecimal.class, TypeAdapters.BIG_DECIMAL));
factories.add(TypeAdapters.newFactory(BigInteger.class, TypeAdapters.BIG_INTEGER));
// Add adapter for LazilyParsedNumber because user can obtain it from Gson and then try to
// serialize it again
factories.add(
TypeAdapters.newFactory(LazilyParsedNumber.class, TypeAdapters.LAZILY_PARSED_NUMBER));
factories.add(TypeAdapters.URL_FACTORY);
factories.add(TypeAdapters.URI_FACTORY);
factories.add(TypeAdapters.UUID_FACTORY);
2015-11-07 00:41:15 +01:00
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);
2020-05-09 17:37:21 +02:00
if (SqlTypesSupport.SUPPORTS_SQL_TYPES) {
factories.add(SqlTypesSupport.TIME_FACTORY);
factories.add(SqlTypesSupport.DATE_FACTORY);
factories.add(SqlTypesSupport.TIMESTAMP_FACTORY);
}
factories.add(ArrayTypeAdapter.FACTORY);
factories.add(TypeAdapters.CLASS_FACTORY);
// type adapters for composite and user-defined types
factories.add(new CollectionTypeAdapterFactory(constructorConstructor));
2021-04-21 08:31:23 +02:00
factories.add(new MapTypeAdapterFactory(constructorConstructor, complexMapKeySerialization, duplicateMapKeyDeserialization));
this.jsonAdapterFactory = new JsonAdapterAnnotationTypeAdapterFactory(constructorConstructor);
factories.add(jsonAdapterFactory);
factories.add(TypeAdapters.ENUM_FACTORY);
factories.add(
new ReflectiveTypeAdapterFactory(
constructorConstructor,
fieldNamingStrategy,
excluder,
jsonAdapterFactory,
reflectionFilters));
this.factories = Collections.unmodifiableList(factories);
}
/**
* Returns a new GsonBuilder containing all custom factories and configuration used by the current
* instance.
*
* @return a GsonBuilder instance.
* @since 2.8.3
*/
public GsonBuilder newBuilder() {
return new GsonBuilder(this);
}
/**
* 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;
}
2011-09-09 06:39:29 +02:00
private TypeAdapter<Number> doubleAdapter(boolean serializeSpecialFloatingPointValues) {
if (serializeSpecialFloatingPointValues) {
return TypeAdapters.DOUBLE;
}
2011-09-09 06:39:29 +02:00
return new TypeAdapter<Number>() {
2011-12-03 20:46:25 +01:00
@Override
public Double read(JsonReader in) throws IOException {
if (in.peek() == JsonToken.NULL) {
in.nextNull();
Down to 22 failing tests. Consolidated all of the different code paths that we use to construct instances. We now have an ObjectConstructor class that knows what type it constructs; this means that we don't need to ever do reflection to lookup a constructor at construction time. Cleaned up some buggy type adapters, particularly around handling of null. Removed dead code for object graph navigation. Moved some classes into 'internal' so they are visible to the 'bind' subpackage. Turned some TypeAdapterFactory/TypeAdapter pairs inside out so that the TypeAdapter is now the inner class. This is necessary so that the factories can take parameters. Added an API to request the 'next' type adapter for a type. This allows type adapters to compose other type adapters. We're using this in two places: - where the user has excluded a type from serialization but not deserialization, we need to use the "default" deserialization but interpose null on serialization. We create a type adapter that delegates for one and returns null for the other. - similarly when a DOM type serializer is registered but no deserializer, or vice versa. This is the biggest change to the MiniGson core. For backwards compatibility, return null for the empty string. Simplify JsonSerializationContext/JsonDeserializationContext to simply call through to GSON. SerializeDefault is currently unsupported. More useful error messages when calling getAsBoolean on a JsonNull. Remove currently unused MemoryRefStack. We might need this back again, though wiring it back in will be much more difficult because we don't interject ourselves between the users' various type adapters.
2011-09-11 09:04:56 +02:00
return null;
}
2011-12-03 20:46:25 +01:00
return in.nextDouble();
}
2011-12-03 20:46:25 +01:00
@Override
public void write(JsonWriter out, Number value) throws IOException {
Down to 22 failing tests. Consolidated all of the different code paths that we use to construct instances. We now have an ObjectConstructor class that knows what type it constructs; this means that we don't need to ever do reflection to lookup a constructor at construction time. Cleaned up some buggy type adapters, particularly around handling of null. Removed dead code for object graph navigation. Moved some classes into 'internal' so they are visible to the 'bind' subpackage. Turned some TypeAdapterFactory/TypeAdapter pairs inside out so that the TypeAdapter is now the inner class. This is necessary so that the factories can take parameters. Added an API to request the 'next' type adapter for a type. This allows type adapters to compose other type adapters. We're using this in two places: - where the user has excluded a type from serialization but not deserialization, we need to use the "default" deserialization but interpose null on serialization. We create a type adapter that delegates for one and returns null for the other. - similarly when a DOM type serializer is registered but no deserializer, or vice versa. This is the biggest change to the MiniGson core. For backwards compatibility, return null for the empty string. Simplify JsonSerializationContext/JsonDeserializationContext to simply call through to GSON. SerializeDefault is currently unsupported. More useful error messages when calling getAsBoolean on a JsonNull. Remove currently unused MemoryRefStack. We might need this back again, though wiring it back in will be much more difficult because we don't interject ourselves between the users' various type adapters.
2011-09-11 09:04:56 +02:00
if (value == null) {
2011-12-03 20:46:25 +01:00
out.nullValue();
Down to 22 failing tests. Consolidated all of the different code paths that we use to construct instances. We now have an ObjectConstructor class that knows what type it constructs; this means that we don't need to ever do reflection to lookup a constructor at construction time. Cleaned up some buggy type adapters, particularly around handling of null. Removed dead code for object graph navigation. Moved some classes into 'internal' so they are visible to the 'bind' subpackage. Turned some TypeAdapterFactory/TypeAdapter pairs inside out so that the TypeAdapter is now the inner class. This is necessary so that the factories can take parameters. Added an API to request the 'next' type adapter for a type. This allows type adapters to compose other type adapters. We're using this in two places: - where the user has excluded a type from serialization but not deserialization, we need to use the "default" deserialization but interpose null on serialization. We create a type adapter that delegates for one and returns null for the other. - similarly when a DOM type serializer is registered but no deserializer, or vice versa. This is the biggest change to the MiniGson core. For backwards compatibility, return null for the empty string. Simplify JsonSerializationContext/JsonDeserializationContext to simply call through to GSON. SerializeDefault is currently unsupported. More useful error messages when calling getAsBoolean on a JsonNull. Remove currently unused MemoryRefStack. We might need this back again, though wiring it back in will be much more difficult because we don't interject ourselves between the users' various type adapters.
2011-09-11 09:04:56 +02:00
return;
}
2011-09-09 06:39:29 +02:00
double doubleValue = value.doubleValue();
checkValidFloatingPoint(doubleValue);
out.value(doubleValue);
}
};
}
2011-09-09 06:39:29 +02:00
private TypeAdapter<Number> floatAdapter(boolean serializeSpecialFloatingPointValues) {
if (serializeSpecialFloatingPointValues) {
return TypeAdapters.FLOAT;
}
2011-09-09 06:39:29 +02:00
return new TypeAdapter<Number>() {
2011-12-03 20:46:25 +01:00
@Override
public Float read(JsonReader in) throws IOException {
if (in.peek() == JsonToken.NULL) {
in.nextNull();
Down to 22 failing tests. Consolidated all of the different code paths that we use to construct instances. We now have an ObjectConstructor class that knows what type it constructs; this means that we don't need to ever do reflection to lookup a constructor at construction time. Cleaned up some buggy type adapters, particularly around handling of null. Removed dead code for object graph navigation. Moved some classes into 'internal' so they are visible to the 'bind' subpackage. Turned some TypeAdapterFactory/TypeAdapter pairs inside out so that the TypeAdapter is now the inner class. This is necessary so that the factories can take parameters. Added an API to request the 'next' type adapter for a type. This allows type adapters to compose other type adapters. We're using this in two places: - where the user has excluded a type from serialization but not deserialization, we need to use the "default" deserialization but interpose null on serialization. We create a type adapter that delegates for one and returns null for the other. - similarly when a DOM type serializer is registered but no deserializer, or vice versa. This is the biggest change to the MiniGson core. For backwards compatibility, return null for the empty string. Simplify JsonSerializationContext/JsonDeserializationContext to simply call through to GSON. SerializeDefault is currently unsupported. More useful error messages when calling getAsBoolean on a JsonNull. Remove currently unused MemoryRefStack. We might need this back again, though wiring it back in will be much more difficult because we don't interject ourselves between the users' various type adapters.
2011-09-11 09:04:56 +02:00
return null;
}
2011-12-03 20:46:25 +01:00
return (float) in.nextDouble();
}
2011-12-03 20:46:25 +01:00
@Override
public void write(JsonWriter out, Number value) throws IOException {
Down to 22 failing tests. Consolidated all of the different code paths that we use to construct instances. We now have an ObjectConstructor class that knows what type it constructs; this means that we don't need to ever do reflection to lookup a constructor at construction time. Cleaned up some buggy type adapters, particularly around handling of null. Removed dead code for object graph navigation. Moved some classes into 'internal' so they are visible to the 'bind' subpackage. Turned some TypeAdapterFactory/TypeAdapter pairs inside out so that the TypeAdapter is now the inner class. This is necessary so that the factories can take parameters. Added an API to request the 'next' type adapter for a type. This allows type adapters to compose other type adapters. We're using this in two places: - where the user has excluded a type from serialization but not deserialization, we need to use the "default" deserialization but interpose null on serialization. We create a type adapter that delegates for one and returns null for the other. - similarly when a DOM type serializer is registered but no deserializer, or vice versa. This is the biggest change to the MiniGson core. For backwards compatibility, return null for the empty string. Simplify JsonSerializationContext/JsonDeserializationContext to simply call through to GSON. SerializeDefault is currently unsupported. More useful error messages when calling getAsBoolean on a JsonNull. Remove currently unused MemoryRefStack. We might need this back again, though wiring it back in will be much more difficult because we don't interject ourselves between the users' various type adapters.
2011-09-11 09:04:56 +02:00
if (value == null) {
2011-12-03 20:46:25 +01:00
out.nullValue();
Down to 22 failing tests. Consolidated all of the different code paths that we use to construct instances. We now have an ObjectConstructor class that knows what type it constructs; this means that we don't need to ever do reflection to lookup a constructor at construction time. Cleaned up some buggy type adapters, particularly around handling of null. Removed dead code for object graph navigation. Moved some classes into 'internal' so they are visible to the 'bind' subpackage. Turned some TypeAdapterFactory/TypeAdapter pairs inside out so that the TypeAdapter is now the inner class. This is necessary so that the factories can take parameters. Added an API to request the 'next' type adapter for a type. This allows type adapters to compose other type adapters. We're using this in two places: - where the user has excluded a type from serialization but not deserialization, we need to use the "default" deserialization but interpose null on serialization. We create a type adapter that delegates for one and returns null for the other. - similarly when a DOM type serializer is registered but no deserializer, or vice versa. This is the biggest change to the MiniGson core. For backwards compatibility, return null for the empty string. Simplify JsonSerializationContext/JsonDeserializationContext to simply call through to GSON. SerializeDefault is currently unsupported. More useful error messages when calling getAsBoolean on a JsonNull. Remove currently unused MemoryRefStack. We might need this back again, though wiring it back in will be much more difficult because we don't interject ourselves between the users' various type adapters.
2011-09-11 09:04:56 +02:00
return;
}
2011-09-09 06:39:29 +02:00
float floatValue = value.floatValue();
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);
}
};
}
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.");
}
}
2015-11-05 19:46:54 +01:00
private static TypeAdapter<Number> longAdapter(LongSerializationPolicy longSerializationPolicy) {
if (longSerializationPolicy == LongSerializationPolicy.DEFAULT) {
return TypeAdapters.LONG;
}
2011-09-09 06:39:29 +02:00
return new TypeAdapter<Number>() {
2011-12-03 20:46:25 +01:00
@Override
public Number read(JsonReader in) throws IOException {
if (in.peek() == JsonToken.NULL) {
in.nextNull();
Down to 22 failing tests. Consolidated all of the different code paths that we use to construct instances. We now have an ObjectConstructor class that knows what type it constructs; this means that we don't need to ever do reflection to lookup a constructor at construction time. Cleaned up some buggy type adapters, particularly around handling of null. Removed dead code for object graph navigation. Moved some classes into 'internal' so they are visible to the 'bind' subpackage. Turned some TypeAdapterFactory/TypeAdapter pairs inside out so that the TypeAdapter is now the inner class. This is necessary so that the factories can take parameters. Added an API to request the 'next' type adapter for a type. This allows type adapters to compose other type adapters. We're using this in two places: - where the user has excluded a type from serialization but not deserialization, we need to use the "default" deserialization but interpose null on serialization. We create a type adapter that delegates for one and returns null for the other. - similarly when a DOM type serializer is registered but no deserializer, or vice versa. This is the biggest change to the MiniGson core. For backwards compatibility, return null for the empty string. Simplify JsonSerializationContext/JsonDeserializationContext to simply call through to GSON. SerializeDefault is currently unsupported. More useful error messages when calling getAsBoolean on a JsonNull. Remove currently unused MemoryRefStack. We might need this back again, though wiring it back in will be much more difficult because we don't interject ourselves between the users' various type adapters.
2011-09-11 09:04:56 +02:00
return null;
}
2011-12-03 20:46:25 +01:00
return in.nextLong();
}
2011-12-03 20:46:25 +01:00
@Override
public void write(JsonWriter out, Number value) throws IOException {
Down to 22 failing tests. Consolidated all of the different code paths that we use to construct instances. We now have an ObjectConstructor class that knows what type it constructs; this means that we don't need to ever do reflection to lookup a constructor at construction time. Cleaned up some buggy type adapters, particularly around handling of null. Removed dead code for object graph navigation. Moved some classes into 'internal' so they are visible to the 'bind' subpackage. Turned some TypeAdapterFactory/TypeAdapter pairs inside out so that the TypeAdapter is now the inner class. This is necessary so that the factories can take parameters. Added an API to request the 'next' type adapter for a type. This allows type adapters to compose other type adapters. We're using this in two places: - where the user has excluded a type from serialization but not deserialization, we need to use the "default" deserialization but interpose null on serialization. We create a type adapter that delegates for one and returns null for the other. - similarly when a DOM type serializer is registered but no deserializer, or vice versa. This is the biggest change to the MiniGson core. For backwards compatibility, return null for the empty string. Simplify JsonSerializationContext/JsonDeserializationContext to simply call through to GSON. SerializeDefault is currently unsupported. More useful error messages when calling getAsBoolean on a JsonNull. Remove currently unused MemoryRefStack. We might need this back again, though wiring it back in will be much more difficult because we don't interject ourselves between the users' various type adapters.
2011-09-11 09:04:56 +02:00
if (value == null) {
2011-12-03 20:46:25 +01:00
out.nullValue();
Down to 22 failing tests. Consolidated all of the different code paths that we use to construct instances. We now have an ObjectConstructor class that knows what type it constructs; this means that we don't need to ever do reflection to lookup a constructor at construction time. Cleaned up some buggy type adapters, particularly around handling of null. Removed dead code for object graph navigation. Moved some classes into 'internal' so they are visible to the 'bind' subpackage. Turned some TypeAdapterFactory/TypeAdapter pairs inside out so that the TypeAdapter is now the inner class. This is necessary so that the factories can take parameters. Added an API to request the 'next' type adapter for a type. This allows type adapters to compose other type adapters. We're using this in two places: - where the user has excluded a type from serialization but not deserialization, we need to use the "default" deserialization but interpose null on serialization. We create a type adapter that delegates for one and returns null for the other. - similarly when a DOM type serializer is registered but no deserializer, or vice versa. This is the biggest change to the MiniGson core. For backwards compatibility, return null for the empty string. Simplify JsonSerializationContext/JsonDeserializationContext to simply call through to GSON. SerializeDefault is currently unsupported. More useful error messages when calling getAsBoolean on a JsonNull. Remove currently unused MemoryRefStack. We might need this back again, though wiring it back in will be much more difficult because we don't interject ourselves between the users' various type adapters.
2011-09-11 09:04:56 +02:00
return;
}
2011-12-03 20:46:25 +01:00
out.value(value.toString());
}
};
2008-09-01 05:13:32 +02:00
}
2015-11-05 19:46:54 +01:00
private static TypeAdapter<AtomicLong> atomicLongAdapter(final TypeAdapter<Number> longAdapter) {
return new TypeAdapter<AtomicLong>() {
@Override
public void write(JsonWriter out, AtomicLong value) throws IOException {
longAdapter.write(out, value.get());
}
@Override
public AtomicLong read(JsonReader in) throws IOException {
Number value = longAdapter.read(in);
return new AtomicLong(value.longValue());
}
}.nullSafe();
}
private static TypeAdapter<AtomicLongArray> atomicLongArrayAdapter(
final TypeAdapter<Number> longAdapter) {
return new TypeAdapter<AtomicLongArray>() {
@Override
public void write(JsonWriter out, AtomicLongArray value) throws IOException {
out.beginArray();
for (int i = 0, length = value.length(); i < length; i++) {
longAdapter.write(out, value.get(i));
}
out.endArray();
}
@Override
public AtomicLongArray read(JsonReader in) throws IOException {
List<Long> list = new ArrayList<>();
in.beginArray();
while (in.hasNext()) {
long value = longAdapter.read(in).longValue();
list.add(value);
}
in.endArray();
int length = list.size();
AtomicLongArray array = new AtomicLongArray(length);
for (int i = 0; i < length; ++i) {
array.set(i, list.get(i));
}
return array;
}
}.nullSafe();
}
/**
* Returns the type adapter for {@code type}.
*
* <p>When calling this method concurrently from multiple threads and requesting an adapter for
* the same type this method may return different {@code TypeAdapter} instances. However, that
* should normally not be an issue because {@code TypeAdapter} implementations are supposed to be
* stateless.
*
* @throws IllegalArgumentException if this Gson instance cannot serialize and deserialize {@code
* type}.
*/
public <T> TypeAdapter<T> getAdapter(TypeToken<T> type) {
Objects.requireNonNull(type, "type must not be null");
TypeAdapter<?> cached = typeTokenCache.get(type);
if (cached != null) {
@SuppressWarnings("unchecked")
TypeAdapter<T> adapter = (TypeAdapter<T>) cached;
return adapter;
}
Map<TypeToken<?>, 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<T> ongoingCall = (TypeAdapter<T>) threadCalls.get(type);
if (ongoingCall != null) {
return ongoingCall;
}
}
TypeAdapter<T> candidate = null;
try {
FutureTypeAdapter<T> call = new FutureTypeAdapter<>();
2013-01-14 23:05:28 +01:00
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();
2013-01-14 23:05:28 +01:00
}
}
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 <T> TypeAdapter<T> getAdapter(Class<T> 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:
*
* <p>Let's say we want to write a type adapter that counts the number of objects being read from
Perform minor code clean-up (#2544) * Perform minor code clean-up Notable changes: - Replace most usages of `<code>` with `{@code ...}` in Javadoc - Add proper summary sentence to `GsonBuilder.enableComplexMapKeySerialization` - Extend documentation for `GsonBuilder.setDateFormat` methods - Fix `TypeToken.isAssignableFrom(Type)` throwing AssertionError in some cases Maybe the method should not throw an exception in the first place, but it might not matter much since it is deprecated already anyway. - Remove outdated `throws NumberFormatException` from internal `JsonReader.nextQuotedValue`; the behavior had been changed by 85ebaf7c3553a5d5c058fd6067824a7c5258d07f - Fix incorrect documentation on JsonScope fields - Fix unit tests having 'expected' and 'actual' switched - Use dedicated Truth methods instead of `isTrue()` / `isFalse()` - Use common helper methods in JsonWriterTest to avoid duplication * Implement `toString()` for ReflectionAccessFilter constants * Address most of the review comments * Add comment about `source.scm.tag=HEAD` warning Actually it looks like the warning is not actually caused by usage of `HEAD` as value, but rather because the project has a snapshot version during development (which is expected though), see https://github.com/apache/maven-artifact-plugin/blob/maven-artifact-plugin-3.5.0/src/main/java/org/apache/maven/plugins/artifact/buildinfo/BuildInfoWriter.java#L140 But this is not a problem either since during release a non-snapshot version is used.
2023-11-19 18:01:19 +01:00
* or written to JSON. We can achieve this by writing a type adapter factory that uses the {@code
* getDelegateAdapter} method:
*
* <pre>{@code
* class StatsTypeAdapterFactory implements TypeAdapterFactory {
* public int numReads = 0;
* public int numWrites = 0;
* public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
* final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
* return new TypeAdapter<T>() {
* public void write(JsonWriter out, T value) throws IOException {
* ++numWrites;
* delegate.write(out, value);
* }
* public T read(JsonReader in) throws IOException {
* ++numReads;
* return delegate.read(in);
* }
* };
* }
* }
* }</pre>
*
* This factory can now be used like this:
*
* <pre>{@code
* StatsTypeAdapterFactory stats = new StatsTypeAdapterFactory();
* Gson gson = new GsonBuilder().registerTypeAdapterFactory(stats).create();
* // Call gson.toJson() and fromJson methods on objects
* System.out.println("Num JSON reads: " + stats.numReads);
* System.out.println("Num JSON writes: " + stats.numWrites);
* }</pre>
*
* Note that this call will skip all factories registered before {@code skipPast}. In case of
* multiple TypeAdapterFactories registered it is up to the caller of this function to 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.
*
* <p>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 <i>this</i> (the type adapter
* factory from where {@code getDelegateAdapter} method is being invoked).
* @param type Type for which the delegate adapter is being searched for.
* @since 2.2
*/
public <T> TypeAdapter<T> getDelegateAdapter(TypeAdapterFactory skipPast, TypeToken<T> type) {
Objects.requireNonNull(skipPast, "skipPast must not be null");
Objects.requireNonNull(type, "type must not be null");
if (jsonAdapterFactory.isClassJsonAdapterFactory(type, skipPast)) {
skipPast = jsonAdapterFactory;
}
2016-06-15 01:34:34 +02:00
boolean skipPastFound = false;
for (TypeAdapterFactory factory : factories) {
if (!skipPastFound) {
if (factory == skipPast) {
skipPastFound = true;
}
continue;
}
TypeAdapter<T> candidate = factory.create(this, type);
if (candidate != null) {
return candidate;
}
}
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
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* 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.
*
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* @param src the object for which JSON representation is to be created
* @return JSON representation of {@code src}.
* @since 1.4
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* @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<Foo>}, you should use:
* <pre>
* Type typeOfSrc = new TypeToken&lt;Collection&lt;Foo&gt;&gt;(){}.getType();
* </pre>
*
* @return JSON representation of {@code src}.
* @since 1.4
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* @see #toJsonTree(Object)
*/
public JsonElement toJsonTree(Object src, Type typeOfSrc) {
JsonTreeWriter writer = new JsonTreeWriter();
toJson(src, typeOfSrc, writer);
return writer.get();
}
2008-09-01 05:13:32 +02:00
/**
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* This method serializes the specified object into its equivalent JSON representation. This
2008-09-01 05:13:32 +02:00
* 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
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* works fine if any of the object fields are of generic type, just the object itself should not
2008-09-01 05:13:32 +02:00
* 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.
2008-09-01 05:13:32 +02:00
*
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* @param src the object for which JSON representation is to be created
* @return JSON representation of {@code src}.
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* @see #toJson(Object, Appendable)
* @see #toJson(Object, Type)
2008-09-01 05:13:32 +02:00
*/
public String toJson(Object src) {
if (src == null) {
return toJson(JsonNull.INSTANCE);
2008-09-01 05:13:32 +02:00
}
return toJson(src, src.getClass());
2008-09-01 05:13:32 +02:00
}
/**
* This method serializes the specified object, including those of generic types, into its
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* equivalent JSON representation. This method must be used if the specified object is a generic
2008-09-01 05:13:32 +02:00
* 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.
2008-09-01 05:13:32 +02:00
*
* @param src the object for which JSON representation is to be created
* @param typeOfSrc The specific genericized type of src. You can obtain this type by using the
* {@link com.google.gson.reflect.TypeToken} class. For example, to get the type for {@code
* Collection<Foo>}, you should use:
* <pre>
* Type typeOfSrc = new TypeToken&lt;Collection&lt;Foo&gt;&gt;(){}.getType();
* </pre>
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
*
* @return JSON representation of {@code src}.
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* @see #toJson(Object, Type, Appendable)
* @see #toJson(Object)
2008-09-01 05:13:32 +02:00
*/
public String toJson(Object src, Type typeOfSrc) {
StringWriter writer = new StringWriter();
toJson(src, typeOfSrc, writer);
2008-09-01 05:13:32 +02:00
return writer.toString();
}
2008-09-01 05:13:32 +02:00
/**
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* This method serializes the specified object into its equivalent JSON representation and writes
2008-09-01 05:13:32 +02:00
* 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
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* Java. Note that this method works fine if any of the object fields are of generic type, just
2008-09-01 05:13:32 +02:00
* the object itself should not be of a generic type. If the object is of generic type, use {@link
* #toJson(Object, Type, Appendable)} instead.
2008-09-01 05:13:32 +02:00
*
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* @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
2008-09-01 05:13:32 +02:00
* @since 1.2
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* @see #toJson(Object)
* @see #toJson(Object, Type, Appendable)
2008-09-01 05:13:32 +02:00
*/
public void toJson(Object src, Appendable writer) throws JsonIOException {
2011-01-22 23:43:43 +01:00
if (src != null) {
toJson(src, src.getClass(), writer);
} else {
toJson(JsonNull.INSTANCE, writer);
2008-09-01 05:13:32 +02:00
}
}
/**
* This method serializes the specified object, including those of generic types, into its
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* 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.
2008-09-01 05:13:32 +02:00
*
* @param src the object for which JSON representation is to be created
* @param typeOfSrc The specific genericized type of src. You can obtain this type by using the
* {@link com.google.gson.reflect.TypeToken} class. For example, to get the type for {@code
* Collection<Foo>}, you should use:
* <pre>
* Type typeOfSrc = new TypeToken&lt;Collection&lt;Foo&gt;&gt;(){}.getType();
* </pre>
*
Strict mode for JSON parsing, contributed by @marten-voorberg. (#2437) * Strict mode for JSON parsing (#2323) * Feat #6: Add strict flag to Gson and GsonBuilder * Test #2: Add failing tests for capitalized keywords * Feat #2: JsonReader does not read (partially) capitalized keywords if strict mode is used * Feat #3: Added implementation and tests for JSONReader not accepting specific escape sequence representing in strict mode * Test #3: Simplify test cases by removing unnecessary array * Feat #3: Improve error by including the illegal character * Feat #5: JsonReader does not allow unespaced control flow characters in strict mode * Test #5: Test unespaced control flow characters in strict mode * Feat #4: Disallow espaced newline character in strict mode * Test #4: Add tests for (dis)allowing newline character depensding on strictness * Test #5: Test case for unescaped control char in non-strict mode * Test #2: Simplify test cases * Feat #13: Change leniency API to Strictness enum in JsonReader, Gson, and GsonBuilder * Feat #15: Change JsonWriter API to also use Strictness * Test #15: Test Strictness in JsonWriter API * Doc #15: Add and update documentation for Strictness in JsonWriter API * refactor #12: Fixed typos and empty catch brackets in tests * refactor #12: Resolved importing wildcards, made some lines adhere to Google java style * #5 Add test case for unescaped control characters * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue --------- Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * Doc #17: Add and change javadoc of public methods * Doc #17: Update JavaDoc in JsonReader and Strictness * Doc #17: Update JavaDoc in Gson and GsonBuilder * Test #34: Add tests for setting strictness through GsonBuilder * Fix: Add Fix broken test * Fix: Invalid JavaDoc in Gson.java * Doc #17: update outdated javadoc * #37: Resolve more PR feedback * Fix #37: Resolve various PR comments * Fix #37: Resolve various PR comments * Refactor #35: Refactor JsonReader#peekKeyword to reduce the amount of strictness checks (#39) * Doc #40: Update JavaDoc based on PR feedback * Doc #40: Update old RFC in GsonBuilder documentation * Doc #40: Fix formatting error in JavaDoc * Doc #40: Add tests for setting strictness and lenient to JsonReaderTest * Test #43: Changed tests to make use of assertThrows * test #43: Changed tests to make use of assertThrows as per feedback * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * test #43: Resolve PR recommendations * Test #43: Mini change to TC * Test #43: Mini change to TC --------- Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * doc #46: Resolved comments in main PR * Feat #45: Change Gson.fromJson and Gson.toJson to be strict when the provided writer/reader is strict * Fix #45: Small type * Update gson/src/test/java/com/google/gson/stream/JsonReaderTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Update gson/src/main/java/com/google/gson/GsonBuilder.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Fix #45: Resolve various comments by eamonmcmanus * Strictness mode follow-up * Update Troubleshooting.md and Gson default lenient mode documentation * Always use GSON strictness when set. * Rename Strictness.DEFAULT to Strictness.LEGACY_STRICT * Update JavaDoc with new strictness functionality * Replace default with legacy strict for JsonReader javadoc * Add JSONReader test cases for U2028 and U2029 * Refactor JSONReader#peekKeyWord() based on @eamonmcmanus's suggestion * Deprecate setLenient in favor of setStrictness --------- Co-authored-by: Carl Peterson <unknown> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Strictness follow-up (#2408) * Strictness mode follow-up - Remove mentions of `null` Gson strictness; this is an implementation detail - Fix incorrect / outdated documentation - Reduce links to RFC; if there is already a link to it in a previous sentence don't link to it again - Extend and update tests - Minor punctuation changes in documentation for consistency * Deprecate `setLenient` methods * `strictness2` fixes & improvements (#2456) * Adjust ProGuard default rules and shrinking tests (#2420) * Adjust ProGuard default rules and shrinking tests * Adjust comment * Add shrinking test for class without no-args constructor; improve docs * Improve Unsafe mention in Troubleshooting Guide * Improve comment for `-if class *` * Bump com.google.guava:guava from 32.0.1-jre to 32.1.1-jre (#2444) Bumps [com.google.guava:guava](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Bump com.google.guava:guava-testlib from 32.0.1-jre to 32.1.1-jre (#2443) Bumps [com.google.guava:guava-testlib](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava-testlib dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Support non-generic type for `TypeToken.getParameterized` for legacy reasons (#2447) This partially restores the behavior before a589ef20087b4b0f1ec3048d3ceaef1eedccd09d, except that back then for a non-generic type a bogus `TypeToken(ParameterizedType)` was created, whereas now a `TypeToken(Class)` is created instead. * Fixed Typo in GsonBuilder.java (#2449) * Make date-formatting tests less fragile with regular expressions. (#2450) * Make date-formatting tests less fragile with regular expressions. This is not great. We should really ensure that formatted dates are the same regardless of JDK version. There is code that attempts to do that but it is not really effective. So for now we fudge around the differences by using regular expressions to paper over the differences. * Temporarily add test-debugging code. * Another attempt at debugging a test failure. * Fix pattern in assertion. * Modification in test cases (#2454) * Fixed Typo in GsonBuilder.java * Suggestions on Test cases * Modified test cases using assertThrows method (JUnit) * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/GsonTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> --------- Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Minor follow-up changes --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Éamonn McManus <emcmanus@google.com> Co-authored-by: Wonil <cwi5525@naver.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Marten <martenvoorberg@gmail.com> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Wonil <cwi5525@naver.com>
2023-07-30 18:20:32 +02:00
* @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
2008-09-01 05:13:32 +02:00
* @since 1.2
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* @see #toJson(Object, Type)
* @see #toJson(Object, Appendable)
2008-09-01 05:13:32 +02:00
*/
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}.
*
Strict mode for JSON parsing, contributed by @marten-voorberg. (#2437) * Strict mode for JSON parsing (#2323) * Feat #6: Add strict flag to Gson and GsonBuilder * Test #2: Add failing tests for capitalized keywords * Feat #2: JsonReader does not read (partially) capitalized keywords if strict mode is used * Feat #3: Added implementation and tests for JSONReader not accepting specific escape sequence representing in strict mode * Test #3: Simplify test cases by removing unnecessary array * Feat #3: Improve error by including the illegal character * Feat #5: JsonReader does not allow unespaced control flow characters in strict mode * Test #5: Test unespaced control flow characters in strict mode * Feat #4: Disallow espaced newline character in strict mode * Test #4: Add tests for (dis)allowing newline character depensding on strictness * Test #5: Test case for unescaped control char in non-strict mode * Test #2: Simplify test cases * Feat #13: Change leniency API to Strictness enum in JsonReader, Gson, and GsonBuilder * Feat #15: Change JsonWriter API to also use Strictness * Test #15: Test Strictness in JsonWriter API * Doc #15: Add and update documentation for Strictness in JsonWriter API * refactor #12: Fixed typos and empty catch brackets in tests * refactor #12: Resolved importing wildcards, made some lines adhere to Google java style * #5 Add test case for unescaped control characters * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue --------- Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * Doc #17: Add and change javadoc of public methods * Doc #17: Update JavaDoc in JsonReader and Strictness * Doc #17: Update JavaDoc in Gson and GsonBuilder * Test #34: Add tests for setting strictness through GsonBuilder * Fix: Add Fix broken test * Fix: Invalid JavaDoc in Gson.java * Doc #17: update outdated javadoc * #37: Resolve more PR feedback * Fix #37: Resolve various PR comments * Fix #37: Resolve various PR comments * Refactor #35: Refactor JsonReader#peekKeyword to reduce the amount of strictness checks (#39) * Doc #40: Update JavaDoc based on PR feedback * Doc #40: Update old RFC in GsonBuilder documentation * Doc #40: Fix formatting error in JavaDoc * Doc #40: Add tests for setting strictness and lenient to JsonReaderTest * Test #43: Changed tests to make use of assertThrows * test #43: Changed tests to make use of assertThrows as per feedback * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * test #43: Resolve PR recommendations * Test #43: Mini change to TC * Test #43: Mini change to TC --------- Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * doc #46: Resolved comments in main PR * Feat #45: Change Gson.fromJson and Gson.toJson to be strict when the provided writer/reader is strict * Fix #45: Small type * Update gson/src/test/java/com/google/gson/stream/JsonReaderTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Update gson/src/main/java/com/google/gson/GsonBuilder.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Fix #45: Resolve various comments by eamonmcmanus * Strictness mode follow-up * Update Troubleshooting.md and Gson default lenient mode documentation * Always use GSON strictness when set. * Rename Strictness.DEFAULT to Strictness.LEGACY_STRICT * Update JavaDoc with new strictness functionality * Replace default with legacy strict for JsonReader javadoc * Add JSONReader test cases for U2028 and U2029 * Refactor JSONReader#peekKeyWord() based on @eamonmcmanus's suggestion * Deprecate setLenient in favor of setStrictness --------- Co-authored-by: Carl Peterson <unknown> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Strictness follow-up (#2408) * Strictness mode follow-up - Remove mentions of `null` Gson strictness; this is an implementation detail - Fix incorrect / outdated documentation - Reduce links to RFC; if there is already a link to it in a previous sentence don't link to it again - Extend and update tests - Minor punctuation changes in documentation for consistency * Deprecate `setLenient` methods * `strictness2` fixes & improvements (#2456) * Adjust ProGuard default rules and shrinking tests (#2420) * Adjust ProGuard default rules and shrinking tests * Adjust comment * Add shrinking test for class without no-args constructor; improve docs * Improve Unsafe mention in Troubleshooting Guide * Improve comment for `-if class *` * Bump com.google.guava:guava from 32.0.1-jre to 32.1.1-jre (#2444) Bumps [com.google.guava:guava](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Bump com.google.guava:guava-testlib from 32.0.1-jre to 32.1.1-jre (#2443) Bumps [com.google.guava:guava-testlib](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava-testlib dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Support non-generic type for `TypeToken.getParameterized` for legacy reasons (#2447) This partially restores the behavior before a589ef20087b4b0f1ec3048d3ceaef1eedccd09d, except that back then for a non-generic type a bogus `TypeToken(ParameterizedType)` was created, whereas now a `TypeToken(Class)` is created instead. * Fixed Typo in GsonBuilder.java (#2449) * Make date-formatting tests less fragile with regular expressions. (#2450) * Make date-formatting tests less fragile with regular expressions. This is not great. We should really ensure that formatted dates are the same regardless of JDK version. There is code that attempts to do that but it is not really effective. So for now we fudge around the differences by using regular expressions to paper over the differences. * Temporarily add test-debugging code. * Another attempt at debugging a test failure. * Fix pattern in assertion. * Modification in test cases (#2454) * Fixed Typo in GsonBuilder.java * Suggestions on Test cases * Modified test cases using assertThrows method (JUnit) * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/GsonTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> --------- Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Minor follow-up changes --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Éamonn McManus <emcmanus@google.com> Co-authored-by: Wonil <cwi5525@naver.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Marten <martenvoorberg@gmail.com> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Wonil <cwi5525@naver.com>
2023-07-30 18:20:32 +02:00
* <p>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.<br>
* Note that in all cases the old strictness setting of the writer will be restored when this
* method returns.
*
* <p>The 'HTML-safe' and 'serialize {@code null}' settings of this {@code Gson} instance
* (configured by the {@link GsonBuilder}) are applied, and the original settings of the writer
* are restored once this method returns.
*
Strict mode for JSON parsing, contributed by @marten-voorberg. (#2437) * Strict mode for JSON parsing (#2323) * Feat #6: Add strict flag to Gson and GsonBuilder * Test #2: Add failing tests for capitalized keywords * Feat #2: JsonReader does not read (partially) capitalized keywords if strict mode is used * Feat #3: Added implementation and tests for JSONReader not accepting specific escape sequence representing in strict mode * Test #3: Simplify test cases by removing unnecessary array * Feat #3: Improve error by including the illegal character * Feat #5: JsonReader does not allow unespaced control flow characters in strict mode * Test #5: Test unespaced control flow characters in strict mode * Feat #4: Disallow espaced newline character in strict mode * Test #4: Add tests for (dis)allowing newline character depensding on strictness * Test #5: Test case for unescaped control char in non-strict mode * Test #2: Simplify test cases * Feat #13: Change leniency API to Strictness enum in JsonReader, Gson, and GsonBuilder * Feat #15: Change JsonWriter API to also use Strictness * Test #15: Test Strictness in JsonWriter API * Doc #15: Add and update documentation for Strictness in JsonWriter API * refactor #12: Fixed typos and empty catch brackets in tests * refactor #12: Resolved importing wildcards, made some lines adhere to Google java style * #5 Add test case for unescaped control characters * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue --------- Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * Doc #17: Add and change javadoc of public methods * Doc #17: Update JavaDoc in JsonReader and Strictness * Doc #17: Update JavaDoc in Gson and GsonBuilder * Test #34: Add tests for setting strictness through GsonBuilder * Fix: Add Fix broken test * Fix: Invalid JavaDoc in Gson.java * Doc #17: update outdated javadoc * #37: Resolve more PR feedback * Fix #37: Resolve various PR comments * Fix #37: Resolve various PR comments * Refactor #35: Refactor JsonReader#peekKeyword to reduce the amount of strictness checks (#39) * Doc #40: Update JavaDoc based on PR feedback * Doc #40: Update old RFC in GsonBuilder documentation * Doc #40: Fix formatting error in JavaDoc * Doc #40: Add tests for setting strictness and lenient to JsonReaderTest * Test #43: Changed tests to make use of assertThrows * test #43: Changed tests to make use of assertThrows as per feedback * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * test #43: Resolve PR recommendations * Test #43: Mini change to TC * Test #43: Mini change to TC --------- Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * doc #46: Resolved comments in main PR * Feat #45: Change Gson.fromJson and Gson.toJson to be strict when the provided writer/reader is strict * Fix #45: Small type * Update gson/src/test/java/com/google/gson/stream/JsonReaderTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Update gson/src/main/java/com/google/gson/GsonBuilder.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Fix #45: Resolve various comments by eamonmcmanus * Strictness mode follow-up * Update Troubleshooting.md and Gson default lenient mode documentation * Always use GSON strictness when set. * Rename Strictness.DEFAULT to Strictness.LEGACY_STRICT * Update JavaDoc with new strictness functionality * Replace default with legacy strict for JsonReader javadoc * Add JSONReader test cases for U2028 and U2029 * Refactor JSONReader#peekKeyWord() based on @eamonmcmanus's suggestion * Deprecate setLenient in favor of setStrictness --------- Co-authored-by: Carl Peterson <unknown> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Strictness follow-up (#2408) * Strictness mode follow-up - Remove mentions of `null` Gson strictness; this is an implementation detail - Fix incorrect / outdated documentation - Reduce links to RFC; if there is already a link to it in a previous sentence don't link to it again - Extend and update tests - Minor punctuation changes in documentation for consistency * Deprecate `setLenient` methods * `strictness2` fixes & improvements (#2456) * Adjust ProGuard default rules and shrinking tests (#2420) * Adjust ProGuard default rules and shrinking tests * Adjust comment * Add shrinking test for class without no-args constructor; improve docs * Improve Unsafe mention in Troubleshooting Guide * Improve comment for `-if class *` * Bump com.google.guava:guava from 32.0.1-jre to 32.1.1-jre (#2444) Bumps [com.google.guava:guava](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Bump com.google.guava:guava-testlib from 32.0.1-jre to 32.1.1-jre (#2443) Bumps [com.google.guava:guava-testlib](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava-testlib dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Support non-generic type for `TypeToken.getParameterized` for legacy reasons (#2447) This partially restores the behavior before a589ef20087b4b0f1ec3048d3ceaef1eedccd09d, except that back then for a non-generic type a bogus `TypeToken(ParameterizedType)` was created, whereas now a `TypeToken(Class)` is created instead. * Fixed Typo in GsonBuilder.java (#2449) * Make date-formatting tests less fragile with regular expressions. (#2450) * Make date-formatting tests less fragile with regular expressions. This is not great. We should really ensure that formatted dates are the same regardless of JDK version. There is code that attempts to do that but it is not really effective. So for now we fudge around the differences by using regular expressions to paper over the differences. * Temporarily add test-debugging code. * Another attempt at debugging a test failure. * Fix pattern in assertion. * Modification in test cases (#2454) * Fixed Typo in GsonBuilder.java * Suggestions on Test cases * Modified test cases using assertThrows method (JUnit) * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/GsonTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> --------- Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Minor follow-up changes --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Éamonn McManus <emcmanus@google.com> Co-authored-by: Wonil <cwi5525@naver.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Marten <martenvoorberg@gmail.com> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Wonil <cwi5525@naver.com>
2023-07-30 18:20:32 +02:00
* @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<Object> adapter = (TypeAdapter<Object>) getAdapter(TypeToken.get(typeOfSrc));
Strict mode for JSON parsing, contributed by @marten-voorberg. (#2437) * Strict mode for JSON parsing (#2323) * Feat #6: Add strict flag to Gson and GsonBuilder * Test #2: Add failing tests for capitalized keywords * Feat #2: JsonReader does not read (partially) capitalized keywords if strict mode is used * Feat #3: Added implementation and tests for JSONReader not accepting specific escape sequence representing in strict mode * Test #3: Simplify test cases by removing unnecessary array * Feat #3: Improve error by including the illegal character * Feat #5: JsonReader does not allow unespaced control flow characters in strict mode * Test #5: Test unespaced control flow characters in strict mode * Feat #4: Disallow espaced newline character in strict mode * Test #4: Add tests for (dis)allowing newline character depensding on strictness * Test #5: Test case for unescaped control char in non-strict mode * Test #2: Simplify test cases * Feat #13: Change leniency API to Strictness enum in JsonReader, Gson, and GsonBuilder * Feat #15: Change JsonWriter API to also use Strictness * Test #15: Test Strictness in JsonWriter API * Doc #15: Add and update documentation for Strictness in JsonWriter API * refactor #12: Fixed typos and empty catch brackets in tests * refactor #12: Resolved importing wildcards, made some lines adhere to Google java style * #5 Add test case for unescaped control characters * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue --------- Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * Doc #17: Add and change javadoc of public methods * Doc #17: Update JavaDoc in JsonReader and Strictness * Doc #17: Update JavaDoc in Gson and GsonBuilder * Test #34: Add tests for setting strictness through GsonBuilder * Fix: Add Fix broken test * Fix: Invalid JavaDoc in Gson.java * Doc #17: update outdated javadoc * #37: Resolve more PR feedback * Fix #37: Resolve various PR comments * Fix #37: Resolve various PR comments * Refactor #35: Refactor JsonReader#peekKeyword to reduce the amount of strictness checks (#39) * Doc #40: Update JavaDoc based on PR feedback * Doc #40: Update old RFC in GsonBuilder documentation * Doc #40: Fix formatting error in JavaDoc * Doc #40: Add tests for setting strictness and lenient to JsonReaderTest * Test #43: Changed tests to make use of assertThrows * test #43: Changed tests to make use of assertThrows as per feedback * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * test #43: Resolve PR recommendations * Test #43: Mini change to TC * Test #43: Mini change to TC --------- Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * doc #46: Resolved comments in main PR * Feat #45: Change Gson.fromJson and Gson.toJson to be strict when the provided writer/reader is strict * Fix #45: Small type * Update gson/src/test/java/com/google/gson/stream/JsonReaderTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Update gson/src/main/java/com/google/gson/GsonBuilder.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Fix #45: Resolve various comments by eamonmcmanus * Strictness mode follow-up * Update Troubleshooting.md and Gson default lenient mode documentation * Always use GSON strictness when set. * Rename Strictness.DEFAULT to Strictness.LEGACY_STRICT * Update JavaDoc with new strictness functionality * Replace default with legacy strict for JsonReader javadoc * Add JSONReader test cases for U2028 and U2029 * Refactor JSONReader#peekKeyWord() based on @eamonmcmanus's suggestion * Deprecate setLenient in favor of setStrictness --------- Co-authored-by: Carl Peterson <unknown> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Strictness follow-up (#2408) * Strictness mode follow-up - Remove mentions of `null` Gson strictness; this is an implementation detail - Fix incorrect / outdated documentation - Reduce links to RFC; if there is already a link to it in a previous sentence don't link to it again - Extend and update tests - Minor punctuation changes in documentation for consistency * Deprecate `setLenient` methods * `strictness2` fixes & improvements (#2456) * Adjust ProGuard default rules and shrinking tests (#2420) * Adjust ProGuard default rules and shrinking tests * Adjust comment * Add shrinking test for class without no-args constructor; improve docs * Improve Unsafe mention in Troubleshooting Guide * Improve comment for `-if class *` * Bump com.google.guava:guava from 32.0.1-jre to 32.1.1-jre (#2444) Bumps [com.google.guava:guava](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Bump com.google.guava:guava-testlib from 32.0.1-jre to 32.1.1-jre (#2443) Bumps [com.google.guava:guava-testlib](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava-testlib dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Support non-generic type for `TypeToken.getParameterized` for legacy reasons (#2447) This partially restores the behavior before a589ef20087b4b0f1ec3048d3ceaef1eedccd09d, except that back then for a non-generic type a bogus `TypeToken(ParameterizedType)` was created, whereas now a `TypeToken(Class)` is created instead. * Fixed Typo in GsonBuilder.java (#2449) * Make date-formatting tests less fragile with regular expressions. (#2450) * Make date-formatting tests less fragile with regular expressions. This is not great. We should really ensure that formatted dates are the same regardless of JDK version. There is code that attempts to do that but it is not really effective. So for now we fudge around the differences by using regular expressions to paper over the differences. * Temporarily add test-debugging code. * Another attempt at debugging a test failure. * Fix pattern in assertion. * Modification in test cases (#2454) * Fixed Typo in GsonBuilder.java * Suggestions on Test cases * Modified test cases using assertThrows method (JUnit) * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/GsonTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> --------- Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Minor follow-up changes --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Éamonn McManus <emcmanus@google.com> Co-authored-by: Wonil <cwi5525@naver.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Marten <martenvoorberg@gmail.com> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Wonil <cwi5525@naver.com>
2023-07-30 18:20:32 +02:00
Strictness oldStrictness = writer.getStrictness();
if (this.strictness != null) {
writer.setStrictness(this.strictness);
} else if (writer.getStrictness() != Strictness.STRICT) {
writer.setStrictness(Strictness.LENIENT);
}
2022-05-17 21:20:10 +02:00
boolean oldOmitQuotes = writer.getOmitQuotes();
boolean oldHtmlSafe = writer.isHtmlSafe();
boolean oldSerializeNulls = writer.getSerializeNulls();
Strict mode for JSON parsing, contributed by @marten-voorberg. (#2437) * Strict mode for JSON parsing (#2323) * Feat #6: Add strict flag to Gson and GsonBuilder * Test #2: Add failing tests for capitalized keywords * Feat #2: JsonReader does not read (partially) capitalized keywords if strict mode is used * Feat #3: Added implementation and tests for JSONReader not accepting specific escape sequence representing in strict mode * Test #3: Simplify test cases by removing unnecessary array * Feat #3: Improve error by including the illegal character * Feat #5: JsonReader does not allow unespaced control flow characters in strict mode * Test #5: Test unespaced control flow characters in strict mode * Feat #4: Disallow espaced newline character in strict mode * Test #4: Add tests for (dis)allowing newline character depensding on strictness * Test #5: Test case for unescaped control char in non-strict mode * Test #2: Simplify test cases * Feat #13: Change leniency API to Strictness enum in JsonReader, Gson, and GsonBuilder * Feat #15: Change JsonWriter API to also use Strictness * Test #15: Test Strictness in JsonWriter API * Doc #15: Add and update documentation for Strictness in JsonWriter API * refactor #12: Fixed typos and empty catch brackets in tests * refactor #12: Resolved importing wildcards, made some lines adhere to Google java style * #5 Add test case for unescaped control characters * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue --------- Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * Doc #17: Add and change javadoc of public methods * Doc #17: Update JavaDoc in JsonReader and Strictness * Doc #17: Update JavaDoc in Gson and GsonBuilder * Test #34: Add tests for setting strictness through GsonBuilder * Fix: Add Fix broken test * Fix: Invalid JavaDoc in Gson.java * Doc #17: update outdated javadoc * #37: Resolve more PR feedback * Fix #37: Resolve various PR comments * Fix #37: Resolve various PR comments * Refactor #35: Refactor JsonReader#peekKeyword to reduce the amount of strictness checks (#39) * Doc #40: Update JavaDoc based on PR feedback * Doc #40: Update old RFC in GsonBuilder documentation * Doc #40: Fix formatting error in JavaDoc * Doc #40: Add tests for setting strictness and lenient to JsonReaderTest * Test #43: Changed tests to make use of assertThrows * test #43: Changed tests to make use of assertThrows as per feedback * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * test #43: Resolve PR recommendations * Test #43: Mini change to TC * Test #43: Mini change to TC --------- Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * doc #46: Resolved comments in main PR * Feat #45: Change Gson.fromJson and Gson.toJson to be strict when the provided writer/reader is strict * Fix #45: Small type * Update gson/src/test/java/com/google/gson/stream/JsonReaderTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Update gson/src/main/java/com/google/gson/GsonBuilder.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Fix #45: Resolve various comments by eamonmcmanus * Strictness mode follow-up * Update Troubleshooting.md and Gson default lenient mode documentation * Always use GSON strictness when set. * Rename Strictness.DEFAULT to Strictness.LEGACY_STRICT * Update JavaDoc with new strictness functionality * Replace default with legacy strict for JsonReader javadoc * Add JSONReader test cases for U2028 and U2029 * Refactor JSONReader#peekKeyWord() based on @eamonmcmanus's suggestion * Deprecate setLenient in favor of setStrictness --------- Co-authored-by: Carl Peterson <unknown> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Strictness follow-up (#2408) * Strictness mode follow-up - Remove mentions of `null` Gson strictness; this is an implementation detail - Fix incorrect / outdated documentation - Reduce links to RFC; if there is already a link to it in a previous sentence don't link to it again - Extend and update tests - Minor punctuation changes in documentation for consistency * Deprecate `setLenient` methods * `strictness2` fixes & improvements (#2456) * Adjust ProGuard default rules and shrinking tests (#2420) * Adjust ProGuard default rules and shrinking tests * Adjust comment * Add shrinking test for class without no-args constructor; improve docs * Improve Unsafe mention in Troubleshooting Guide * Improve comment for `-if class *` * Bump com.google.guava:guava from 32.0.1-jre to 32.1.1-jre (#2444) Bumps [com.google.guava:guava](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Bump com.google.guava:guava-testlib from 32.0.1-jre to 32.1.1-jre (#2443) Bumps [com.google.guava:guava-testlib](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava-testlib dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Support non-generic type for `TypeToken.getParameterized` for legacy reasons (#2447) This partially restores the behavior before a589ef20087b4b0f1ec3048d3ceaef1eedccd09d, except that back then for a non-generic type a bogus `TypeToken(ParameterizedType)` was created, whereas now a `TypeToken(Class)` is created instead. * Fixed Typo in GsonBuilder.java (#2449) * Make date-formatting tests less fragile with regular expressions. (#2450) * Make date-formatting tests less fragile with regular expressions. This is not great. We should really ensure that formatted dates are the same regardless of JDK version. There is code that attempts to do that but it is not really effective. So for now we fudge around the differences by using regular expressions to paper over the differences. * Temporarily add test-debugging code. * Another attempt at debugging a test failure. * Fix pattern in assertion. * Modification in test cases (#2454) * Fixed Typo in GsonBuilder.java * Suggestions on Test cases * Modified test cases using assertThrows method (JUnit) * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/GsonTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> --------- Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Minor follow-up changes --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Éamonn McManus <emcmanus@google.com> Co-authored-by: Wonil <cwi5525@naver.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Marten <martenvoorberg@gmail.com> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Wonil <cwi5525@naver.com>
2023-07-30 18:20:32 +02:00
2023-09-19 17:22:29 +02:00
writer.setOmitQuotes(omitQuotes);
Strict mode for JSON parsing, contributed by @marten-voorberg. (#2437) * Strict mode for JSON parsing (#2323) * Feat #6: Add strict flag to Gson and GsonBuilder * Test #2: Add failing tests for capitalized keywords * Feat #2: JsonReader does not read (partially) capitalized keywords if strict mode is used * Feat #3: Added implementation and tests for JSONReader not accepting specific escape sequence representing in strict mode * Test #3: Simplify test cases by removing unnecessary array * Feat #3: Improve error by including the illegal character * Feat #5: JsonReader does not allow unespaced control flow characters in strict mode * Test #5: Test unespaced control flow characters in strict mode * Feat #4: Disallow espaced newline character in strict mode * Test #4: Add tests for (dis)allowing newline character depensding on strictness * Test #5: Test case for unescaped control char in non-strict mode * Test #2: Simplify test cases * Feat #13: Change leniency API to Strictness enum in JsonReader, Gson, and GsonBuilder * Feat #15: Change JsonWriter API to also use Strictness * Test #15: Test Strictness in JsonWriter API * Doc #15: Add and update documentation for Strictness in JsonWriter API * refactor #12: Fixed typos and empty catch brackets in tests * refactor #12: Resolved importing wildcards, made some lines adhere to Google java style * #5 Add test case for unescaped control characters * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue --------- Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * Doc #17: Add and change javadoc of public methods * Doc #17: Update JavaDoc in JsonReader and Strictness * Doc #17: Update JavaDoc in Gson and GsonBuilder * Test #34: Add tests for setting strictness through GsonBuilder * Fix: Add Fix broken test * Fix: Invalid JavaDoc in Gson.java * Doc #17: update outdated javadoc * #37: Resolve more PR feedback * Fix #37: Resolve various PR comments * Fix #37: Resolve various PR comments * Refactor #35: Refactor JsonReader#peekKeyword to reduce the amount of strictness checks (#39) * Doc #40: Update JavaDoc based on PR feedback * Doc #40: Update old RFC in GsonBuilder documentation * Doc #40: Fix formatting error in JavaDoc * Doc #40: Add tests for setting strictness and lenient to JsonReaderTest * Test #43: Changed tests to make use of assertThrows * test #43: Changed tests to make use of assertThrows as per feedback * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * test #43: Resolve PR recommendations * Test #43: Mini change to TC * Test #43: Mini change to TC --------- Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * doc #46: Resolved comments in main PR * Feat #45: Change Gson.fromJson and Gson.toJson to be strict when the provided writer/reader is strict * Fix #45: Small type * Update gson/src/test/java/com/google/gson/stream/JsonReaderTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Update gson/src/main/java/com/google/gson/GsonBuilder.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Fix #45: Resolve various comments by eamonmcmanus * Strictness mode follow-up * Update Troubleshooting.md and Gson default lenient mode documentation * Always use GSON strictness when set. * Rename Strictness.DEFAULT to Strictness.LEGACY_STRICT * Update JavaDoc with new strictness functionality * Replace default with legacy strict for JsonReader javadoc * Add JSONReader test cases for U2028 and U2029 * Refactor JSONReader#peekKeyWord() based on @eamonmcmanus's suggestion * Deprecate setLenient in favor of setStrictness --------- Co-authored-by: Carl Peterson <unknown> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Strictness follow-up (#2408) * Strictness mode follow-up - Remove mentions of `null` Gson strictness; this is an implementation detail - Fix incorrect / outdated documentation - Reduce links to RFC; if there is already a link to it in a previous sentence don't link to it again - Extend and update tests - Minor punctuation changes in documentation for consistency * Deprecate `setLenient` methods * `strictness2` fixes & improvements (#2456) * Adjust ProGuard default rules and shrinking tests (#2420) * Adjust ProGuard default rules and shrinking tests * Adjust comment * Add shrinking test for class without no-args constructor; improve docs * Improve Unsafe mention in Troubleshooting Guide * Improve comment for `-if class *` * Bump com.google.guava:guava from 32.0.1-jre to 32.1.1-jre (#2444) Bumps [com.google.guava:guava](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Bump com.google.guava:guava-testlib from 32.0.1-jre to 32.1.1-jre (#2443) Bumps [com.google.guava:guava-testlib](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava-testlib dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Support non-generic type for `TypeToken.getParameterized` for legacy reasons (#2447) This partially restores the behavior before a589ef20087b4b0f1ec3048d3ceaef1eedccd09d, except that back then for a non-generic type a bogus `TypeToken(ParameterizedType)` was created, whereas now a `TypeToken(Class)` is created instead. * Fixed Typo in GsonBuilder.java (#2449) * Make date-formatting tests less fragile with regular expressions. (#2450) * Make date-formatting tests less fragile with regular expressions. This is not great. We should really ensure that formatted dates are the same regardless of JDK version. There is code that attempts to do that but it is not really effective. So for now we fudge around the differences by using regular expressions to paper over the differences. * Temporarily add test-debugging code. * Another attempt at debugging a test failure. * Fix pattern in assertion. * Modification in test cases (#2454) * Fixed Typo in GsonBuilder.java * Suggestions on Test cases * Modified test cases using assertThrows method (JUnit) * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/GsonTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> --------- Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Minor follow-up changes --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Éamonn McManus <emcmanus@google.com> Co-authored-by: Wonil <cwi5525@naver.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Marten <martenvoorberg@gmail.com> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Wonil <cwi5525@naver.com>
2023-07-30 18:20:32 +02:00
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 {
Strict mode for JSON parsing, contributed by @marten-voorberg. (#2437) * Strict mode for JSON parsing (#2323) * Feat #6: Add strict flag to Gson and GsonBuilder * Test #2: Add failing tests for capitalized keywords * Feat #2: JsonReader does not read (partially) capitalized keywords if strict mode is used * Feat #3: Added implementation and tests for JSONReader not accepting specific escape sequence representing in strict mode * Test #3: Simplify test cases by removing unnecessary array * Feat #3: Improve error by including the illegal character * Feat #5: JsonReader does not allow unespaced control flow characters in strict mode * Test #5: Test unespaced control flow characters in strict mode * Feat #4: Disallow espaced newline character in strict mode * Test #4: Add tests for (dis)allowing newline character depensding on strictness * Test #5: Test case for unescaped control char in non-strict mode * Test #2: Simplify test cases * Feat #13: Change leniency API to Strictness enum in JsonReader, Gson, and GsonBuilder * Feat #15: Change JsonWriter API to also use Strictness * Test #15: Test Strictness in JsonWriter API * Doc #15: Add and update documentation for Strictness in JsonWriter API * refactor #12: Fixed typos and empty catch brackets in tests * refactor #12: Resolved importing wildcards, made some lines adhere to Google java style * #5 Add test case for unescaped control characters * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue --------- Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * Doc #17: Add and change javadoc of public methods * Doc #17: Update JavaDoc in JsonReader and Strictness * Doc #17: Update JavaDoc in Gson and GsonBuilder * Test #34: Add tests for setting strictness through GsonBuilder * Fix: Add Fix broken test * Fix: Invalid JavaDoc in Gson.java * Doc #17: update outdated javadoc * #37: Resolve more PR feedback * Fix #37: Resolve various PR comments * Fix #37: Resolve various PR comments * Refactor #35: Refactor JsonReader#peekKeyword to reduce the amount of strictness checks (#39) * Doc #40: Update JavaDoc based on PR feedback * Doc #40: Update old RFC in GsonBuilder documentation * Doc #40: Fix formatting error in JavaDoc * Doc #40: Add tests for setting strictness and lenient to JsonReaderTest * Test #43: Changed tests to make use of assertThrows * test #43: Changed tests to make use of assertThrows as per feedback * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * test #43: Resolve PR recommendations * Test #43: Mini change to TC * Test #43: Mini change to TC --------- Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * doc #46: Resolved comments in main PR * Feat #45: Change Gson.fromJson and Gson.toJson to be strict when the provided writer/reader is strict * Fix #45: Small type * Update gson/src/test/java/com/google/gson/stream/JsonReaderTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Update gson/src/main/java/com/google/gson/GsonBuilder.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Fix #45: Resolve various comments by eamonmcmanus * Strictness mode follow-up * Update Troubleshooting.md and Gson default lenient mode documentation * Always use GSON strictness when set. * Rename Strictness.DEFAULT to Strictness.LEGACY_STRICT * Update JavaDoc with new strictness functionality * Replace default with legacy strict for JsonReader javadoc * Add JSONReader test cases for U2028 and U2029 * Refactor JSONReader#peekKeyWord() based on @eamonmcmanus's suggestion * Deprecate setLenient in favor of setStrictness --------- Co-authored-by: Carl Peterson <unknown> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Strictness follow-up (#2408) * Strictness mode follow-up - Remove mentions of `null` Gson strictness; this is an implementation detail - Fix incorrect / outdated documentation - Reduce links to RFC; if there is already a link to it in a previous sentence don't link to it again - Extend and update tests - Minor punctuation changes in documentation for consistency * Deprecate `setLenient` methods * `strictness2` fixes & improvements (#2456) * Adjust ProGuard default rules and shrinking tests (#2420) * Adjust ProGuard default rules and shrinking tests * Adjust comment * Add shrinking test for class without no-args constructor; improve docs * Improve Unsafe mention in Troubleshooting Guide * Improve comment for `-if class *` * Bump com.google.guava:guava from 32.0.1-jre to 32.1.1-jre (#2444) Bumps [com.google.guava:guava](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Bump com.google.guava:guava-testlib from 32.0.1-jre to 32.1.1-jre (#2443) Bumps [com.google.guava:guava-testlib](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava-testlib dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Support non-generic type for `TypeToken.getParameterized` for legacy reasons (#2447) This partially restores the behavior before a589ef20087b4b0f1ec3048d3ceaef1eedccd09d, except that back then for a non-generic type a bogus `TypeToken(ParameterizedType)` was created, whereas now a `TypeToken(Class)` is created instead. * Fixed Typo in GsonBuilder.java (#2449) * Make date-formatting tests less fragile with regular expressions. (#2450) * Make date-formatting tests less fragile with regular expressions. This is not great. We should really ensure that formatted dates are the same regardless of JDK version. There is code that attempts to do that but it is not really effective. So for now we fudge around the differences by using regular expressions to paper over the differences. * Temporarily add test-debugging code. * Another attempt at debugging a test failure. * Fix pattern in assertion. * Modification in test cases (#2454) * Fixed Typo in GsonBuilder.java * Suggestions on Test cases * Modified test cases using assertThrows method (JUnit) * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/GsonTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> --------- Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Minor follow-up changes --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Éamonn McManus <emcmanus@google.com> Co-authored-by: Wonil <cwi5525@naver.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Marten <martenvoorberg@gmail.com> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Wonil <cwi5525@naver.com>
2023-07-30 18:20:32 +02:00
writer.setStrictness(oldStrictness);
2022-05-17 21:20:10 +02:00
writer.setOmitQuotes(oldOmitQuotes);
writer.setHtmlSafe(oldHtmlSafe);
writer.setSerializeNulls(oldSerializeNulls);
}
}
/**
* Converts a tree of {@link JsonElement}s into its equivalent JSON representation.
*
* @param jsonElement root of a tree of {@link JsonElement}s
* @return JSON String representation of the tree.
* @since 1.4
*/
public String toJson(JsonElement jsonElement) {
StringWriter writer = new StringWriter();
toJson(jsonElement, writer);
return writer.toString();
}
/**
* Writes out the equivalent JSON for a tree of {@link JsonElement}s.
*
* @param jsonElement root of a tree of {@link JsonElement}s
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* @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);
}
2008-09-01 05:13:32 +02:00
}
/**
* Writes the JSON for {@code jsonElement} to {@code writer}.
*
Strict mode for JSON parsing, contributed by @marten-voorberg. (#2437) * Strict mode for JSON parsing (#2323) * Feat #6: Add strict flag to Gson and GsonBuilder * Test #2: Add failing tests for capitalized keywords * Feat #2: JsonReader does not read (partially) capitalized keywords if strict mode is used * Feat #3: Added implementation and tests for JSONReader not accepting specific escape sequence representing in strict mode * Test #3: Simplify test cases by removing unnecessary array * Feat #3: Improve error by including the illegal character * Feat #5: JsonReader does not allow unespaced control flow characters in strict mode * Test #5: Test unespaced control flow characters in strict mode * Feat #4: Disallow espaced newline character in strict mode * Test #4: Add tests for (dis)allowing newline character depensding on strictness * Test #5: Test case for unescaped control char in non-strict mode * Test #2: Simplify test cases * Feat #13: Change leniency API to Strictness enum in JsonReader, Gson, and GsonBuilder * Feat #15: Change JsonWriter API to also use Strictness * Test #15: Test Strictness in JsonWriter API * Doc #15: Add and update documentation for Strictness in JsonWriter API * refactor #12: Fixed typos and empty catch brackets in tests * refactor #12: Resolved importing wildcards, made some lines adhere to Google java style * #5 Add test case for unescaped control characters * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue --------- Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * Doc #17: Add and change javadoc of public methods * Doc #17: Update JavaDoc in JsonReader and Strictness * Doc #17: Update JavaDoc in Gson and GsonBuilder * Test #34: Add tests for setting strictness through GsonBuilder * Fix: Add Fix broken test * Fix: Invalid JavaDoc in Gson.java * Doc #17: update outdated javadoc * #37: Resolve more PR feedback * Fix #37: Resolve various PR comments * Fix #37: Resolve various PR comments * Refactor #35: Refactor JsonReader#peekKeyword to reduce the amount of strictness checks (#39) * Doc #40: Update JavaDoc based on PR feedback * Doc #40: Update old RFC in GsonBuilder documentation * Doc #40: Fix formatting error in JavaDoc * Doc #40: Add tests for setting strictness and lenient to JsonReaderTest * Test #43: Changed tests to make use of assertThrows * test #43: Changed tests to make use of assertThrows as per feedback * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * test #43: Resolve PR recommendations * Test #43: Mini change to TC * Test #43: Mini change to TC --------- Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * doc #46: Resolved comments in main PR * Feat #45: Change Gson.fromJson and Gson.toJson to be strict when the provided writer/reader is strict * Fix #45: Small type * Update gson/src/test/java/com/google/gson/stream/JsonReaderTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Update gson/src/main/java/com/google/gson/GsonBuilder.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Fix #45: Resolve various comments by eamonmcmanus * Strictness mode follow-up * Update Troubleshooting.md and Gson default lenient mode documentation * Always use GSON strictness when set. * Rename Strictness.DEFAULT to Strictness.LEGACY_STRICT * Update JavaDoc with new strictness functionality * Replace default with legacy strict for JsonReader javadoc * Add JSONReader test cases for U2028 and U2029 * Refactor JSONReader#peekKeyWord() based on @eamonmcmanus's suggestion * Deprecate setLenient in favor of setStrictness --------- Co-authored-by: Carl Peterson <unknown> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Strictness follow-up (#2408) * Strictness mode follow-up - Remove mentions of `null` Gson strictness; this is an implementation detail - Fix incorrect / outdated documentation - Reduce links to RFC; if there is already a link to it in a previous sentence don't link to it again - Extend and update tests - Minor punctuation changes in documentation for consistency * Deprecate `setLenient` methods * `strictness2` fixes & improvements (#2456) * Adjust ProGuard default rules and shrinking tests (#2420) * Adjust ProGuard default rules and shrinking tests * Adjust comment * Add shrinking test for class without no-args constructor; improve docs * Improve Unsafe mention in Troubleshooting Guide * Improve comment for `-if class *` * Bump com.google.guava:guava from 32.0.1-jre to 32.1.1-jre (#2444) Bumps [com.google.guava:guava](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Bump com.google.guava:guava-testlib from 32.0.1-jre to 32.1.1-jre (#2443) Bumps [com.google.guava:guava-testlib](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava-testlib dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Support non-generic type for `TypeToken.getParameterized` for legacy reasons (#2447) This partially restores the behavior before a589ef20087b4b0f1ec3048d3ceaef1eedccd09d, except that back then for a non-generic type a bogus `TypeToken(ParameterizedType)` was created, whereas now a `TypeToken(Class)` is created instead. * Fixed Typo in GsonBuilder.java (#2449) * Make date-formatting tests less fragile with regular expressions. (#2450) * Make date-formatting tests less fragile with regular expressions. This is not great. We should really ensure that formatted dates are the same regardless of JDK version. There is code that attempts to do that but it is not really effective. So for now we fudge around the differences by using regular expressions to paper over the differences. * Temporarily add test-debugging code. * Another attempt at debugging a test failure. * Fix pattern in assertion. * Modification in test cases (#2454) * Fixed Typo in GsonBuilder.java * Suggestions on Test cases * Modified test cases using assertThrows method (JUnit) * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/GsonTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> --------- Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Minor follow-up changes --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Éamonn McManus <emcmanus@google.com> Co-authored-by: Wonil <cwi5525@naver.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Marten <martenvoorberg@gmail.com> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Wonil <cwi5525@naver.com>
2023-07-30 18:20:32 +02:00
* <p>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.<br>
* Note that in all cases the old strictness setting of the writer will be restored when this
* method returns.
*
* <p>The 'HTML-safe' and 'serialize {@code null}' settings of this {@code Gson} instance
* (configured by the {@link GsonBuilder}) are applied, and the original settings of the writer
* are restored once this method returns.
*
Strict mode for JSON parsing, contributed by @marten-voorberg. (#2437) * Strict mode for JSON parsing (#2323) * Feat #6: Add strict flag to Gson and GsonBuilder * Test #2: Add failing tests for capitalized keywords * Feat #2: JsonReader does not read (partially) capitalized keywords if strict mode is used * Feat #3: Added implementation and tests for JSONReader not accepting specific escape sequence representing in strict mode * Test #3: Simplify test cases by removing unnecessary array * Feat #3: Improve error by including the illegal character * Feat #5: JsonReader does not allow unespaced control flow characters in strict mode * Test #5: Test unespaced control flow characters in strict mode * Feat #4: Disallow espaced newline character in strict mode * Test #4: Add tests for (dis)allowing newline character depensding on strictness * Test #5: Test case for unescaped control char in non-strict mode * Test #2: Simplify test cases * Feat #13: Change leniency API to Strictness enum in JsonReader, Gson, and GsonBuilder * Feat #15: Change JsonWriter API to also use Strictness * Test #15: Test Strictness in JsonWriter API * Doc #15: Add and update documentation for Strictness in JsonWriter API * refactor #12: Fixed typos and empty catch brackets in tests * refactor #12: Resolved importing wildcards, made some lines adhere to Google java style * #5 Add test case for unescaped control characters * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue --------- Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * Doc #17: Add and change javadoc of public methods * Doc #17: Update JavaDoc in JsonReader and Strictness * Doc #17: Update JavaDoc in Gson and GsonBuilder * Test #34: Add tests for setting strictness through GsonBuilder * Fix: Add Fix broken test * Fix: Invalid JavaDoc in Gson.java * Doc #17: update outdated javadoc * #37: Resolve more PR feedback * Fix #37: Resolve various PR comments * Fix #37: Resolve various PR comments * Refactor #35: Refactor JsonReader#peekKeyword to reduce the amount of strictness checks (#39) * Doc #40: Update JavaDoc based on PR feedback * Doc #40: Update old RFC in GsonBuilder documentation * Doc #40: Fix formatting error in JavaDoc * Doc #40: Add tests for setting strictness and lenient to JsonReaderTest * Test #43: Changed tests to make use of assertThrows * test #43: Changed tests to make use of assertThrows as per feedback * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * test #43: Resolve PR recommendations * Test #43: Mini change to TC * Test #43: Mini change to TC --------- Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * doc #46: Resolved comments in main PR * Feat #45: Change Gson.fromJson and Gson.toJson to be strict when the provided writer/reader is strict * Fix #45: Small type * Update gson/src/test/java/com/google/gson/stream/JsonReaderTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Update gson/src/main/java/com/google/gson/GsonBuilder.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Fix #45: Resolve various comments by eamonmcmanus * Strictness mode follow-up * Update Troubleshooting.md and Gson default lenient mode documentation * Always use GSON strictness when set. * Rename Strictness.DEFAULT to Strictness.LEGACY_STRICT * Update JavaDoc with new strictness functionality * Replace default with legacy strict for JsonReader javadoc * Add JSONReader test cases for U2028 and U2029 * Refactor JSONReader#peekKeyWord() based on @eamonmcmanus's suggestion * Deprecate setLenient in favor of setStrictness --------- Co-authored-by: Carl Peterson <unknown> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Strictness follow-up (#2408) * Strictness mode follow-up - Remove mentions of `null` Gson strictness; this is an implementation detail - Fix incorrect / outdated documentation - Reduce links to RFC; if there is already a link to it in a previous sentence don't link to it again - Extend and update tests - Minor punctuation changes in documentation for consistency * Deprecate `setLenient` methods * `strictness2` fixes & improvements (#2456) * Adjust ProGuard default rules and shrinking tests (#2420) * Adjust ProGuard default rules and shrinking tests * Adjust comment * Add shrinking test for class without no-args constructor; improve docs * Improve Unsafe mention in Troubleshooting Guide * Improve comment for `-if class *` * Bump com.google.guava:guava from 32.0.1-jre to 32.1.1-jre (#2444) Bumps [com.google.guava:guava](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Bump com.google.guava:guava-testlib from 32.0.1-jre to 32.1.1-jre (#2443) Bumps [com.google.guava:guava-testlib](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava-testlib dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Support non-generic type for `TypeToken.getParameterized` for legacy reasons (#2447) This partially restores the behavior before a589ef20087b4b0f1ec3048d3ceaef1eedccd09d, except that back then for a non-generic type a bogus `TypeToken(ParameterizedType)` was created, whereas now a `TypeToken(Class)` is created instead. * Fixed Typo in GsonBuilder.java (#2449) * Make date-formatting tests less fragile with regular expressions. (#2450) * Make date-formatting tests less fragile with regular expressions. This is not great. We should really ensure that formatted dates are the same regardless of JDK version. There is code that attempts to do that but it is not really effective. So for now we fudge around the differences by using regular expressions to paper over the differences. * Temporarily add test-debugging code. * Another attempt at debugging a test failure. * Fix pattern in assertion. * Modification in test cases (#2454) * Fixed Typo in GsonBuilder.java * Suggestions on Test cases * Modified test cases using assertThrows method (JUnit) * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/GsonTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> --------- Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Minor follow-up changes --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Éamonn McManus <emcmanus@google.com> Co-authored-by: Wonil <cwi5525@naver.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Marten <martenvoorberg@gmail.com> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Wonil <cwi5525@naver.com>
2023-07-30 18:20:32 +02:00
* @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 {
Strict mode for JSON parsing, contributed by @marten-voorberg. (#2437) * Strict mode for JSON parsing (#2323) * Feat #6: Add strict flag to Gson and GsonBuilder * Test #2: Add failing tests for capitalized keywords * Feat #2: JsonReader does not read (partially) capitalized keywords if strict mode is used * Feat #3: Added implementation and tests for JSONReader not accepting specific escape sequence representing in strict mode * Test #3: Simplify test cases by removing unnecessary array * Feat #3: Improve error by including the illegal character * Feat #5: JsonReader does not allow unespaced control flow characters in strict mode * Test #5: Test unespaced control flow characters in strict mode * Feat #4: Disallow espaced newline character in strict mode * Test #4: Add tests for (dis)allowing newline character depensding on strictness * Test #5: Test case for unescaped control char in non-strict mode * Test #2: Simplify test cases * Feat #13: Change leniency API to Strictness enum in JsonReader, Gson, and GsonBuilder * Feat #15: Change JsonWriter API to also use Strictness * Test #15: Test Strictness in JsonWriter API * Doc #15: Add and update documentation for Strictness in JsonWriter API * refactor #12: Fixed typos and empty catch brackets in tests * refactor #12: Resolved importing wildcards, made some lines adhere to Google java style * #5 Add test case for unescaped control characters * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue --------- Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * Doc #17: Add and change javadoc of public methods * Doc #17: Update JavaDoc in JsonReader and Strictness * Doc #17: Update JavaDoc in Gson and GsonBuilder * Test #34: Add tests for setting strictness through GsonBuilder * Fix: Add Fix broken test * Fix: Invalid JavaDoc in Gson.java * Doc #17: update outdated javadoc * #37: Resolve more PR feedback * Fix #37: Resolve various PR comments * Fix #37: Resolve various PR comments * Refactor #35: Refactor JsonReader#peekKeyword to reduce the amount of strictness checks (#39) * Doc #40: Update JavaDoc based on PR feedback * Doc #40: Update old RFC in GsonBuilder documentation * Doc #40: Fix formatting error in JavaDoc * Doc #40: Add tests for setting strictness and lenient to JsonReaderTest * Test #43: Changed tests to make use of assertThrows * test #43: Changed tests to make use of assertThrows as per feedback * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * test #43: Resolve PR recommendations * Test #43: Mini change to TC * Test #43: Mini change to TC --------- Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * doc #46: Resolved comments in main PR * Feat #45: Change Gson.fromJson and Gson.toJson to be strict when the provided writer/reader is strict * Fix #45: Small type * Update gson/src/test/java/com/google/gson/stream/JsonReaderTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Update gson/src/main/java/com/google/gson/GsonBuilder.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Fix #45: Resolve various comments by eamonmcmanus * Strictness mode follow-up * Update Troubleshooting.md and Gson default lenient mode documentation * Always use GSON strictness when set. * Rename Strictness.DEFAULT to Strictness.LEGACY_STRICT * Update JavaDoc with new strictness functionality * Replace default with legacy strict for JsonReader javadoc * Add JSONReader test cases for U2028 and U2029 * Refactor JSONReader#peekKeyWord() based on @eamonmcmanus's suggestion * Deprecate setLenient in favor of setStrictness --------- Co-authored-by: Carl Peterson <unknown> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Strictness follow-up (#2408) * Strictness mode follow-up - Remove mentions of `null` Gson strictness; this is an implementation detail - Fix incorrect / outdated documentation - Reduce links to RFC; if there is already a link to it in a previous sentence don't link to it again - Extend and update tests - Minor punctuation changes in documentation for consistency * Deprecate `setLenient` methods * `strictness2` fixes & improvements (#2456) * Adjust ProGuard default rules and shrinking tests (#2420) * Adjust ProGuard default rules and shrinking tests * Adjust comment * Add shrinking test for class without no-args constructor; improve docs * Improve Unsafe mention in Troubleshooting Guide * Improve comment for `-if class *` * Bump com.google.guava:guava from 32.0.1-jre to 32.1.1-jre (#2444) Bumps [com.google.guava:guava](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Bump com.google.guava:guava-testlib from 32.0.1-jre to 32.1.1-jre (#2443) Bumps [com.google.guava:guava-testlib](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava-testlib dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Support non-generic type for `TypeToken.getParameterized` for legacy reasons (#2447) This partially restores the behavior before a589ef20087b4b0f1ec3048d3ceaef1eedccd09d, except that back then for a non-generic type a bogus `TypeToken(ParameterizedType)` was created, whereas now a `TypeToken(Class)` is created instead. * Fixed Typo in GsonBuilder.java (#2449) * Make date-formatting tests less fragile with regular expressions. (#2450) * Make date-formatting tests less fragile with regular expressions. This is not great. We should really ensure that formatted dates are the same regardless of JDK version. There is code that attempts to do that but it is not really effective. So for now we fudge around the differences by using regular expressions to paper over the differences. * Temporarily add test-debugging code. * Another attempt at debugging a test failure. * Fix pattern in assertion. * Modification in test cases (#2454) * Fixed Typo in GsonBuilder.java * Suggestions on Test cases * Modified test cases using assertThrows method (JUnit) * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/GsonTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> --------- Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Minor follow-up changes --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Éamonn McManus <emcmanus@google.com> Co-authored-by: Wonil <cwi5525@naver.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Marten <martenvoorberg@gmail.com> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Wonil <cwi5525@naver.com>
2023-07-30 18:20:32 +02:00
Strictness oldStrictness = writer.getStrictness();
Merge remote-tracking branch 'origin/main' # Conflicts: # .github/ISSUE_TEMPLATE/config.yml # .github/dependabot.yml # .github/pull_request_template.md # .github/workflows/build.yml # .github/workflows/check-android-compatibility.yml # .github/workflows/check-api-compatibility.yml # .github/workflows/cifuzz.yml # .github/workflows/codeql-analysis.yml # extras/pom.xml # extras/src/main/java/com/google/gson/extras/examples/rawcollections/RawCollectionsExample.java # extras/src/main/java/com/google/gson/graph/GraphAdapterBuilder.java # extras/src/main/java/com/google/gson/interceptors/Intercept.java # extras/src/main/java/com/google/gson/interceptors/InterceptorFactory.java # extras/src/main/java/com/google/gson/interceptors/JsonPostDeserializer.java # extras/src/main/java/com/google/gson/typeadapters/PostConstructAdapterFactory.java # extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java # extras/src/main/java/com/google/gson/typeadapters/UtcDateTypeAdapter.java # extras/src/test/java/com/google/gson/graph/GraphAdapterBuilderTest.java # extras/src/test/java/com/google/gson/interceptors/InterceptorTest.java # extras/src/test/java/com/google/gson/typeadapters/PostConstructAdapterFactoryTest.java # extras/src/test/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactoryTest.java # extras/src/test/java/com/google/gson/typeadapters/UtcDateTypeAdapterTest.java # graal-native-image-test/pom.xml # graal-native-image-test/src/test/java/com/google/gson/native_test/Java17RecordReflectionTest.java # graal-native-image-test/src/test/java/com/google/gson/native_test/ReflectionTest.java # gson/pom.xml # gson/src/main/java/com/google/gson/Gson.java # gson/src/main/java/com/google/gson/GsonBuilder.java # gson/src/main/java/com/google/gson/JsonParser.java # gson/src/main/java/com/google/gson/internal/LinkedTreeMap.java # gson/src/main/java/com/google/gson/internal/bind/DateTypeAdapter.java # gson/src/main/java/com/google/gson/internal/bind/DefaultDateTypeAdapter.java # gson/src/main/java/com/google/gson/internal/bind/MapTypeAdapterFactory.java # gson/src/main/java/com/google/gson/internal/bind/TypeAdapters.java # gson/src/main/java/com/google/gson/stream/JsonReader.java # gson/src/main/java/com/google/gson/stream/JsonTreeWriter.java # gson/src/main/java/com/google/gson/stream/JsonWriter.java # gson/src/test/java/com/google/gson/CommentsTest.java # gson/src/test/java/com/google/gson/GsonTest.java # gson/src/test/java/com/google/gson/MixedStreamTest.java # gson/src/test/java/com/google/gson/ToNumberPolicyTest.java # gson/src/test/java/com/google/gson/functional/ArrayTest.java # gson/src/test/java/com/google/gson/functional/ConcurrencyTest.java # gson/src/test/java/com/google/gson/functional/CustomDeserializerTest.java # gson/src/test/java/com/google/gson/functional/CustomTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/DefaultTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/EnumWithObfuscatedTest.java # gson/src/test/java/com/google/gson/functional/ExposeFieldsTest.java # gson/src/test/java/com/google/gson/functional/FormattingStyleTest.java # gson/src/test/java/com/google/gson/functional/InstanceCreatorTest.java # gson/src/test/java/com/google/gson/functional/InternationalizationTest.java # gson/src/test/java/com/google/gson/functional/Java17RecordTest.java # gson/src/test/java/com/google/gson/functional/JavaUtilConcurrentAtomicTest.java # gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnClassesTest.java # gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnFieldsTest.java # gson/src/test/java/com/google/gson/functional/JsonParserTest.java # gson/src/test/java/com/google/gson/functional/NullObjectAndFieldTest.java # gson/src/test/java/com/google/gson/functional/ObjectTest.java # gson/src/test/java/com/google/gson/functional/PrimitiveTest.java # gson/src/test/java/com/google/gson/functional/ReflectionAccessTest.java # gson/src/test/java/com/google/gson/functional/StreamingTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/TreeTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/TypeAdapterPrecedenceTest.java # gson/src/test/java/com/google/gson/internal/bind/Java17ReflectiveTypeAdapterFactoryTest.java # gson/src/test/java/com/google/gson/internal/bind/JsonTreeReaderTest.java # gson/src/test/java/com/google/gson/internal/bind/JsonTreeWriterTest.java # gson/src/test/java/com/google/gson/internal/reflect/Java17ReflectionHelperTest.java # gson/src/test/java/com/google/gson/stream/JsonReaderTest.java # metrics/pom.xml # metrics/src/main/java/com/google/gson/metrics/BagOfPrimitives.java # metrics/src/main/java/com/google/gson/metrics/BagOfPrimitivesDeserializationBenchmark.java # metrics/src/main/java/com/google/gson/metrics/CollectionsDeserializationBenchmark.java # metrics/src/main/java/com/google/gson/metrics/NonUploadingCaliperRunner.java # metrics/src/main/java/com/google/gson/metrics/ParseBenchmark.java # metrics/src/main/java/com/google/gson/metrics/SerializationBenchmark.java # pom.xml # proto/pom.xml # proto/src/main/java/com/google/gson/protobuf/ProtoTypeAdapter.java # proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithAnnotationsTest.java # proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithComplexAndRepeatedFieldsTest.java # proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithPrimitiveTypesTest.java # shrinker-test/pom.xml # shrinker-test/src/main/java/com/example/ClassWithExposeAnnotation.java # shrinker-test/src/main/java/com/example/ClassWithHasArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithJsonAdapterAnnotation.java # shrinker-test/src/main/java/com/example/ClassWithNoArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithUnreferencedHasArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithUnreferencedNoArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithVersionAnnotations.java # shrinker-test/src/main/java/com/example/GenericClasses.java # shrinker-test/src/main/java/com/example/Main.java # shrinker-test/src/main/java/com/example/NoSerializedNameMain.java # shrinker-test/src/main/java/com/example/TestExecutor.java # shrinker-test/src/main/java/com/example/UnusedClass.java # shrinker-test/src/test/java/com/google/gson/it/ShrinkingIT.java
2024-03-12 12:56:07 +01:00
boolean oldOmitQuotes = writer.getOmitQuotes();
boolean oldHtmlSafe = writer.isHtmlSafe();
boolean oldSerializeNulls = writer.getSerializeNulls();
Strict mode for JSON parsing, contributed by @marten-voorberg. (#2437) * Strict mode for JSON parsing (#2323) * Feat #6: Add strict flag to Gson and GsonBuilder * Test #2: Add failing tests for capitalized keywords * Feat #2: JsonReader does not read (partially) capitalized keywords if strict mode is used * Feat #3: Added implementation and tests for JSONReader not accepting specific escape sequence representing in strict mode * Test #3: Simplify test cases by removing unnecessary array * Feat #3: Improve error by including the illegal character * Feat #5: JsonReader does not allow unespaced control flow characters in strict mode * Test #5: Test unespaced control flow characters in strict mode * Feat #4: Disallow espaced newline character in strict mode * Test #4: Add tests for (dis)allowing newline character depensding on strictness * Test #5: Test case for unescaped control char in non-strict mode * Test #2: Simplify test cases * Feat #13: Change leniency API to Strictness enum in JsonReader, Gson, and GsonBuilder * Feat #15: Change JsonWriter API to also use Strictness * Test #15: Test Strictness in JsonWriter API * Doc #15: Add and update documentation for Strictness in JsonWriter API * refactor #12: Fixed typos and empty catch brackets in tests * refactor #12: Resolved importing wildcards, made some lines adhere to Google java style * #5 Add test case for unescaped control characters * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue --------- Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * Doc #17: Add and change javadoc of public methods * Doc #17: Update JavaDoc in JsonReader and Strictness * Doc #17: Update JavaDoc in Gson and GsonBuilder * Test #34: Add tests for setting strictness through GsonBuilder * Fix: Add Fix broken test * Fix: Invalid JavaDoc in Gson.java * Doc #17: update outdated javadoc * #37: Resolve more PR feedback * Fix #37: Resolve various PR comments * Fix #37: Resolve various PR comments * Refactor #35: Refactor JsonReader#peekKeyword to reduce the amount of strictness checks (#39) * Doc #40: Update JavaDoc based on PR feedback * Doc #40: Update old RFC in GsonBuilder documentation * Doc #40: Fix formatting error in JavaDoc * Doc #40: Add tests for setting strictness and lenient to JsonReaderTest * Test #43: Changed tests to make use of assertThrows * test #43: Changed tests to make use of assertThrows as per feedback * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * test #43: Resolve PR recommendations * Test #43: Mini change to TC * Test #43: Mini change to TC --------- Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * doc #46: Resolved comments in main PR * Feat #45: Change Gson.fromJson and Gson.toJson to be strict when the provided writer/reader is strict * Fix #45: Small type * Update gson/src/test/java/com/google/gson/stream/JsonReaderTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Update gson/src/main/java/com/google/gson/GsonBuilder.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Fix #45: Resolve various comments by eamonmcmanus * Strictness mode follow-up * Update Troubleshooting.md and Gson default lenient mode documentation * Always use GSON strictness when set. * Rename Strictness.DEFAULT to Strictness.LEGACY_STRICT * Update JavaDoc with new strictness functionality * Replace default with legacy strict for JsonReader javadoc * Add JSONReader test cases for U2028 and U2029 * Refactor JSONReader#peekKeyWord() based on @eamonmcmanus's suggestion * Deprecate setLenient in favor of setStrictness --------- Co-authored-by: Carl Peterson <unknown> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Strictness follow-up (#2408) * Strictness mode follow-up - Remove mentions of `null` Gson strictness; this is an implementation detail - Fix incorrect / outdated documentation - Reduce links to RFC; if there is already a link to it in a previous sentence don't link to it again - Extend and update tests - Minor punctuation changes in documentation for consistency * Deprecate `setLenient` methods * `strictness2` fixes & improvements (#2456) * Adjust ProGuard default rules and shrinking tests (#2420) * Adjust ProGuard default rules and shrinking tests * Adjust comment * Add shrinking test for class without no-args constructor; improve docs * Improve Unsafe mention in Troubleshooting Guide * Improve comment for `-if class *` * Bump com.google.guava:guava from 32.0.1-jre to 32.1.1-jre (#2444) Bumps [com.google.guava:guava](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Bump com.google.guava:guava-testlib from 32.0.1-jre to 32.1.1-jre (#2443) Bumps [com.google.guava:guava-testlib](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava-testlib dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Support non-generic type for `TypeToken.getParameterized` for legacy reasons (#2447) This partially restores the behavior before a589ef20087b4b0f1ec3048d3ceaef1eedccd09d, except that back then for a non-generic type a bogus `TypeToken(ParameterizedType)` was created, whereas now a `TypeToken(Class)` is created instead. * Fixed Typo in GsonBuilder.java (#2449) * Make date-formatting tests less fragile with regular expressions. (#2450) * Make date-formatting tests less fragile with regular expressions. This is not great. We should really ensure that formatted dates are the same regardless of JDK version. There is code that attempts to do that but it is not really effective. So for now we fudge around the differences by using regular expressions to paper over the differences. * Temporarily add test-debugging code. * Another attempt at debugging a test failure. * Fix pattern in assertion. * Modification in test cases (#2454) * Fixed Typo in GsonBuilder.java * Suggestions on Test cases * Modified test cases using assertThrows method (JUnit) * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/GsonTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> --------- Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Minor follow-up changes --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Éamonn McManus <emcmanus@google.com> Co-authored-by: Wonil <cwi5525@naver.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Marten <martenvoorberg@gmail.com> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Wonil <cwi5525@naver.com>
2023-07-30 18:20:32 +02:00
Merge remote-tracking branch 'origin/main' # Conflicts: # .github/ISSUE_TEMPLATE/config.yml # .github/dependabot.yml # .github/pull_request_template.md # .github/workflows/build.yml # .github/workflows/check-android-compatibility.yml # .github/workflows/check-api-compatibility.yml # .github/workflows/cifuzz.yml # .github/workflows/codeql-analysis.yml # extras/pom.xml # extras/src/main/java/com/google/gson/extras/examples/rawcollections/RawCollectionsExample.java # extras/src/main/java/com/google/gson/graph/GraphAdapterBuilder.java # extras/src/main/java/com/google/gson/interceptors/Intercept.java # extras/src/main/java/com/google/gson/interceptors/InterceptorFactory.java # extras/src/main/java/com/google/gson/interceptors/JsonPostDeserializer.java # extras/src/main/java/com/google/gson/typeadapters/PostConstructAdapterFactory.java # extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java # extras/src/main/java/com/google/gson/typeadapters/UtcDateTypeAdapter.java # extras/src/test/java/com/google/gson/graph/GraphAdapterBuilderTest.java # extras/src/test/java/com/google/gson/interceptors/InterceptorTest.java # extras/src/test/java/com/google/gson/typeadapters/PostConstructAdapterFactoryTest.java # extras/src/test/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactoryTest.java # extras/src/test/java/com/google/gson/typeadapters/UtcDateTypeAdapterTest.java # graal-native-image-test/pom.xml # graal-native-image-test/src/test/java/com/google/gson/native_test/Java17RecordReflectionTest.java # graal-native-image-test/src/test/java/com/google/gson/native_test/ReflectionTest.java # gson/pom.xml # gson/src/main/java/com/google/gson/Gson.java # gson/src/main/java/com/google/gson/GsonBuilder.java # gson/src/main/java/com/google/gson/JsonParser.java # gson/src/main/java/com/google/gson/internal/LinkedTreeMap.java # gson/src/main/java/com/google/gson/internal/bind/DateTypeAdapter.java # gson/src/main/java/com/google/gson/internal/bind/DefaultDateTypeAdapter.java # gson/src/main/java/com/google/gson/internal/bind/MapTypeAdapterFactory.java # gson/src/main/java/com/google/gson/internal/bind/TypeAdapters.java # gson/src/main/java/com/google/gson/stream/JsonReader.java # gson/src/main/java/com/google/gson/stream/JsonTreeWriter.java # gson/src/main/java/com/google/gson/stream/JsonWriter.java # gson/src/test/java/com/google/gson/CommentsTest.java # gson/src/test/java/com/google/gson/GsonTest.java # gson/src/test/java/com/google/gson/MixedStreamTest.java # gson/src/test/java/com/google/gson/ToNumberPolicyTest.java # gson/src/test/java/com/google/gson/functional/ArrayTest.java # gson/src/test/java/com/google/gson/functional/ConcurrencyTest.java # gson/src/test/java/com/google/gson/functional/CustomDeserializerTest.java # gson/src/test/java/com/google/gson/functional/CustomTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/DefaultTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/EnumWithObfuscatedTest.java # gson/src/test/java/com/google/gson/functional/ExposeFieldsTest.java # gson/src/test/java/com/google/gson/functional/FormattingStyleTest.java # gson/src/test/java/com/google/gson/functional/InstanceCreatorTest.java # gson/src/test/java/com/google/gson/functional/InternationalizationTest.java # gson/src/test/java/com/google/gson/functional/Java17RecordTest.java # gson/src/test/java/com/google/gson/functional/JavaUtilConcurrentAtomicTest.java # gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnClassesTest.java # gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnFieldsTest.java # gson/src/test/java/com/google/gson/functional/JsonParserTest.java # gson/src/test/java/com/google/gson/functional/NullObjectAndFieldTest.java # gson/src/test/java/com/google/gson/functional/ObjectTest.java # gson/src/test/java/com/google/gson/functional/PrimitiveTest.java # gson/src/test/java/com/google/gson/functional/ReflectionAccessTest.java # gson/src/test/java/com/google/gson/functional/StreamingTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/TreeTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/TypeAdapterPrecedenceTest.java # gson/src/test/java/com/google/gson/internal/bind/Java17ReflectiveTypeAdapterFactoryTest.java # gson/src/test/java/com/google/gson/internal/bind/JsonTreeReaderTest.java # gson/src/test/java/com/google/gson/internal/bind/JsonTreeWriterTest.java # gson/src/test/java/com/google/gson/internal/reflect/Java17ReflectionHelperTest.java # gson/src/test/java/com/google/gson/stream/JsonReaderTest.java # metrics/pom.xml # metrics/src/main/java/com/google/gson/metrics/BagOfPrimitives.java # metrics/src/main/java/com/google/gson/metrics/BagOfPrimitivesDeserializationBenchmark.java # metrics/src/main/java/com/google/gson/metrics/CollectionsDeserializationBenchmark.java # metrics/src/main/java/com/google/gson/metrics/NonUploadingCaliperRunner.java # metrics/src/main/java/com/google/gson/metrics/ParseBenchmark.java # metrics/src/main/java/com/google/gson/metrics/SerializationBenchmark.java # pom.xml # proto/pom.xml # proto/src/main/java/com/google/gson/protobuf/ProtoTypeAdapter.java # proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithAnnotationsTest.java # proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithComplexAndRepeatedFieldsTest.java # proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithPrimitiveTypesTest.java # shrinker-test/pom.xml # shrinker-test/src/main/java/com/example/ClassWithExposeAnnotation.java # shrinker-test/src/main/java/com/example/ClassWithHasArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithJsonAdapterAnnotation.java # shrinker-test/src/main/java/com/example/ClassWithNoArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithUnreferencedHasArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithUnreferencedNoArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithVersionAnnotations.java # shrinker-test/src/main/java/com/example/GenericClasses.java # shrinker-test/src/main/java/com/example/Main.java # shrinker-test/src/main/java/com/example/NoSerializedNameMain.java # shrinker-test/src/main/java/com/example/TestExecutor.java # shrinker-test/src/main/java/com/example/UnusedClass.java # shrinker-test/src/test/java/com/google/gson/it/ShrinkingIT.java
2024-03-12 12:56:07 +01:00
writer.setOmitQuotes(omitQuotes);
Strict mode for JSON parsing, contributed by @marten-voorberg. (#2437) * Strict mode for JSON parsing (#2323) * Feat #6: Add strict flag to Gson and GsonBuilder * Test #2: Add failing tests for capitalized keywords * Feat #2: JsonReader does not read (partially) capitalized keywords if strict mode is used * Feat #3: Added implementation and tests for JSONReader not accepting specific escape sequence representing in strict mode * Test #3: Simplify test cases by removing unnecessary array * Feat #3: Improve error by including the illegal character * Feat #5: JsonReader does not allow unespaced control flow characters in strict mode * Test #5: Test unespaced control flow characters in strict mode * Feat #4: Disallow espaced newline character in strict mode * Test #4: Add tests for (dis)allowing newline character depensding on strictness * Test #5: Test case for unescaped control char in non-strict mode * Test #2: Simplify test cases * Feat #13: Change leniency API to Strictness enum in JsonReader, Gson, and GsonBuilder * Feat #15: Change JsonWriter API to also use Strictness * Test #15: Test Strictness in JsonWriter API * Doc #15: Add and update documentation for Strictness in JsonWriter API * refactor #12: Fixed typos and empty catch brackets in tests * refactor #12: Resolved importing wildcards, made some lines adhere to Google java style * #5 Add test case for unescaped control characters * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue --------- Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * Doc #17: Add and change javadoc of public methods * Doc #17: Update JavaDoc in JsonReader and Strictness * Doc #17: Update JavaDoc in Gson and GsonBuilder * Test #34: Add tests for setting strictness through GsonBuilder * Fix: Add Fix broken test * Fix: Invalid JavaDoc in Gson.java * Doc #17: update outdated javadoc * #37: Resolve more PR feedback * Fix #37: Resolve various PR comments * Fix #37: Resolve various PR comments * Refactor #35: Refactor JsonReader#peekKeyword to reduce the amount of strictness checks (#39) * Doc #40: Update JavaDoc based on PR feedback * Doc #40: Update old RFC in GsonBuilder documentation * Doc #40: Fix formatting error in JavaDoc * Doc #40: Add tests for setting strictness and lenient to JsonReaderTest * Test #43: Changed tests to make use of assertThrows * test #43: Changed tests to make use of assertThrows as per feedback * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * test #43: Resolve PR recommendations * Test #43: Mini change to TC * Test #43: Mini change to TC --------- Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * doc #46: Resolved comments in main PR * Feat #45: Change Gson.fromJson and Gson.toJson to be strict when the provided writer/reader is strict * Fix #45: Small type * Update gson/src/test/java/com/google/gson/stream/JsonReaderTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Update gson/src/main/java/com/google/gson/GsonBuilder.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Fix #45: Resolve various comments by eamonmcmanus * Strictness mode follow-up * Update Troubleshooting.md and Gson default lenient mode documentation * Always use GSON strictness when set. * Rename Strictness.DEFAULT to Strictness.LEGACY_STRICT * Update JavaDoc with new strictness functionality * Replace default with legacy strict for JsonReader javadoc * Add JSONReader test cases for U2028 and U2029 * Refactor JSONReader#peekKeyWord() based on @eamonmcmanus's suggestion * Deprecate setLenient in favor of setStrictness --------- Co-authored-by: Carl Peterson <unknown> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Strictness follow-up (#2408) * Strictness mode follow-up - Remove mentions of `null` Gson strictness; this is an implementation detail - Fix incorrect / outdated documentation - Reduce links to RFC; if there is already a link to it in a previous sentence don't link to it again - Extend and update tests - Minor punctuation changes in documentation for consistency * Deprecate `setLenient` methods * `strictness2` fixes & improvements (#2456) * Adjust ProGuard default rules and shrinking tests (#2420) * Adjust ProGuard default rules and shrinking tests * Adjust comment * Add shrinking test for class without no-args constructor; improve docs * Improve Unsafe mention in Troubleshooting Guide * Improve comment for `-if class *` * Bump com.google.guava:guava from 32.0.1-jre to 32.1.1-jre (#2444) Bumps [com.google.guava:guava](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Bump com.google.guava:guava-testlib from 32.0.1-jre to 32.1.1-jre (#2443) Bumps [com.google.guava:guava-testlib](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava-testlib dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Support non-generic type for `TypeToken.getParameterized` for legacy reasons (#2447) This partially restores the behavior before a589ef20087b4b0f1ec3048d3ceaef1eedccd09d, except that back then for a non-generic type a bogus `TypeToken(ParameterizedType)` was created, whereas now a `TypeToken(Class)` is created instead. * Fixed Typo in GsonBuilder.java (#2449) * Make date-formatting tests less fragile with regular expressions. (#2450) * Make date-formatting tests less fragile with regular expressions. This is not great. We should really ensure that formatted dates are the same regardless of JDK version. There is code that attempts to do that but it is not really effective. So for now we fudge around the differences by using regular expressions to paper over the differences. * Temporarily add test-debugging code. * Another attempt at debugging a test failure. * Fix pattern in assertion. * Modification in test cases (#2454) * Fixed Typo in GsonBuilder.java * Suggestions on Test cases * Modified test cases using assertThrows method (JUnit) * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/GsonTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> --------- Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Minor follow-up changes --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Éamonn McManus <emcmanus@google.com> Co-authored-by: Wonil <cwi5525@naver.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Marten <martenvoorberg@gmail.com> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Wonil <cwi5525@naver.com>
2023-07-30 18:20:32 +02:00
writer.setHtmlSafe(htmlSafe);
writer.setSerializeNulls(serializeNulls);
Strict mode for JSON parsing, contributed by @marten-voorberg. (#2437) * Strict mode for JSON parsing (#2323) * Feat #6: Add strict flag to Gson and GsonBuilder * Test #2: Add failing tests for capitalized keywords * Feat #2: JsonReader does not read (partially) capitalized keywords if strict mode is used * Feat #3: Added implementation and tests for JSONReader not accepting specific escape sequence representing in strict mode * Test #3: Simplify test cases by removing unnecessary array * Feat #3: Improve error by including the illegal character * Feat #5: JsonReader does not allow unespaced control flow characters in strict mode * Test #5: Test unespaced control flow characters in strict mode * Feat #4: Disallow espaced newline character in strict mode * Test #4: Add tests for (dis)allowing newline character depensding on strictness * Test #5: Test case for unescaped control char in non-strict mode * Test #2: Simplify test cases * Feat #13: Change leniency API to Strictness enum in JsonReader, Gson, and GsonBuilder * Feat #15: Change JsonWriter API to also use Strictness * Test #15: Test Strictness in JsonWriter API * Doc #15: Add and update documentation for Strictness in JsonWriter API * refactor #12: Fixed typos and empty catch brackets in tests * refactor #12: Resolved importing wildcards, made some lines adhere to Google java style * #5 Add test case for unescaped control characters * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue --------- Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * Doc #17: Add and change javadoc of public methods * Doc #17: Update JavaDoc in JsonReader and Strictness * Doc #17: Update JavaDoc in Gson and GsonBuilder * Test #34: Add tests for setting strictness through GsonBuilder * Fix: Add Fix broken test * Fix: Invalid JavaDoc in Gson.java * Doc #17: update outdated javadoc * #37: Resolve more PR feedback * Fix #37: Resolve various PR comments * Fix #37: Resolve various PR comments * Refactor #35: Refactor JsonReader#peekKeyword to reduce the amount of strictness checks (#39) * Doc #40: Update JavaDoc based on PR feedback * Doc #40: Update old RFC in GsonBuilder documentation * Doc #40: Fix formatting error in JavaDoc * Doc #40: Add tests for setting strictness and lenient to JsonReaderTest * Test #43: Changed tests to make use of assertThrows * test #43: Changed tests to make use of assertThrows as per feedback * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * test #43: Resolve PR recommendations * Test #43: Mini change to TC * Test #43: Mini change to TC --------- Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * doc #46: Resolved comments in main PR * Feat #45: Change Gson.fromJson and Gson.toJson to be strict when the provided writer/reader is strict * Fix #45: Small type * Update gson/src/test/java/com/google/gson/stream/JsonReaderTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Update gson/src/main/java/com/google/gson/GsonBuilder.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Fix #45: Resolve various comments by eamonmcmanus * Strictness mode follow-up * Update Troubleshooting.md and Gson default lenient mode documentation * Always use GSON strictness when set. * Rename Strictness.DEFAULT to Strictness.LEGACY_STRICT * Update JavaDoc with new strictness functionality * Replace default with legacy strict for JsonReader javadoc * Add JSONReader test cases for U2028 and U2029 * Refactor JSONReader#peekKeyWord() based on @eamonmcmanus's suggestion * Deprecate setLenient in favor of setStrictness --------- Co-authored-by: Carl Peterson <unknown> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Strictness follow-up (#2408) * Strictness mode follow-up - Remove mentions of `null` Gson strictness; this is an implementation detail - Fix incorrect / outdated documentation - Reduce links to RFC; if there is already a link to it in a previous sentence don't link to it again - Extend and update tests - Minor punctuation changes in documentation for consistency * Deprecate `setLenient` methods * `strictness2` fixes & improvements (#2456) * Adjust ProGuard default rules and shrinking tests (#2420) * Adjust ProGuard default rules and shrinking tests * Adjust comment * Add shrinking test for class without no-args constructor; improve docs * Improve Unsafe mention in Troubleshooting Guide * Improve comment for `-if class *` * Bump com.google.guava:guava from 32.0.1-jre to 32.1.1-jre (#2444) Bumps [com.google.guava:guava](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Bump com.google.guava:guava-testlib from 32.0.1-jre to 32.1.1-jre (#2443) Bumps [com.google.guava:guava-testlib](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava-testlib dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Support non-generic type for `TypeToken.getParameterized` for legacy reasons (#2447) This partially restores the behavior before a589ef20087b4b0f1ec3048d3ceaef1eedccd09d, except that back then for a non-generic type a bogus `TypeToken(ParameterizedType)` was created, whereas now a `TypeToken(Class)` is created instead. * Fixed Typo in GsonBuilder.java (#2449) * Make date-formatting tests less fragile with regular expressions. (#2450) * Make date-formatting tests less fragile with regular expressions. This is not great. We should really ensure that formatted dates are the same regardless of JDK version. There is code that attempts to do that but it is not really effective. So for now we fudge around the differences by using regular expressions to paper over the differences. * Temporarily add test-debugging code. * Another attempt at debugging a test failure. * Fix pattern in assertion. * Modification in test cases (#2454) * Fixed Typo in GsonBuilder.java * Suggestions on Test cases * Modified test cases using assertThrows method (JUnit) * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/GsonTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> --------- Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Minor follow-up changes --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Éamonn McManus <emcmanus@google.com> Co-authored-by: Wonil <cwi5525@naver.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Marten <martenvoorberg@gmail.com> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Wonil <cwi5525@naver.com>
2023-07-30 18:20:32 +02:00
if (this.strictness != null) {
writer.setStrictness(this.strictness);
} else if (writer.getStrictness() != Strictness.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 {
Strict mode for JSON parsing, contributed by @marten-voorberg. (#2437) * Strict mode for JSON parsing (#2323) * Feat #6: Add strict flag to Gson and GsonBuilder * Test #2: Add failing tests for capitalized keywords * Feat #2: JsonReader does not read (partially) capitalized keywords if strict mode is used * Feat #3: Added implementation and tests for JSONReader not accepting specific escape sequence representing in strict mode * Test #3: Simplify test cases by removing unnecessary array * Feat #3: Improve error by including the illegal character * Feat #5: JsonReader does not allow unespaced control flow characters in strict mode * Test #5: Test unespaced control flow characters in strict mode * Feat #4: Disallow espaced newline character in strict mode * Test #4: Add tests for (dis)allowing newline character depensding on strictness * Test #5: Test case for unescaped control char in non-strict mode * Test #2: Simplify test cases * Feat #13: Change leniency API to Strictness enum in JsonReader, Gson, and GsonBuilder * Feat #15: Change JsonWriter API to also use Strictness * Test #15: Test Strictness in JsonWriter API * Doc #15: Add and update documentation for Strictness in JsonWriter API * refactor #12: Fixed typos and empty catch brackets in tests * refactor #12: Resolved importing wildcards, made some lines adhere to Google java style * #5 Add test case for unescaped control characters * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue --------- Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * Doc #17: Add and change javadoc of public methods * Doc #17: Update JavaDoc in JsonReader and Strictness * Doc #17: Update JavaDoc in Gson and GsonBuilder * Test #34: Add tests for setting strictness through GsonBuilder * Fix: Add Fix broken test * Fix: Invalid JavaDoc in Gson.java * Doc #17: update outdated javadoc * #37: Resolve more PR feedback * Fix #37: Resolve various PR comments * Fix #37: Resolve various PR comments * Refactor #35: Refactor JsonReader#peekKeyword to reduce the amount of strictness checks (#39) * Doc #40: Update JavaDoc based on PR feedback * Doc #40: Update old RFC in GsonBuilder documentation * Doc #40: Fix formatting error in JavaDoc * Doc #40: Add tests for setting strictness and lenient to JsonReaderTest * Test #43: Changed tests to make use of assertThrows * test #43: Changed tests to make use of assertThrows as per feedback * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * test #43: Resolve PR recommendations * Test #43: Mini change to TC * Test #43: Mini change to TC --------- Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * doc #46: Resolved comments in main PR * Feat #45: Change Gson.fromJson and Gson.toJson to be strict when the provided writer/reader is strict * Fix #45: Small type * Update gson/src/test/java/com/google/gson/stream/JsonReaderTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Update gson/src/main/java/com/google/gson/GsonBuilder.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Fix #45: Resolve various comments by eamonmcmanus * Strictness mode follow-up * Update Troubleshooting.md and Gson default lenient mode documentation * Always use GSON strictness when set. * Rename Strictness.DEFAULT to Strictness.LEGACY_STRICT * Update JavaDoc with new strictness functionality * Replace default with legacy strict for JsonReader javadoc * Add JSONReader test cases for U2028 and U2029 * Refactor JSONReader#peekKeyWord() based on @eamonmcmanus's suggestion * Deprecate setLenient in favor of setStrictness --------- Co-authored-by: Carl Peterson <unknown> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Strictness follow-up (#2408) * Strictness mode follow-up - Remove mentions of `null` Gson strictness; this is an implementation detail - Fix incorrect / outdated documentation - Reduce links to RFC; if there is already a link to it in a previous sentence don't link to it again - Extend and update tests - Minor punctuation changes in documentation for consistency * Deprecate `setLenient` methods * `strictness2` fixes & improvements (#2456) * Adjust ProGuard default rules and shrinking tests (#2420) * Adjust ProGuard default rules and shrinking tests * Adjust comment * Add shrinking test for class without no-args constructor; improve docs * Improve Unsafe mention in Troubleshooting Guide * Improve comment for `-if class *` * Bump com.google.guava:guava from 32.0.1-jre to 32.1.1-jre (#2444) Bumps [com.google.guava:guava](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Bump com.google.guava:guava-testlib from 32.0.1-jre to 32.1.1-jre (#2443) Bumps [com.google.guava:guava-testlib](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava-testlib dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Support non-generic type for `TypeToken.getParameterized` for legacy reasons (#2447) This partially restores the behavior before a589ef20087b4b0f1ec3048d3ceaef1eedccd09d, except that back then for a non-generic type a bogus `TypeToken(ParameterizedType)` was created, whereas now a `TypeToken(Class)` is created instead. * Fixed Typo in GsonBuilder.java (#2449) * Make date-formatting tests less fragile with regular expressions. (#2450) * Make date-formatting tests less fragile with regular expressions. This is not great. We should really ensure that formatted dates are the same regardless of JDK version. There is code that attempts to do that but it is not really effective. So for now we fudge around the differences by using regular expressions to paper over the differences. * Temporarily add test-debugging code. * Another attempt at debugging a test failure. * Fix pattern in assertion. * Modification in test cases (#2454) * Fixed Typo in GsonBuilder.java * Suggestions on Test cases * Modified test cases using assertThrows method (JUnit) * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/GsonTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> --------- Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Minor follow-up changes --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Éamonn McManus <emcmanus@google.com> Co-authored-by: Wonil <cwi5525@naver.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Marten <martenvoorberg@gmail.com> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Wonil <cwi5525@naver.com>
2023-07-30 18:20:32 +02:00
writer.setStrictness(oldStrictness);
Merge remote-tracking branch 'origin/main' # Conflicts: # .github/ISSUE_TEMPLATE/config.yml # .github/dependabot.yml # .github/pull_request_template.md # .github/workflows/build.yml # .github/workflows/check-android-compatibility.yml # .github/workflows/check-api-compatibility.yml # .github/workflows/cifuzz.yml # .github/workflows/codeql-analysis.yml # extras/pom.xml # extras/src/main/java/com/google/gson/extras/examples/rawcollections/RawCollectionsExample.java # extras/src/main/java/com/google/gson/graph/GraphAdapterBuilder.java # extras/src/main/java/com/google/gson/interceptors/Intercept.java # extras/src/main/java/com/google/gson/interceptors/InterceptorFactory.java # extras/src/main/java/com/google/gson/interceptors/JsonPostDeserializer.java # extras/src/main/java/com/google/gson/typeadapters/PostConstructAdapterFactory.java # extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java # extras/src/main/java/com/google/gson/typeadapters/UtcDateTypeAdapter.java # extras/src/test/java/com/google/gson/graph/GraphAdapterBuilderTest.java # extras/src/test/java/com/google/gson/interceptors/InterceptorTest.java # extras/src/test/java/com/google/gson/typeadapters/PostConstructAdapterFactoryTest.java # extras/src/test/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactoryTest.java # extras/src/test/java/com/google/gson/typeadapters/UtcDateTypeAdapterTest.java # graal-native-image-test/pom.xml # graal-native-image-test/src/test/java/com/google/gson/native_test/Java17RecordReflectionTest.java # graal-native-image-test/src/test/java/com/google/gson/native_test/ReflectionTest.java # gson/pom.xml # gson/src/main/java/com/google/gson/Gson.java # gson/src/main/java/com/google/gson/GsonBuilder.java # gson/src/main/java/com/google/gson/JsonParser.java # gson/src/main/java/com/google/gson/internal/LinkedTreeMap.java # gson/src/main/java/com/google/gson/internal/bind/DateTypeAdapter.java # gson/src/main/java/com/google/gson/internal/bind/DefaultDateTypeAdapter.java # gson/src/main/java/com/google/gson/internal/bind/MapTypeAdapterFactory.java # gson/src/main/java/com/google/gson/internal/bind/TypeAdapters.java # gson/src/main/java/com/google/gson/stream/JsonReader.java # gson/src/main/java/com/google/gson/stream/JsonTreeWriter.java # gson/src/main/java/com/google/gson/stream/JsonWriter.java # gson/src/test/java/com/google/gson/CommentsTest.java # gson/src/test/java/com/google/gson/GsonTest.java # gson/src/test/java/com/google/gson/MixedStreamTest.java # gson/src/test/java/com/google/gson/ToNumberPolicyTest.java # gson/src/test/java/com/google/gson/functional/ArrayTest.java # gson/src/test/java/com/google/gson/functional/ConcurrencyTest.java # gson/src/test/java/com/google/gson/functional/CustomDeserializerTest.java # gson/src/test/java/com/google/gson/functional/CustomTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/DefaultTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/EnumWithObfuscatedTest.java # gson/src/test/java/com/google/gson/functional/ExposeFieldsTest.java # gson/src/test/java/com/google/gson/functional/FormattingStyleTest.java # gson/src/test/java/com/google/gson/functional/InstanceCreatorTest.java # gson/src/test/java/com/google/gson/functional/InternationalizationTest.java # gson/src/test/java/com/google/gson/functional/Java17RecordTest.java # gson/src/test/java/com/google/gson/functional/JavaUtilConcurrentAtomicTest.java # gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnClassesTest.java # gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnFieldsTest.java # gson/src/test/java/com/google/gson/functional/JsonParserTest.java # gson/src/test/java/com/google/gson/functional/NullObjectAndFieldTest.java # gson/src/test/java/com/google/gson/functional/ObjectTest.java # gson/src/test/java/com/google/gson/functional/PrimitiveTest.java # gson/src/test/java/com/google/gson/functional/ReflectionAccessTest.java # gson/src/test/java/com/google/gson/functional/StreamingTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/TreeTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/TypeAdapterPrecedenceTest.java # gson/src/test/java/com/google/gson/internal/bind/Java17ReflectiveTypeAdapterFactoryTest.java # gson/src/test/java/com/google/gson/internal/bind/JsonTreeReaderTest.java # gson/src/test/java/com/google/gson/internal/bind/JsonTreeWriterTest.java # gson/src/test/java/com/google/gson/internal/reflect/Java17ReflectionHelperTest.java # gson/src/test/java/com/google/gson/stream/JsonReaderTest.java # metrics/pom.xml # metrics/src/main/java/com/google/gson/metrics/BagOfPrimitives.java # metrics/src/main/java/com/google/gson/metrics/BagOfPrimitivesDeserializationBenchmark.java # metrics/src/main/java/com/google/gson/metrics/CollectionsDeserializationBenchmark.java # metrics/src/main/java/com/google/gson/metrics/NonUploadingCaliperRunner.java # metrics/src/main/java/com/google/gson/metrics/ParseBenchmark.java # metrics/src/main/java/com/google/gson/metrics/SerializationBenchmark.java # pom.xml # proto/pom.xml # proto/src/main/java/com/google/gson/protobuf/ProtoTypeAdapter.java # proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithAnnotationsTest.java # proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithComplexAndRepeatedFieldsTest.java # proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithPrimitiveTypesTest.java # shrinker-test/pom.xml # shrinker-test/src/main/java/com/example/ClassWithExposeAnnotation.java # shrinker-test/src/main/java/com/example/ClassWithHasArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithJsonAdapterAnnotation.java # shrinker-test/src/main/java/com/example/ClassWithNoArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithUnreferencedHasArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithUnreferencedNoArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithVersionAnnotations.java # shrinker-test/src/main/java/com/example/GenericClasses.java # shrinker-test/src/main/java/com/example/Main.java # shrinker-test/src/main/java/com/example/NoSerializedNameMain.java # shrinker-test/src/main/java/com/example/TestExecutor.java # shrinker-test/src/main/java/com/example/UnusedClass.java # shrinker-test/src/test/java/com/google/gson/it/ShrinkingIT.java
2024-03-12 12:56:07 +01:00
writer.setOmitQuotes(oldOmitQuotes);
writer.setHtmlSafe(oldHtmlSafe);
writer.setSerializeNulls(oldSerializeNulls);
}
}
/**
* Returns a new JSON writer configured for the settings on this Gson instance.
*
* <p>The following settings are considered:
* <ul>
* <li>{@link GsonBuilder#disableHtmlEscaping()}
* <li>{@link GsonBuilder#generateNonExecutableJson()}
* <li>{@link GsonBuilder#serializeNulls()}
Strict mode for JSON parsing, contributed by @marten-voorberg. (#2437) * Strict mode for JSON parsing (#2323) * Feat #6: Add strict flag to Gson and GsonBuilder * Test #2: Add failing tests for capitalized keywords * Feat #2: JsonReader does not read (partially) capitalized keywords if strict mode is used * Feat #3: Added implementation and tests for JSONReader not accepting specific escape sequence representing in strict mode * Test #3: Simplify test cases by removing unnecessary array * Feat #3: Improve error by including the illegal character * Feat #5: JsonReader does not allow unespaced control flow characters in strict mode * Test #5: Test unespaced control flow characters in strict mode * Feat #4: Disallow espaced newline character in strict mode * Test #4: Add tests for (dis)allowing newline character depensding on strictness * Test #5: Test case for unescaped control char in non-strict mode * Test #2: Simplify test cases * Feat #13: Change leniency API to Strictness enum in JsonReader, Gson, and GsonBuilder * Feat #15: Change JsonWriter API to also use Strictness * Test #15: Test Strictness in JsonWriter API * Doc #15: Add and update documentation for Strictness in JsonWriter API * refactor #12: Fixed typos and empty catch brackets in tests * refactor #12: Resolved importing wildcards, made some lines adhere to Google java style * #5 Add test case for unescaped control characters * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue --------- Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * Doc #17: Add and change javadoc of public methods * Doc #17: Update JavaDoc in JsonReader and Strictness * Doc #17: Update JavaDoc in Gson and GsonBuilder * Test #34: Add tests for setting strictness through GsonBuilder * Fix: Add Fix broken test * Fix: Invalid JavaDoc in Gson.java * Doc #17: update outdated javadoc * #37: Resolve more PR feedback * Fix #37: Resolve various PR comments * Fix #37: Resolve various PR comments * Refactor #35: Refactor JsonReader#peekKeyword to reduce the amount of strictness checks (#39) * Doc #40: Update JavaDoc based on PR feedback * Doc #40: Update old RFC in GsonBuilder documentation * Doc #40: Fix formatting error in JavaDoc * Doc #40: Add tests for setting strictness and lenient to JsonReaderTest * Test #43: Changed tests to make use of assertThrows * test #43: Changed tests to make use of assertThrows as per feedback * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * test #43: Resolve PR recommendations * Test #43: Mini change to TC * Test #43: Mini change to TC --------- Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * doc #46: Resolved comments in main PR * Feat #45: Change Gson.fromJson and Gson.toJson to be strict when the provided writer/reader is strict * Fix #45: Small type * Update gson/src/test/java/com/google/gson/stream/JsonReaderTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Update gson/src/main/java/com/google/gson/GsonBuilder.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Fix #45: Resolve various comments by eamonmcmanus * Strictness mode follow-up * Update Troubleshooting.md and Gson default lenient mode documentation * Always use GSON strictness when set. * Rename Strictness.DEFAULT to Strictness.LEGACY_STRICT * Update JavaDoc with new strictness functionality * Replace default with legacy strict for JsonReader javadoc * Add JSONReader test cases for U2028 and U2029 * Refactor JSONReader#peekKeyWord() based on @eamonmcmanus's suggestion * Deprecate setLenient in favor of setStrictness --------- Co-authored-by: Carl Peterson <unknown> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Strictness follow-up (#2408) * Strictness mode follow-up - Remove mentions of `null` Gson strictness; this is an implementation detail - Fix incorrect / outdated documentation - Reduce links to RFC; if there is already a link to it in a previous sentence don't link to it again - Extend and update tests - Minor punctuation changes in documentation for consistency * Deprecate `setLenient` methods * `strictness2` fixes & improvements (#2456) * Adjust ProGuard default rules and shrinking tests (#2420) * Adjust ProGuard default rules and shrinking tests * Adjust comment * Add shrinking test for class without no-args constructor; improve docs * Improve Unsafe mention in Troubleshooting Guide * Improve comment for `-if class *` * Bump com.google.guava:guava from 32.0.1-jre to 32.1.1-jre (#2444) Bumps [com.google.guava:guava](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Bump com.google.guava:guava-testlib from 32.0.1-jre to 32.1.1-jre (#2443) Bumps [com.google.guava:guava-testlib](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava-testlib dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Support non-generic type for `TypeToken.getParameterized` for legacy reasons (#2447) This partially restores the behavior before a589ef20087b4b0f1ec3048d3ceaef1eedccd09d, except that back then for a non-generic type a bogus `TypeToken(ParameterizedType)` was created, whereas now a `TypeToken(Class)` is created instead. * Fixed Typo in GsonBuilder.java (#2449) * Make date-formatting tests less fragile with regular expressions. (#2450) * Make date-formatting tests less fragile with regular expressions. This is not great. We should really ensure that formatted dates are the same regardless of JDK version. There is code that attempts to do that but it is not really effective. So for now we fudge around the differences by using regular expressions to paper over the differences. * Temporarily add test-debugging code. * Another attempt at debugging a test failure. * Fix pattern in assertion. * Modification in test cases (#2454) * Fixed Typo in GsonBuilder.java * Suggestions on Test cases * Modified test cases using assertThrows method (JUnit) * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/GsonTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> --------- Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Minor follow-up changes --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Éamonn McManus <emcmanus@google.com> Co-authored-by: Wonil <cwi5525@naver.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Marten <martenvoorberg@gmail.com> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Wonil <cwi5525@naver.com>
2023-07-30 18:20:32 +02:00
* <li>{@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
Merge remote-tracking branch 'origin/main' # Conflicts: # .github/ISSUE_TEMPLATE/config.yml # .github/dependabot.yml # .github/pull_request_template.md # .github/workflows/build.yml # .github/workflows/check-android-compatibility.yml # .github/workflows/check-api-compatibility.yml # .github/workflows/cifuzz.yml # .github/workflows/codeql-analysis.yml # extras/pom.xml # extras/src/main/java/com/google/gson/extras/examples/rawcollections/RawCollectionsExample.java # extras/src/main/java/com/google/gson/graph/GraphAdapterBuilder.java # extras/src/main/java/com/google/gson/interceptors/Intercept.java # extras/src/main/java/com/google/gson/interceptors/InterceptorFactory.java # extras/src/main/java/com/google/gson/interceptors/JsonPostDeserializer.java # extras/src/main/java/com/google/gson/typeadapters/PostConstructAdapterFactory.java # extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java # extras/src/main/java/com/google/gson/typeadapters/UtcDateTypeAdapter.java # extras/src/test/java/com/google/gson/graph/GraphAdapterBuilderTest.java # extras/src/test/java/com/google/gson/interceptors/InterceptorTest.java # extras/src/test/java/com/google/gson/typeadapters/PostConstructAdapterFactoryTest.java # extras/src/test/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactoryTest.java # extras/src/test/java/com/google/gson/typeadapters/UtcDateTypeAdapterTest.java # graal-native-image-test/pom.xml # graal-native-image-test/src/test/java/com/google/gson/native_test/Java17RecordReflectionTest.java # graal-native-image-test/src/test/java/com/google/gson/native_test/ReflectionTest.java # gson/pom.xml # gson/src/main/java/com/google/gson/Gson.java # gson/src/main/java/com/google/gson/GsonBuilder.java # gson/src/main/java/com/google/gson/JsonParser.java # gson/src/main/java/com/google/gson/internal/LinkedTreeMap.java # gson/src/main/java/com/google/gson/internal/bind/DateTypeAdapter.java # gson/src/main/java/com/google/gson/internal/bind/DefaultDateTypeAdapter.java # gson/src/main/java/com/google/gson/internal/bind/MapTypeAdapterFactory.java # gson/src/main/java/com/google/gson/internal/bind/TypeAdapters.java # gson/src/main/java/com/google/gson/stream/JsonReader.java # gson/src/main/java/com/google/gson/stream/JsonTreeWriter.java # gson/src/main/java/com/google/gson/stream/JsonWriter.java # gson/src/test/java/com/google/gson/CommentsTest.java # gson/src/test/java/com/google/gson/GsonTest.java # gson/src/test/java/com/google/gson/MixedStreamTest.java # gson/src/test/java/com/google/gson/ToNumberPolicyTest.java # gson/src/test/java/com/google/gson/functional/ArrayTest.java # gson/src/test/java/com/google/gson/functional/ConcurrencyTest.java # gson/src/test/java/com/google/gson/functional/CustomDeserializerTest.java # gson/src/test/java/com/google/gson/functional/CustomTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/DefaultTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/EnumWithObfuscatedTest.java # gson/src/test/java/com/google/gson/functional/ExposeFieldsTest.java # gson/src/test/java/com/google/gson/functional/FormattingStyleTest.java # gson/src/test/java/com/google/gson/functional/InstanceCreatorTest.java # gson/src/test/java/com/google/gson/functional/InternationalizationTest.java # gson/src/test/java/com/google/gson/functional/Java17RecordTest.java # gson/src/test/java/com/google/gson/functional/JavaUtilConcurrentAtomicTest.java # gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnClassesTest.java # gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnFieldsTest.java # gson/src/test/java/com/google/gson/functional/JsonParserTest.java # gson/src/test/java/com/google/gson/functional/NullObjectAndFieldTest.java # gson/src/test/java/com/google/gson/functional/ObjectTest.java # gson/src/test/java/com/google/gson/functional/PrimitiveTest.java # gson/src/test/java/com/google/gson/functional/ReflectionAccessTest.java # gson/src/test/java/com/google/gson/functional/StreamingTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/TreeTypeAdaptersTest.java # gson/src/test/java/com/google/gson/functional/TypeAdapterPrecedenceTest.java # gson/src/test/java/com/google/gson/internal/bind/Java17ReflectiveTypeAdapterFactoryTest.java # gson/src/test/java/com/google/gson/internal/bind/JsonTreeReaderTest.java # gson/src/test/java/com/google/gson/internal/bind/JsonTreeWriterTest.java # gson/src/test/java/com/google/gson/internal/reflect/Java17ReflectionHelperTest.java # gson/src/test/java/com/google/gson/stream/JsonReaderTest.java # metrics/pom.xml # metrics/src/main/java/com/google/gson/metrics/BagOfPrimitives.java # metrics/src/main/java/com/google/gson/metrics/BagOfPrimitivesDeserializationBenchmark.java # metrics/src/main/java/com/google/gson/metrics/CollectionsDeserializationBenchmark.java # metrics/src/main/java/com/google/gson/metrics/NonUploadingCaliperRunner.java # metrics/src/main/java/com/google/gson/metrics/ParseBenchmark.java # metrics/src/main/java/com/google/gson/metrics/SerializationBenchmark.java # pom.xml # proto/pom.xml # proto/src/main/java/com/google/gson/protobuf/ProtoTypeAdapter.java # proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithAnnotationsTest.java # proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithComplexAndRepeatedFieldsTest.java # proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithPrimitiveTypesTest.java # shrinker-test/pom.xml # shrinker-test/src/main/java/com/example/ClassWithExposeAnnotation.java # shrinker-test/src/main/java/com/example/ClassWithHasArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithJsonAdapterAnnotation.java # shrinker-test/src/main/java/com/example/ClassWithNoArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithUnreferencedHasArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithUnreferencedNoArgsConstructor.java # shrinker-test/src/main/java/com/example/ClassWithVersionAnnotations.java # shrinker-test/src/main/java/com/example/GenericClasses.java # shrinker-test/src/main/java/com/example/Main.java # shrinker-test/src/main/java/com/example/NoSerializedNameMain.java # shrinker-test/src/main/java/com/example/TestExecutor.java # shrinker-test/src/main/java/com/example/UnusedClass.java # shrinker-test/src/test/java/com/google/gson/it/ShrinkingIT.java
2024-03-12 12:56:07 +01:00
* the {@code Gson} instance will be used for the created writer.
* <li>{@link GsonBuilder#setOmitQuotes()}
* <li>{@link GsonBuilder#setPrettyPrinting()}
* <li>{@link GsonBuilder#setFormattingStyle(FormattingStyle)}
* </ul>
*/
public JsonWriter newJsonWriter(Writer writer) throws IOException {
if (generateNonExecutableJson) {
2022-05-17 21:20:10 +02:00
writer.write(DefaultConfig.JSON_NON_EXECUTABLE_PREFIX);
}
JsonWriter jsonWriter = new JsonWriter(writer);
configure(jsonWriter);
return jsonWriter;
}
public void configure(JsonWriter writer) {
writer.setFormattingStyle(formattingStyle);
writer.setHtmlSafe(htmlSafe);
2023-09-19 17:22:29 +02:00
writer.setStrictness(strictness == null ? Strictness.LEGACY_STRICT : strictness);
writer.setOmitQuotes(omitQuotes);
writer.setSerializeNulls(serializeNulls);
writer.setSerializeSpecialFloatingPointValues(serializeSpecialFloatingPointValues);
}
/**
* Returns a new JSON reader configured for the settings on this Gson instance.
*
* <p>The following settings are considered:
* <ul>
Strict mode for JSON parsing, contributed by @marten-voorberg. (#2437) * Strict mode for JSON parsing (#2323) * Feat #6: Add strict flag to Gson and GsonBuilder * Test #2: Add failing tests for capitalized keywords * Feat #2: JsonReader does not read (partially) capitalized keywords if strict mode is used * Feat #3: Added implementation and tests for JSONReader not accepting specific escape sequence representing in strict mode * Test #3: Simplify test cases by removing unnecessary array * Feat #3: Improve error by including the illegal character * Feat #5: JsonReader does not allow unespaced control flow characters in strict mode * Test #5: Test unespaced control flow characters in strict mode * Feat #4: Disallow espaced newline character in strict mode * Test #4: Add tests for (dis)allowing newline character depensding on strictness * Test #5: Test case for unescaped control char in non-strict mode * Test #2: Simplify test cases * Feat #13: Change leniency API to Strictness enum in JsonReader, Gson, and GsonBuilder * Feat #15: Change JsonWriter API to also use Strictness * Test #15: Test Strictness in JsonWriter API * Doc #15: Add and update documentation for Strictness in JsonWriter API * refactor #12: Fixed typos and empty catch brackets in tests * refactor #12: Resolved importing wildcards, made some lines adhere to Google java style * #5 Add test case for unescaped control characters * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue --------- Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * Doc #17: Add and change javadoc of public methods * Doc #17: Update JavaDoc in JsonReader and Strictness * Doc #17: Update JavaDoc in Gson and GsonBuilder * Test #34: Add tests for setting strictness through GsonBuilder * Fix: Add Fix broken test * Fix: Invalid JavaDoc in Gson.java * Doc #17: update outdated javadoc * #37: Resolve more PR feedback * Fix #37: Resolve various PR comments * Fix #37: Resolve various PR comments * Refactor #35: Refactor JsonReader#peekKeyword to reduce the amount of strictness checks (#39) * Doc #40: Update JavaDoc based on PR feedback * Doc #40: Update old RFC in GsonBuilder documentation * Doc #40: Fix formatting error in JavaDoc * Doc #40: Add tests for setting strictness and lenient to JsonReaderTest * Test #43: Changed tests to make use of assertThrows * test #43: Changed tests to make use of assertThrows as per feedback * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * test #43: Resolve PR recommendations * Test #43: Mini change to TC * Test #43: Mini change to TC --------- Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * doc #46: Resolved comments in main PR * Feat #45: Change Gson.fromJson and Gson.toJson to be strict when the provided writer/reader is strict * Fix #45: Small type * Update gson/src/test/java/com/google/gson/stream/JsonReaderTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Update gson/src/main/java/com/google/gson/GsonBuilder.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Fix #45: Resolve various comments by eamonmcmanus * Strictness mode follow-up * Update Troubleshooting.md and Gson default lenient mode documentation * Always use GSON strictness when set. * Rename Strictness.DEFAULT to Strictness.LEGACY_STRICT * Update JavaDoc with new strictness functionality * Replace default with legacy strict for JsonReader javadoc * Add JSONReader test cases for U2028 and U2029 * Refactor JSONReader#peekKeyWord() based on @eamonmcmanus's suggestion * Deprecate setLenient in favor of setStrictness --------- Co-authored-by: Carl Peterson <unknown> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Strictness follow-up (#2408) * Strictness mode follow-up - Remove mentions of `null` Gson strictness; this is an implementation detail - Fix incorrect / outdated documentation - Reduce links to RFC; if there is already a link to it in a previous sentence don't link to it again - Extend and update tests - Minor punctuation changes in documentation for consistency * Deprecate `setLenient` methods * `strictness2` fixes & improvements (#2456) * Adjust ProGuard default rules and shrinking tests (#2420) * Adjust ProGuard default rules and shrinking tests * Adjust comment * Add shrinking test for class without no-args constructor; improve docs * Improve Unsafe mention in Troubleshooting Guide * Improve comment for `-if class *` * Bump com.google.guava:guava from 32.0.1-jre to 32.1.1-jre (#2444) Bumps [com.google.guava:guava](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Bump com.google.guava:guava-testlib from 32.0.1-jre to 32.1.1-jre (#2443) Bumps [com.google.guava:guava-testlib](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava-testlib dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Support non-generic type for `TypeToken.getParameterized` for legacy reasons (#2447) This partially restores the behavior before a589ef20087b4b0f1ec3048d3ceaef1eedccd09d, except that back then for a non-generic type a bogus `TypeToken(ParameterizedType)` was created, whereas now a `TypeToken(Class)` is created instead. * Fixed Typo in GsonBuilder.java (#2449) * Make date-formatting tests less fragile with regular expressions. (#2450) * Make date-formatting tests less fragile with regular expressions. This is not great. We should really ensure that formatted dates are the same regardless of JDK version. There is code that attempts to do that but it is not really effective. So for now we fudge around the differences by using regular expressions to paper over the differences. * Temporarily add test-debugging code. * Another attempt at debugging a test failure. * Fix pattern in assertion. * Modification in test cases (#2454) * Fixed Typo in GsonBuilder.java * Suggestions on Test cases * Modified test cases using assertThrows method (JUnit) * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/GsonTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> --------- Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Minor follow-up changes --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Éamonn McManus <emcmanus@google.com> Co-authored-by: Wonil <cwi5525@naver.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Marten <martenvoorberg@gmail.com> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Wonil <cwi5525@naver.com>
2023-07-30 18:20:32 +02:00
* <li>{@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.</li>
* </ul>
*/
public JsonReader newJsonReader(Reader reader) {
JsonReader jsonReader = new JsonReader(reader);
configure(jsonReader);
return jsonReader;
}
public void configure(JsonReader reader) {
2023-09-19 17:22:29 +02:00
reader.setStrictness(strictness == null ? Strictness.LEGACY_STRICT : strictness);
reader.setSerializeSpecialFloatingPointValues(serializeSpecialFloatingPointValues);
}
2008-09-01 05:13:32 +02:00
/**
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* This method deserializes the specified JSON into an object of the specified class. It is not
2008-09-01 05:13:32 +02:00
* 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
2008-09-01 05:13:32 +02:00
* 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,
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* TypeToken)}. If you have the JSON in a {@link Reader} instead of a String, use {@link
2008-09-01 05:13:32 +02:00
* #fromJson(Reader, Class)} instead.
*
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* <p>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.
*
2008-09-01 05:13:32 +02:00
* @param <T> the type of the desired object
* @param json the string from which the object is to be deserialized
* @param classOfT the class of T
* @return an object of type T from the string. Returns {@code null} if {@code json} is {@code
* null} or if {@code json} is empty.
* @throws JsonSyntaxException if json is not a valid representation for an object of type
2008-09-01 05:13:32 +02:00
* classOfT
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* @see #fromJson(Reader, Class)
* @see #fromJson(String, TypeToken)
2008-09-01 05:13:32 +02:00
*/
public <T> T fromJson(String json, Class<T> classOfT) throws JsonSyntaxException {
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
T object = fromJson(json, TypeToken.get(classOfT));
return Primitives.wrap(classOfT).cast(object);
2008-09-01 05:13:32 +02:00
}
/**
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* This method deserializes the specified JSON into an object of the specified type. This method
2008-09-01 05:13:32 +02:00
* is useful if the specified object is a generic type. For non-generic objects, use {@link
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* #fromJson(String, Class)} instead. If you have the JSON in a {@link Reader} instead of a
2008-09-01 05:13:32 +02:00
* String, use {@link #fromJson(Reader, Type)} instead.
*
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* <p>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.
*
* <p>An exception is thrown if the JSON string has multiple top-level JSON elements, or if there
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* is trailing data. Use {@link #fromJson(JsonReader, Type)} if this behavior is not desired.
*
2008-09-01 05:13:32 +02:00
* @param <T> the type of the desired object
* @param json the string from which the object is to be deserialized
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* @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)
*/
Fix error prone warns (#2320) * Adds `@SuppressWarnings("NarrowingCompoundAssignment")` * Adds `@SuppressWarnings("TypeParameterUnusedInFormals")` * Adds `@SuppressWarnings("JavaUtilDate")` * Adds a limit to `String.split()` * Add `error_prone_annotations` to the `pom.xml` * Adds `@InlineMe(...)` to deprecated methods * Adds `@SuppressWarnings("ImmutableEnumChecker")` * Adds `@SuppressWarnings("ModifiedButNotUsed")` * Adds `@SuppressWarnings("MixedMutabilityReturnType")` * Removes an unused import * Adds `requires` to `module-info.java` * Adds ErrorProne `link` into `pom.xml` * Remove unused imports Removed from: - ParseBenchmark * Adds `@SuppressWarnings("EqualsGetClass")` * Excludes from `proto` just the generated code. Replaces `.*proto.*` with `.*/generated-test-sources/protobuf/.*` in such way will be excluded just the generated code and not the whole `proto` directory * Removes an unused variable Removes the `descriptor` variable because is unused. * Fixes the `BadImport` warn into `ProtosWithAnnotationsTest` * Fixes the `BadImport` warns into `ProtosWithAnnotationsTest` * Enables ErrorProne in `gson/src/test.*` Removes the `gson/src/test.*` path from the `-XepExcludedPaths` parameter of the ErrorProne plugin * Fixes `UnusedVariable` warns This commit fix all `UnusedVariable` warns given by ErrorProne in the `gson/src/test.*` path. Some field is annotated with `@Keep` that means is used by reflection. In some other case the record is annotated with `@SuppressWarnings("unused")` * Fixes `JavaUtilDate` warns This commit fix all `JavaUtilDate` warns given by ErrorProne in the `gson/src/test.*` path. Classes/Methods are annotated with `@SuppressWarnings("JavaUtilDate")` because it's not possible use differente Date API. * Fixes `EqualsGetClass` warns This commit fix all `EqualsGetClass` warns given by ErrorProne in the `gson/src/test.*` path. I have rewrite the `equals()` methods to use `instanceof` * Replaces pattern matching for instanceof with casts * Fixes `JdkObsolete` warns This commit fix all `JdkObsolete` warns given by ErrorProne in the `gson/src/test.*` path. In some cases I have replaced the obsolete JDK classes with the newest alternatives. In other cases, I have added the `@SuppressWarnings("JdkObsolete")` * Fixes `ClassCanBeStatic` warns This commit fix all `ClassCanBeStatic` warns given by ErrorProne in the `gson/src/test.*` path. I have added the `static` keyword, or I have added `@SuppressWarnings("ClassCanBeStatic")` * Fixes `UndefinedEquals` warns This commit fix all `UndefinedEquals` warns given by ErrorProne in the `gson/src/test.*` path. I have added `@SuppressWarnings("UndefinedEquals")` or fixed the asserts Note: In this commit I have also renamed a test from `testRawCollectionDeserializationNotAlllowed` to `testRawCollectionDeserializationNotAllowed` * Fixes `GetClassOnEnum` warns This commit fix all `GetClassOnEnum` warns given by ErrorProne in the `gson/src/test.*` path. I have replaced the `.getClass()` with `.getDeclaringClass()` * Fixes `ImmutableEnumChecker` warns This commit fix all `ImmutableEnumChecker` warns given by ErrorProne in the `gson/src/test.*` path. I have added the `final` keyword, or I have added the `@SuppressWarnings("ImmutableEnumChecker")` annotation * Fixes `StaticAssignmentOfThrowable` warns This commit fix all `StaticAssignmentOfThrowable` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `AssertionFailureIgnored` warns This commit fix all `AssertionFailureIgnored` warns given by ErrorProne in the `gson/src/test.*` path. I have added the `@SuppressWarnings("AssertionFailureIgnored")` annotation * Fixes `ModifiedButNotUsed` warns This commit fix all `ModifiedButNotUsed` warns given by ErrorProne in the `gson/src/test.*` path. I have added the `@SuppressWarnings("ModifiedButNotUsed")` annotation * Fixes `MissingSummary` warns This commit fix all `MissingSummary` warns given by ErrorProne in the `gson/src/test.*` path. I have remove the Javadoc `@author` * Fixes `FloatingPointLiteralPrecision` warns This commit fix all `FloatingPointLiteralPrecision` warns given by ErrorProne in the `gson/src/test.*` path. I have added the `@SuppressWarnings("FloatingPointLiteralPrecision")` annotation * Fixes `StringSplitter` warns This commit fix all `StringSplitter` warns given by ErrorProne in the `gson/src/test.*` path. I have replaced the `String.split(...)` with `Splitter` * Fixes `EmptyCatch` warns This commit fix all `EmptyCatch` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `UnicodeEscape` warns This commit fix all `UnicodeEscape` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `EmptyBlockTag` warns This commit fix all `EmptyBlockTag` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `LongFloatConversion` warns This commit fix all `LongFloatConversion` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `LongDoubleConversion` warns This commit fix all `LongDoubleConversion` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `TruthAssertExpected` warns This commit fix all `TruthAssertExpected` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `UnusedMethod` warns This commit fix all `UnusedMethod` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `UnusedTypeParameter` warns This commit fix all `UnusedTypeParameter` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `CatchFail` warns This commit fix all `CatchFail` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `MathAbsoluteNegative` warns This commit fix all `MathAbsoluteNegative` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `LoopOverCharArray` warns This commit fix all `LoopOverCharArray` warns given by ErrorProne in the `gson/src/test.*` path. `toCharArray` allocates a new array, using `charAt` is more efficient * Fixes `HidingField` warns This commit fix all `HidingField` warns given by ErrorProne in the `gson/src/test.*` path. * Implements code review feedback * Implements code review feedback This commit implements some other code review feedback * Enable ErrorProne in `extra` Thi commit removes the `.*extras/src/test.*` path from the `-XepExcludedPaths` parameter of ErrorProne. * Fix the `JavaUtilDate` warns This commit fix all `JavaUtilDate` warns given by ErrorProne in the `extras/src/test.*` path. * Implements code review feedback * Removes redundant new-line * Implements code review feedback * Adds `JDK11` to run test with `--release 11` * Revert "Adds `JDK11` to run test with `--release 11`" This reverts commit a7cca386098ae847a10a31c09c3ab9b11eee5920.
2023-03-01 23:23:27 +01:00
@SuppressWarnings({"unchecked", "TypeParameterUnusedInFormals"})
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
public <T> 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.
*
* <p>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 <T> the type of the desired object
* @param json the string from which the object is to be deserialized
* @param typeOfT The specific genericized type of src. You should create an anonymous subclass of
* {@code TypeToken} with the specific generic type arguments. For example, to get the type
2008-09-01 05:13:32 +02:00
* for {@code Collection<Foo>}, you should use:
* <pre>
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* new TypeToken&lt;Collection&lt;Foo&gt;&gt;(){}
2008-09-01 05:13:32 +02:00
* </pre>
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
*
* @return an object of type T from the string. Returns {@code null} if {@code json} is {@code
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* 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
2008-09-01 05:13:32 +02:00
*/
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
public <T> T fromJson(String json, TypeToken<T> typeOfT) throws JsonSyntaxException {
if (json == null) {
return null;
}
2011-11-13 01:04:39 +01:00
StringReader reader = new StringReader(json);
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
return fromJson(reader, typeOfT);
2008-09-01 05:13:32 +02:00
}
/**
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* This method deserializes the JSON read from the specified reader into an object of the
2008-09-01 05:13:32 +02:00
* 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
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* method works fine if any of the fields of the specified object are generics, just the object
2008-09-01 05:13:32 +02:00
* itself should not be a generic type. For the cases when the object is of generic type, invoke
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* {@link #fromJson(Reader, TypeToken)}. If you have the JSON in a String form instead of a {@link
2008-09-01 05:13:32 +02:00
* Reader}, use {@link #fromJson(String, Class)} instead.
*
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* <p>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.
*
2008-09-01 05:13:32 +02:00
* @param <T> the type of the desired object
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* @param json the reader producing the JSON from which the object is to be deserialized.
2008-09-01 05:13:32 +02:00
* @param classOfT the class of T
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* @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
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* @throws JsonSyntaxException if json is not a valid representation for an object of type typeOfT
2008-09-01 05:13:32 +02:00
* @since 1.2
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* @see #fromJson(String, Class)
* @see #fromJson(Reader, TypeToken)
2008-09-01 05:13:32 +02:00
*/
public <T> T fromJson(Reader json, Class<T> classOfT)
throws JsonSyntaxException, JsonIOException {
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
T object = fromJson(json, TypeToken.get(classOfT));
return Primitives.wrap(classOfT).cast(object);
2008-09-01 05:13:32 +02:00
}
/**
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* This method deserializes the JSON read from the specified reader into an object of the
2008-09-01 05:13:32 +02:00
* specified type. This method is useful if the specified object is a generic type. For
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* non-generic objects, use {@link #fromJson(Reader, Class)} instead. If you have the JSON in a
2008-09-01 05:13:32 +02:00
* String form instead of a {@link Reader}, use {@link #fromJson(String, Type)} instead.
*
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* <p>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.
*
* <p>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.
*
2008-09-01 05:13:32 +02:00
* @param <T> the type of the desired object
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* @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)
*/
Fix error prone warns (#2320) * Adds `@SuppressWarnings("NarrowingCompoundAssignment")` * Adds `@SuppressWarnings("TypeParameterUnusedInFormals")` * Adds `@SuppressWarnings("JavaUtilDate")` * Adds a limit to `String.split()` * Add `error_prone_annotations` to the `pom.xml` * Adds `@InlineMe(...)` to deprecated methods * Adds `@SuppressWarnings("ImmutableEnumChecker")` * Adds `@SuppressWarnings("ModifiedButNotUsed")` * Adds `@SuppressWarnings("MixedMutabilityReturnType")` * Removes an unused import * Adds `requires` to `module-info.java` * Adds ErrorProne `link` into `pom.xml` * Remove unused imports Removed from: - ParseBenchmark * Adds `@SuppressWarnings("EqualsGetClass")` * Excludes from `proto` just the generated code. Replaces `.*proto.*` with `.*/generated-test-sources/protobuf/.*` in such way will be excluded just the generated code and not the whole `proto` directory * Removes an unused variable Removes the `descriptor` variable because is unused. * Fixes the `BadImport` warn into `ProtosWithAnnotationsTest` * Fixes the `BadImport` warns into `ProtosWithAnnotationsTest` * Enables ErrorProne in `gson/src/test.*` Removes the `gson/src/test.*` path from the `-XepExcludedPaths` parameter of the ErrorProne plugin * Fixes `UnusedVariable` warns This commit fix all `UnusedVariable` warns given by ErrorProne in the `gson/src/test.*` path. Some field is annotated with `@Keep` that means is used by reflection. In some other case the record is annotated with `@SuppressWarnings("unused")` * Fixes `JavaUtilDate` warns This commit fix all `JavaUtilDate` warns given by ErrorProne in the `gson/src/test.*` path. Classes/Methods are annotated with `@SuppressWarnings("JavaUtilDate")` because it's not possible use differente Date API. * Fixes `EqualsGetClass` warns This commit fix all `EqualsGetClass` warns given by ErrorProne in the `gson/src/test.*` path. I have rewrite the `equals()` methods to use `instanceof` * Replaces pattern matching for instanceof with casts * Fixes `JdkObsolete` warns This commit fix all `JdkObsolete` warns given by ErrorProne in the `gson/src/test.*` path. In some cases I have replaced the obsolete JDK classes with the newest alternatives. In other cases, I have added the `@SuppressWarnings("JdkObsolete")` * Fixes `ClassCanBeStatic` warns This commit fix all `ClassCanBeStatic` warns given by ErrorProne in the `gson/src/test.*` path. I have added the `static` keyword, or I have added `@SuppressWarnings("ClassCanBeStatic")` * Fixes `UndefinedEquals` warns This commit fix all `UndefinedEquals` warns given by ErrorProne in the `gson/src/test.*` path. I have added `@SuppressWarnings("UndefinedEquals")` or fixed the asserts Note: In this commit I have also renamed a test from `testRawCollectionDeserializationNotAlllowed` to `testRawCollectionDeserializationNotAllowed` * Fixes `GetClassOnEnum` warns This commit fix all `GetClassOnEnum` warns given by ErrorProne in the `gson/src/test.*` path. I have replaced the `.getClass()` with `.getDeclaringClass()` * Fixes `ImmutableEnumChecker` warns This commit fix all `ImmutableEnumChecker` warns given by ErrorProne in the `gson/src/test.*` path. I have added the `final` keyword, or I have added the `@SuppressWarnings("ImmutableEnumChecker")` annotation * Fixes `StaticAssignmentOfThrowable` warns This commit fix all `StaticAssignmentOfThrowable` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `AssertionFailureIgnored` warns This commit fix all `AssertionFailureIgnored` warns given by ErrorProne in the `gson/src/test.*` path. I have added the `@SuppressWarnings("AssertionFailureIgnored")` annotation * Fixes `ModifiedButNotUsed` warns This commit fix all `ModifiedButNotUsed` warns given by ErrorProne in the `gson/src/test.*` path. I have added the `@SuppressWarnings("ModifiedButNotUsed")` annotation * Fixes `MissingSummary` warns This commit fix all `MissingSummary` warns given by ErrorProne in the `gson/src/test.*` path. I have remove the Javadoc `@author` * Fixes `FloatingPointLiteralPrecision` warns This commit fix all `FloatingPointLiteralPrecision` warns given by ErrorProne in the `gson/src/test.*` path. I have added the `@SuppressWarnings("FloatingPointLiteralPrecision")` annotation * Fixes `StringSplitter` warns This commit fix all `StringSplitter` warns given by ErrorProne in the `gson/src/test.*` path. I have replaced the `String.split(...)` with `Splitter` * Fixes `EmptyCatch` warns This commit fix all `EmptyCatch` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `UnicodeEscape` warns This commit fix all `UnicodeEscape` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `EmptyBlockTag` warns This commit fix all `EmptyBlockTag` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `LongFloatConversion` warns This commit fix all `LongFloatConversion` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `LongDoubleConversion` warns This commit fix all `LongDoubleConversion` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `TruthAssertExpected` warns This commit fix all `TruthAssertExpected` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `UnusedMethod` warns This commit fix all `UnusedMethod` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `UnusedTypeParameter` warns This commit fix all `UnusedTypeParameter` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `CatchFail` warns This commit fix all `CatchFail` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `MathAbsoluteNegative` warns This commit fix all `MathAbsoluteNegative` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `LoopOverCharArray` warns This commit fix all `LoopOverCharArray` warns given by ErrorProne in the `gson/src/test.*` path. `toCharArray` allocates a new array, using `charAt` is more efficient * Fixes `HidingField` warns This commit fix all `HidingField` warns given by ErrorProne in the `gson/src/test.*` path. * Implements code review feedback * Implements code review feedback This commit implements some other code review feedback * Enable ErrorProne in `extra` Thi commit removes the `.*extras/src/test.*` path from the `-XepExcludedPaths` parameter of ErrorProne. * Fix the `JavaUtilDate` warns This commit fix all `JavaUtilDate` warns given by ErrorProne in the `extras/src/test.*` path. * Implements code review feedback * Removes redundant new-line * Implements code review feedback * Adds `JDK11` to run test with `--release 11` * Revert "Adds `JDK11` to run test with `--release 11`" This reverts commit a7cca386098ae847a10a31c09c3ab9b11eee5920.
2023-03-01 23:23:27 +01:00
@SuppressWarnings({"unchecked", "TypeParameterUnusedInFormals"})
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
public <T> 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.
*
* <p>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.
*
2008-09-01 05:13:32 +02:00
* @param <T> the type of the desired object
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* @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
2008-09-01 05:13:32 +02:00
* for {@code Collection<Foo>}, you should use:
* <pre>
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* new TypeToken&lt;Collection&lt;Foo&gt;&gt;(){}
2008-09-01 05:13:32 +02:00
* </pre>
*
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* @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
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* @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
2008-09-01 05:13:32 +02:00
*/
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
public <T> T fromJson(Reader json, TypeToken<T> typeOfT)
throws JsonIOException, JsonSyntaxException {
JsonReader jsonReader = newJsonReader(json);
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
T object = fromJson(jsonReader, typeOfT);
assertFullConsumption(object, jsonReader);
return object;
}
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
// 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
/**
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* 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.
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
*
* <p>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)}.
*
* <p>Unlike the other {@code fromJson} methods, no exception is thrown if the JSON data has
* multiple top-level JSON elements, or if there is trailing data.
*
Strict mode for JSON parsing, contributed by @marten-voorberg. (#2437) * Strict mode for JSON parsing (#2323) * Feat #6: Add strict flag to Gson and GsonBuilder * Test #2: Add failing tests for capitalized keywords * Feat #2: JsonReader does not read (partially) capitalized keywords if strict mode is used * Feat #3: Added implementation and tests for JSONReader not accepting specific escape sequence representing in strict mode * Test #3: Simplify test cases by removing unnecessary array * Feat #3: Improve error by including the illegal character * Feat #5: JsonReader does not allow unespaced control flow characters in strict mode * Test #5: Test unespaced control flow characters in strict mode * Feat #4: Disallow espaced newline character in strict mode * Test #4: Add tests for (dis)allowing newline character depensding on strictness * Test #5: Test case for unescaped control char in non-strict mode * Test #2: Simplify test cases * Feat #13: Change leniency API to Strictness enum in JsonReader, Gson, and GsonBuilder * Feat #15: Change JsonWriter API to also use Strictness * Test #15: Test Strictness in JsonWriter API * Doc #15: Add and update documentation for Strictness in JsonWriter API * refactor #12: Fixed typos and empty catch brackets in tests * refactor #12: Resolved importing wildcards, made some lines adhere to Google java style * #5 Add test case for unescaped control characters * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue --------- Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * Doc #17: Add and change javadoc of public methods * Doc #17: Update JavaDoc in JsonReader and Strictness * Doc #17: Update JavaDoc in Gson and GsonBuilder * Test #34: Add tests for setting strictness through GsonBuilder * Fix: Add Fix broken test * Fix: Invalid JavaDoc in Gson.java * Doc #17: update outdated javadoc * #37: Resolve more PR feedback * Fix #37: Resolve various PR comments * Fix #37: Resolve various PR comments * Refactor #35: Refactor JsonReader#peekKeyword to reduce the amount of strictness checks (#39) * Doc #40: Update JavaDoc based on PR feedback * Doc #40: Update old RFC in GsonBuilder documentation * Doc #40: Fix formatting error in JavaDoc * Doc #40: Add tests for setting strictness and lenient to JsonReaderTest * Test #43: Changed tests to make use of assertThrows * test #43: Changed tests to make use of assertThrows as per feedback * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * test #43: Resolve PR recommendations * Test #43: Mini change to TC * Test #43: Mini change to TC --------- Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * doc #46: Resolved comments in main PR * Feat #45: Change Gson.fromJson and Gson.toJson to be strict when the provided writer/reader is strict * Fix #45: Small type * Update gson/src/test/java/com/google/gson/stream/JsonReaderTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Update gson/src/main/java/com/google/gson/GsonBuilder.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Fix #45: Resolve various comments by eamonmcmanus * Strictness mode follow-up * Update Troubleshooting.md and Gson default lenient mode documentation * Always use GSON strictness when set. * Rename Strictness.DEFAULT to Strictness.LEGACY_STRICT * Update JavaDoc with new strictness functionality * Replace default with legacy strict for JsonReader javadoc * Add JSONReader test cases for U2028 and U2029 * Refactor JSONReader#peekKeyWord() based on @eamonmcmanus's suggestion * Deprecate setLenient in favor of setStrictness --------- Co-authored-by: Carl Peterson <unknown> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Strictness follow-up (#2408) * Strictness mode follow-up - Remove mentions of `null` Gson strictness; this is an implementation detail - Fix incorrect / outdated documentation - Reduce links to RFC; if there is already a link to it in a previous sentence don't link to it again - Extend and update tests - Minor punctuation changes in documentation for consistency * Deprecate `setLenient` methods * `strictness2` fixes & improvements (#2456) * Adjust ProGuard default rules and shrinking tests (#2420) * Adjust ProGuard default rules and shrinking tests * Adjust comment * Add shrinking test for class without no-args constructor; improve docs * Improve Unsafe mention in Troubleshooting Guide * Improve comment for `-if class *` * Bump com.google.guava:guava from 32.0.1-jre to 32.1.1-jre (#2444) Bumps [com.google.guava:guava](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Bump com.google.guava:guava-testlib from 32.0.1-jre to 32.1.1-jre (#2443) Bumps [com.google.guava:guava-testlib](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava-testlib dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Support non-generic type for `TypeToken.getParameterized` for legacy reasons (#2447) This partially restores the behavior before a589ef20087b4b0f1ec3048d3ceaef1eedccd09d, except that back then for a non-generic type a bogus `TypeToken(ParameterizedType)` was created, whereas now a `TypeToken(Class)` is created instead. * Fixed Typo in GsonBuilder.java (#2449) * Make date-formatting tests less fragile with regular expressions. (#2450) * Make date-formatting tests less fragile with regular expressions. This is not great. We should really ensure that formatted dates are the same regardless of JDK version. There is code that attempts to do that but it is not really effective. So for now we fudge around the differences by using regular expressions to paper over the differences. * Temporarily add test-debugging code. * Another attempt at debugging a test failure. * Fix pattern in assertion. * Modification in test cases (#2454) * Fixed Typo in GsonBuilder.java * Suggestions on Test cases * Modified test cases using assertThrows method (JUnit) * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/GsonTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> --------- Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Minor follow-up changes --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Éamonn McManus <emcmanus@google.com> Co-authored-by: Wonil <cwi5525@naver.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Marten <martenvoorberg@gmail.com> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Wonil <cwi5525@naver.com>
2023-07-30 18:20:32 +02:00
* <p>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.<br>
* Note that in all cases the old strictness setting of the reader will be restored when this
* method returns.
*
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* @param <T> 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)
*/
Fix error prone warns (#2320) * Adds `@SuppressWarnings("NarrowingCompoundAssignment")` * Adds `@SuppressWarnings("TypeParameterUnusedInFormals")` * Adds `@SuppressWarnings("JavaUtilDate")` * Adds a limit to `String.split()` * Add `error_prone_annotations` to the `pom.xml` * Adds `@InlineMe(...)` to deprecated methods * Adds `@SuppressWarnings("ImmutableEnumChecker")` * Adds `@SuppressWarnings("ModifiedButNotUsed")` * Adds `@SuppressWarnings("MixedMutabilityReturnType")` * Removes an unused import * Adds `requires` to `module-info.java` * Adds ErrorProne `link` into `pom.xml` * Remove unused imports Removed from: - ParseBenchmark * Adds `@SuppressWarnings("EqualsGetClass")` * Excludes from `proto` just the generated code. Replaces `.*proto.*` with `.*/generated-test-sources/protobuf/.*` in such way will be excluded just the generated code and not the whole `proto` directory * Removes an unused variable Removes the `descriptor` variable because is unused. * Fixes the `BadImport` warn into `ProtosWithAnnotationsTest` * Fixes the `BadImport` warns into `ProtosWithAnnotationsTest` * Enables ErrorProne in `gson/src/test.*` Removes the `gson/src/test.*` path from the `-XepExcludedPaths` parameter of the ErrorProne plugin * Fixes `UnusedVariable` warns This commit fix all `UnusedVariable` warns given by ErrorProne in the `gson/src/test.*` path. Some field is annotated with `@Keep` that means is used by reflection. In some other case the record is annotated with `@SuppressWarnings("unused")` * Fixes `JavaUtilDate` warns This commit fix all `JavaUtilDate` warns given by ErrorProne in the `gson/src/test.*` path. Classes/Methods are annotated with `@SuppressWarnings("JavaUtilDate")` because it's not possible use differente Date API. * Fixes `EqualsGetClass` warns This commit fix all `EqualsGetClass` warns given by ErrorProne in the `gson/src/test.*` path. I have rewrite the `equals()` methods to use `instanceof` * Replaces pattern matching for instanceof with casts * Fixes `JdkObsolete` warns This commit fix all `JdkObsolete` warns given by ErrorProne in the `gson/src/test.*` path. In some cases I have replaced the obsolete JDK classes with the newest alternatives. In other cases, I have added the `@SuppressWarnings("JdkObsolete")` * Fixes `ClassCanBeStatic` warns This commit fix all `ClassCanBeStatic` warns given by ErrorProne in the `gson/src/test.*` path. I have added the `static` keyword, or I have added `@SuppressWarnings("ClassCanBeStatic")` * Fixes `UndefinedEquals` warns This commit fix all `UndefinedEquals` warns given by ErrorProne in the `gson/src/test.*` path. I have added `@SuppressWarnings("UndefinedEquals")` or fixed the asserts Note: In this commit I have also renamed a test from `testRawCollectionDeserializationNotAlllowed` to `testRawCollectionDeserializationNotAllowed` * Fixes `GetClassOnEnum` warns This commit fix all `GetClassOnEnum` warns given by ErrorProne in the `gson/src/test.*` path. I have replaced the `.getClass()` with `.getDeclaringClass()` * Fixes `ImmutableEnumChecker` warns This commit fix all `ImmutableEnumChecker` warns given by ErrorProne in the `gson/src/test.*` path. I have added the `final` keyword, or I have added the `@SuppressWarnings("ImmutableEnumChecker")` annotation * Fixes `StaticAssignmentOfThrowable` warns This commit fix all `StaticAssignmentOfThrowable` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `AssertionFailureIgnored` warns This commit fix all `AssertionFailureIgnored` warns given by ErrorProne in the `gson/src/test.*` path. I have added the `@SuppressWarnings("AssertionFailureIgnored")` annotation * Fixes `ModifiedButNotUsed` warns This commit fix all `ModifiedButNotUsed` warns given by ErrorProne in the `gson/src/test.*` path. I have added the `@SuppressWarnings("ModifiedButNotUsed")` annotation * Fixes `MissingSummary` warns This commit fix all `MissingSummary` warns given by ErrorProne in the `gson/src/test.*` path. I have remove the Javadoc `@author` * Fixes `FloatingPointLiteralPrecision` warns This commit fix all `FloatingPointLiteralPrecision` warns given by ErrorProne in the `gson/src/test.*` path. I have added the `@SuppressWarnings("FloatingPointLiteralPrecision")` annotation * Fixes `StringSplitter` warns This commit fix all `StringSplitter` warns given by ErrorProne in the `gson/src/test.*` path. I have replaced the `String.split(...)` with `Splitter` * Fixes `EmptyCatch` warns This commit fix all `EmptyCatch` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `UnicodeEscape` warns This commit fix all `UnicodeEscape` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `EmptyBlockTag` warns This commit fix all `EmptyBlockTag` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `LongFloatConversion` warns This commit fix all `LongFloatConversion` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `LongDoubleConversion` warns This commit fix all `LongDoubleConversion` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `TruthAssertExpected` warns This commit fix all `TruthAssertExpected` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `UnusedMethod` warns This commit fix all `UnusedMethod` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `UnusedTypeParameter` warns This commit fix all `UnusedTypeParameter` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `CatchFail` warns This commit fix all `CatchFail` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `MathAbsoluteNegative` warns This commit fix all `MathAbsoluteNegative` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `LoopOverCharArray` warns This commit fix all `LoopOverCharArray` warns given by ErrorProne in the `gson/src/test.*` path. `toCharArray` allocates a new array, using `charAt` is more efficient * Fixes `HidingField` warns This commit fix all `HidingField` warns given by ErrorProne in the `gson/src/test.*` path. * Implements code review feedback * Implements code review feedback This commit implements some other code review feedback * Enable ErrorProne in `extra` Thi commit removes the `.*extras/src/test.*` path from the `-XepExcludedPaths` parameter of ErrorProne. * Fix the `JavaUtilDate` warns This commit fix all `JavaUtilDate` warns given by ErrorProne in the `extras/src/test.*` path. * Implements code review feedback * Removes redundant new-line * Implements code review feedback * Adds `JDK11` to run test with `--release 11` * Revert "Adds `JDK11` to run test with `--release 11`" This reverts commit a7cca386098ae847a10a31c09c3ab9b11eee5920.
2023-03-01 23:23:27 +01:00
@SuppressWarnings({"unchecked", "TypeParameterUnusedInFormals"})
public <T> T fromJson(JsonReader reader, Type typeOfT)
throws JsonIOException, JsonSyntaxException {
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
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.
*
* <p>Unlike the other {@code fromJson} methods, no exception is thrown if the JSON data has
* multiple top-level JSON elements, or if there is trailing data.
*
Strict mode for JSON parsing, contributed by @marten-voorberg. (#2437) * Strict mode for JSON parsing (#2323) * Feat #6: Add strict flag to Gson and GsonBuilder * Test #2: Add failing tests for capitalized keywords * Feat #2: JsonReader does not read (partially) capitalized keywords if strict mode is used * Feat #3: Added implementation and tests for JSONReader not accepting specific escape sequence representing in strict mode * Test #3: Simplify test cases by removing unnecessary array * Feat #3: Improve error by including the illegal character * Feat #5: JsonReader does not allow unespaced control flow characters in strict mode * Test #5: Test unespaced control flow characters in strict mode * Feat #4: Disallow espaced newline character in strict mode * Test #4: Add tests for (dis)allowing newline character depensding on strictness * Test #5: Test case for unescaped control char in non-strict mode * Test #2: Simplify test cases * Feat #13: Change leniency API to Strictness enum in JsonReader, Gson, and GsonBuilder * Feat #15: Change JsonWriter API to also use Strictness * Test #15: Test Strictness in JsonWriter API * Doc #15: Add and update documentation for Strictness in JsonWriter API * refactor #12: Fixed typos and empty catch brackets in tests * refactor #12: Resolved importing wildcards, made some lines adhere to Google java style * #5 Add test case for unescaped control characters * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue --------- Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * Doc #17: Add and change javadoc of public methods * Doc #17: Update JavaDoc in JsonReader and Strictness * Doc #17: Update JavaDoc in Gson and GsonBuilder * Test #34: Add tests for setting strictness through GsonBuilder * Fix: Add Fix broken test * Fix: Invalid JavaDoc in Gson.java * Doc #17: update outdated javadoc * #37: Resolve more PR feedback * Fix #37: Resolve various PR comments * Fix #37: Resolve various PR comments * Refactor #35: Refactor JsonReader#peekKeyword to reduce the amount of strictness checks (#39) * Doc #40: Update JavaDoc based on PR feedback * Doc #40: Update old RFC in GsonBuilder documentation * Doc #40: Fix formatting error in JavaDoc * Doc #40: Add tests for setting strictness and lenient to JsonReaderTest * Test #43: Changed tests to make use of assertThrows * test #43: Changed tests to make use of assertThrows as per feedback * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * test #43: Resolve PR recommendations * Test #43: Mini change to TC * Test #43: Mini change to TC --------- Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * doc #46: Resolved comments in main PR * Feat #45: Change Gson.fromJson and Gson.toJson to be strict when the provided writer/reader is strict * Fix #45: Small type * Update gson/src/test/java/com/google/gson/stream/JsonReaderTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Update gson/src/main/java/com/google/gson/GsonBuilder.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Fix #45: Resolve various comments by eamonmcmanus * Strictness mode follow-up * Update Troubleshooting.md and Gson default lenient mode documentation * Always use GSON strictness when set. * Rename Strictness.DEFAULT to Strictness.LEGACY_STRICT * Update JavaDoc with new strictness functionality * Replace default with legacy strict for JsonReader javadoc * Add JSONReader test cases for U2028 and U2029 * Refactor JSONReader#peekKeyWord() based on @eamonmcmanus's suggestion * Deprecate setLenient in favor of setStrictness --------- Co-authored-by: Carl Peterson <unknown> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Strictness follow-up (#2408) * Strictness mode follow-up - Remove mentions of `null` Gson strictness; this is an implementation detail - Fix incorrect / outdated documentation - Reduce links to RFC; if there is already a link to it in a previous sentence don't link to it again - Extend and update tests - Minor punctuation changes in documentation for consistency * Deprecate `setLenient` methods * `strictness2` fixes & improvements (#2456) * Adjust ProGuard default rules and shrinking tests (#2420) * Adjust ProGuard default rules and shrinking tests * Adjust comment * Add shrinking test for class without no-args constructor; improve docs * Improve Unsafe mention in Troubleshooting Guide * Improve comment for `-if class *` * Bump com.google.guava:guava from 32.0.1-jre to 32.1.1-jre (#2444) Bumps [com.google.guava:guava](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Bump com.google.guava:guava-testlib from 32.0.1-jre to 32.1.1-jre (#2443) Bumps [com.google.guava:guava-testlib](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava-testlib dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Support non-generic type for `TypeToken.getParameterized` for legacy reasons (#2447) This partially restores the behavior before a589ef20087b4b0f1ec3048d3ceaef1eedccd09d, except that back then for a non-generic type a bogus `TypeToken(ParameterizedType)` was created, whereas now a `TypeToken(Class)` is created instead. * Fixed Typo in GsonBuilder.java (#2449) * Make date-formatting tests less fragile with regular expressions. (#2450) * Make date-formatting tests less fragile with regular expressions. This is not great. We should really ensure that formatted dates are the same regardless of JDK version. There is code that attempts to do that but it is not really effective. So for now we fudge around the differences by using regular expressions to paper over the differences. * Temporarily add test-debugging code. * Another attempt at debugging a test failure. * Fix pattern in assertion. * Modification in test cases (#2454) * Fixed Typo in GsonBuilder.java * Suggestions on Test cases * Modified test cases using assertThrows method (JUnit) * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/GsonTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> --------- Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Minor follow-up changes --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Éamonn McManus <emcmanus@google.com> Co-authored-by: Wonil <cwi5525@naver.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Marten <martenvoorberg@gmail.com> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Wonil <cwi5525@naver.com>
2023-07-30 18:20:32 +02:00
* <p>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.<br>
* Note that in all cases the old strictness setting of the reader will be restored when this
* method returns.
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
*
* @param <T> 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<Foo>}, you should use:
* <pre>
* new TypeToken&lt;Collection&lt;Foo&gt;&gt;(){}
* </pre>
*
* @return an object of type T from the JsonReader. Returns {@code null} if {@code reader} is at
* EOF.
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* @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
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
*/
public <T> T fromJson(JsonReader reader, TypeToken<T> typeOfT)
throws JsonIOException, JsonSyntaxException {
Down to 22 failing tests. Consolidated all of the different code paths that we use to construct instances. We now have an ObjectConstructor class that knows what type it constructs; this means that we don't need to ever do reflection to lookup a constructor at construction time. Cleaned up some buggy type adapters, particularly around handling of null. Removed dead code for object graph navigation. Moved some classes into 'internal' so they are visible to the 'bind' subpackage. Turned some TypeAdapterFactory/TypeAdapter pairs inside out so that the TypeAdapter is now the inner class. This is necessary so that the factories can take parameters. Added an API to request the 'next' type adapter for a type. This allows type adapters to compose other type adapters. We're using this in two places: - where the user has excluded a type from serialization but not deserialization, we need to use the "default" deserialization but interpose null on serialization. We create a type adapter that delegates for one and returns null for the other. - similarly when a DOM type serializer is registered but no deserializer, or vice versa. This is the biggest change to the MiniGson core. For backwards compatibility, return null for the empty string. Simplify JsonSerializationContext/JsonDeserializationContext to simply call through to GSON. SerializeDefault is currently unsupported. More useful error messages when calling getAsBoolean on a JsonNull. Remove currently unused MemoryRefStack. We might need this back again, though wiring it back in will be much more difficult because we don't interject ourselves between the users' various type adapters.
2011-09-11 09:04:56 +02:00
boolean isEmpty = true;
Strict mode for JSON parsing, contributed by @marten-voorberg. (#2437) * Strict mode for JSON parsing (#2323) * Feat #6: Add strict flag to Gson and GsonBuilder * Test #2: Add failing tests for capitalized keywords * Feat #2: JsonReader does not read (partially) capitalized keywords if strict mode is used * Feat #3: Added implementation and tests for JSONReader not accepting specific escape sequence representing in strict mode * Test #3: Simplify test cases by removing unnecessary array * Feat #3: Improve error by including the illegal character * Feat #5: JsonReader does not allow unespaced control flow characters in strict mode * Test #5: Test unespaced control flow characters in strict mode * Feat #4: Disallow espaced newline character in strict mode * Test #4: Add tests for (dis)allowing newline character depensding on strictness * Test #5: Test case for unescaped control char in non-strict mode * Test #2: Simplify test cases * Feat #13: Change leniency API to Strictness enum in JsonReader, Gson, and GsonBuilder * Feat #15: Change JsonWriter API to also use Strictness * Test #15: Test Strictness in JsonWriter API * Doc #15: Add and update documentation for Strictness in JsonWriter API * refactor #12: Fixed typos and empty catch brackets in tests * refactor #12: Resolved importing wildcards, made some lines adhere to Google java style * #5 Add test case for unescaped control characters * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue --------- Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * Doc #17: Add and change javadoc of public methods * Doc #17: Update JavaDoc in JsonReader and Strictness * Doc #17: Update JavaDoc in Gson and GsonBuilder * Test #34: Add tests for setting strictness through GsonBuilder * Fix: Add Fix broken test * Fix: Invalid JavaDoc in Gson.java * Doc #17: update outdated javadoc * #37: Resolve more PR feedback * Fix #37: Resolve various PR comments * Fix #37: Resolve various PR comments * Refactor #35: Refactor JsonReader#peekKeyword to reduce the amount of strictness checks (#39) * Doc #40: Update JavaDoc based on PR feedback * Doc #40: Update old RFC in GsonBuilder documentation * Doc #40: Fix formatting error in JavaDoc * Doc #40: Add tests for setting strictness and lenient to JsonReaderTest * Test #43: Changed tests to make use of assertThrows * test #43: Changed tests to make use of assertThrows as per feedback * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * test #43: Resolve PR recommendations * Test #43: Mini change to TC * Test #43: Mini change to TC --------- Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * doc #46: Resolved comments in main PR * Feat #45: Change Gson.fromJson and Gson.toJson to be strict when the provided writer/reader is strict * Fix #45: Small type * Update gson/src/test/java/com/google/gson/stream/JsonReaderTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Update gson/src/main/java/com/google/gson/GsonBuilder.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Fix #45: Resolve various comments by eamonmcmanus * Strictness mode follow-up * Update Troubleshooting.md and Gson default lenient mode documentation * Always use GSON strictness when set. * Rename Strictness.DEFAULT to Strictness.LEGACY_STRICT * Update JavaDoc with new strictness functionality * Replace default with legacy strict for JsonReader javadoc * Add JSONReader test cases for U2028 and U2029 * Refactor JSONReader#peekKeyWord() based on @eamonmcmanus's suggestion * Deprecate setLenient in favor of setStrictness --------- Co-authored-by: Carl Peterson <unknown> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Strictness follow-up (#2408) * Strictness mode follow-up - Remove mentions of `null` Gson strictness; this is an implementation detail - Fix incorrect / outdated documentation - Reduce links to RFC; if there is already a link to it in a previous sentence don't link to it again - Extend and update tests - Minor punctuation changes in documentation for consistency * Deprecate `setLenient` methods * `strictness2` fixes & improvements (#2456) * Adjust ProGuard default rules and shrinking tests (#2420) * Adjust ProGuard default rules and shrinking tests * Adjust comment * Add shrinking test for class without no-args constructor; improve docs * Improve Unsafe mention in Troubleshooting Guide * Improve comment for `-if class *` * Bump com.google.guava:guava from 32.0.1-jre to 32.1.1-jre (#2444) Bumps [com.google.guava:guava](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Bump com.google.guava:guava-testlib from 32.0.1-jre to 32.1.1-jre (#2443) Bumps [com.google.guava:guava-testlib](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava-testlib dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Support non-generic type for `TypeToken.getParameterized` for legacy reasons (#2447) This partially restores the behavior before a589ef20087b4b0f1ec3048d3ceaef1eedccd09d, except that back then for a non-generic type a bogus `TypeToken(ParameterizedType)` was created, whereas now a `TypeToken(Class)` is created instead. * Fixed Typo in GsonBuilder.java (#2449) * Make date-formatting tests less fragile with regular expressions. (#2450) * Make date-formatting tests less fragile with regular expressions. This is not great. We should really ensure that formatted dates are the same regardless of JDK version. There is code that attempts to do that but it is not really effective. So for now we fudge around the differences by using regular expressions to paper over the differences. * Temporarily add test-debugging code. * Another attempt at debugging a test failure. * Fix pattern in assertion. * Modification in test cases (#2454) * Fixed Typo in GsonBuilder.java * Suggestions on Test cases * Modified test cases using assertThrows method (JUnit) * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/GsonTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> --------- Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Minor follow-up changes --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Éamonn McManus <emcmanus@google.com> Co-authored-by: Wonil <cwi5525@naver.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Marten <martenvoorberg@gmail.com> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Wonil <cwi5525@naver.com>
2023-07-30 18:20:32 +02:00
Strictness oldStrictness = reader.getStrictness();
if (this.strictness != null) {
reader.setStrictness(this.strictness);
} else if (reader.getStrictness() != Strictness.STRICT) {
reader.setStrictness(Strictness.LENIENT);
}
try {
JsonToken unused = reader.peek();
Down to 22 failing tests. Consolidated all of the different code paths that we use to construct instances. We now have an ObjectConstructor class that knows what type it constructs; this means that we don't need to ever do reflection to lookup a constructor at construction time. Cleaned up some buggy type adapters, particularly around handling of null. Removed dead code for object graph navigation. Moved some classes into 'internal' so they are visible to the 'bind' subpackage. Turned some TypeAdapterFactory/TypeAdapter pairs inside out so that the TypeAdapter is now the inner class. This is necessary so that the factories can take parameters. Added an API to request the 'next' type adapter for a type. This allows type adapters to compose other type adapters. We're using this in two places: - where the user has excluded a type from serialization but not deserialization, we need to use the "default" deserialization but interpose null on serialization. We create a type adapter that delegates for one and returns null for the other. - similarly when a DOM type serializer is registered but no deserializer, or vice versa. This is the biggest change to the MiniGson core. For backwards compatibility, return null for the empty string. Simplify JsonSerializationContext/JsonDeserializationContext to simply call through to GSON. SerializeDefault is currently unsupported. More useful error messages when calling getAsBoolean on a JsonNull. Remove currently unused MemoryRefStack. We might need this back again, though wiring it back in will be much more difficult because we don't interject ourselves between the users' various type adapters.
2011-09-11 09:04:56 +02:00
isEmpty = false;
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
TypeAdapter<T> typeAdapter = getAdapter(typeOfT);
return typeAdapter.read(reader);
Down to 22 failing tests. Consolidated all of the different code paths that we use to construct instances. We now have an ObjectConstructor class that knows what type it constructs; this means that we don't need to ever do reflection to lookup a constructor at construction time. Cleaned up some buggy type adapters, particularly around handling of null. Removed dead code for object graph navigation. Moved some classes into 'internal' so they are visible to the 'bind' subpackage. Turned some TypeAdapterFactory/TypeAdapter pairs inside out so that the TypeAdapter is now the inner class. This is necessary so that the factories can take parameters. Added an API to request the 'next' type adapter for a type. This allows type adapters to compose other type adapters. We're using this in two places: - where the user has excluded a type from serialization but not deserialization, we need to use the "default" deserialization but interpose null on serialization. We create a type adapter that delegates for one and returns null for the other. - similarly when a DOM type serializer is registered but no deserializer, or vice versa. This is the biggest change to the MiniGson core. For backwards compatibility, return null for the empty string. Simplify JsonSerializationContext/JsonDeserializationContext to simply call through to GSON. SerializeDefault is currently unsupported. More useful error messages when calling getAsBoolean on a JsonNull. Remove currently unused MemoryRefStack. We might need this back again, though wiring it back in will be much more difficult because we don't interject ourselves between the users' various type adapters.
2011-09-11 09:04:56 +02:00
} 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 {
Strict mode for JSON parsing, contributed by @marten-voorberg. (#2437) * Strict mode for JSON parsing (#2323) * Feat #6: Add strict flag to Gson and GsonBuilder * Test #2: Add failing tests for capitalized keywords * Feat #2: JsonReader does not read (partially) capitalized keywords if strict mode is used * Feat #3: Added implementation and tests for JSONReader not accepting specific escape sequence representing in strict mode * Test #3: Simplify test cases by removing unnecessary array * Feat #3: Improve error by including the illegal character * Feat #5: JsonReader does not allow unespaced control flow characters in strict mode * Test #5: Test unespaced control flow characters in strict mode * Feat #4: Disallow espaced newline character in strict mode * Test #4: Add tests for (dis)allowing newline character depensding on strictness * Test #5: Test case for unescaped control char in non-strict mode * Test #2: Simplify test cases * Feat #13: Change leniency API to Strictness enum in JsonReader, Gson, and GsonBuilder * Feat #15: Change JsonWriter API to also use Strictness * Test #15: Test Strictness in JsonWriter API * Doc #15: Add and update documentation for Strictness in JsonWriter API * refactor #12: Fixed typos and empty catch brackets in tests * refactor #12: Resolved importing wildcards, made some lines adhere to Google java style * #5 Add test case for unescaped control characters * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Feat #5: add new lines to make JsonReader able to detect unescaped control characters (U+0000 through U+001F) and throw exceptions. * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue * Test #11: Added two tests for testing implementation of control character handling in strict mode and moved the implementation to nextQuotedValue --------- Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * Doc #17: Add and change javadoc of public methods * Doc #17: Update JavaDoc in JsonReader and Strictness * Doc #17: Update JavaDoc in Gson and GsonBuilder * Test #34: Add tests for setting strictness through GsonBuilder * Fix: Add Fix broken test * Fix: Invalid JavaDoc in Gson.java * Doc #17: update outdated javadoc * #37: Resolve more PR feedback * Fix #37: Resolve various PR comments * Fix #37: Resolve various PR comments * Refactor #35: Refactor JsonReader#peekKeyword to reduce the amount of strictness checks (#39) * Doc #40: Update JavaDoc based on PR feedback * Doc #40: Update old RFC in GsonBuilder documentation * Doc #40: Fix formatting error in JavaDoc * Doc #40: Add tests for setting strictness and lenient to JsonReaderTest * Test #43: Changed tests to make use of assertThrows * test #43: Changed tests to make use of assertThrows as per feedback * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * Test #43: Update JsonWriterTest#testStrictnessNull to use assertThrows * test #43: Resolve PR recommendations * Test #43: Mini change to TC * Test #43: Mini change to TC --------- Co-authored-by: Marten Voorberg <martenvoorberg@gmail.com> * doc #46: Resolved comments in main PR * Feat #45: Change Gson.fromJson and Gson.toJson to be strict when the provided writer/reader is strict * Fix #45: Small type * Update gson/src/test/java/com/google/gson/stream/JsonReaderTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Update gson/src/main/java/com/google/gson/GsonBuilder.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Fix #45: Resolve various comments by Marcono1234 * Fix #45: Resolve various comments by eamonmcmanus * Strictness mode follow-up * Update Troubleshooting.md and Gson default lenient mode documentation * Always use GSON strictness when set. * Rename Strictness.DEFAULT to Strictness.LEGACY_STRICT * Update JavaDoc with new strictness functionality * Replace default with legacy strict for JsonReader javadoc * Add JSONReader test cases for U2028 and U2029 * Refactor JSONReader#peekKeyWord() based on @eamonmcmanus's suggestion * Deprecate setLenient in favor of setStrictness --------- Co-authored-by: Carl Peterson <unknown> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Strictness follow-up (#2408) * Strictness mode follow-up - Remove mentions of `null` Gson strictness; this is an implementation detail - Fix incorrect / outdated documentation - Reduce links to RFC; if there is already a link to it in a previous sentence don't link to it again - Extend and update tests - Minor punctuation changes in documentation for consistency * Deprecate `setLenient` methods * `strictness2` fixes & improvements (#2456) * Adjust ProGuard default rules and shrinking tests (#2420) * Adjust ProGuard default rules and shrinking tests * Adjust comment * Add shrinking test for class without no-args constructor; improve docs * Improve Unsafe mention in Troubleshooting Guide * Improve comment for `-if class *` * Bump com.google.guava:guava from 32.0.1-jre to 32.1.1-jre (#2444) Bumps [com.google.guava:guava](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Bump com.google.guava:guava-testlib from 32.0.1-jre to 32.1.1-jre (#2443) Bumps [com.google.guava:guava-testlib](https://github.com/google/guava) from 32.0.1-jre to 32.1.1-jre. - [Release notes](https://github.com/google/guava/releases) - [Commits](https://github.com/google/guava/commits) --- updated-dependencies: - dependency-name: com.google.guava:guava-testlib dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Support non-generic type for `TypeToken.getParameterized` for legacy reasons (#2447) This partially restores the behavior before a589ef20087b4b0f1ec3048d3ceaef1eedccd09d, except that back then for a non-generic type a bogus `TypeToken(ParameterizedType)` was created, whereas now a `TypeToken(Class)` is created instead. * Fixed Typo in GsonBuilder.java (#2449) * Make date-formatting tests less fragile with regular expressions. (#2450) * Make date-formatting tests less fragile with regular expressions. This is not great. We should really ensure that formatted dates are the same regardless of JDK version. There is code that attempts to do that but it is not really effective. So for now we fudge around the differences by using regular expressions to paper over the differences. * Temporarily add test-debugging code. * Another attempt at debugging a test failure. * Fix pattern in assertion. * Modification in test cases (#2454) * Fixed Typo in GsonBuilder.java * Suggestions on Test cases * Modified test cases using assertThrows method (JUnit) * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/GsonTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonArrayAsListTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/JsonStreamParserTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/TypeAdapterTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Update gson/src/test/java/com/google/gson/ToNumberPolicyTest.java Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> --------- Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> * Minor follow-up changes --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Éamonn McManus <emcmanus@google.com> Co-authored-by: Wonil <cwi5525@naver.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Marten <martenvoorberg@gmail.com> Co-authored-by: Gustaf Johansson <gustajoh@kth.se> Co-authored-by: gustajoh <58432871+gustajoh@users.noreply.github.com> Co-authored-by: LMC117 <2295699210@qq.com> Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: elevne <97422844+elevne@users.noreply.github.com> Co-authored-by: Wonil <cwi5525@naver.com>
2023-07-30 18:20:32 +02:00
reader.setStrictness(oldStrictness);
}
}
/**
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* 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
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* 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
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* {@link #fromJson(JsonElement, TypeToken)}.
*
* @param <T> the type of the desired object
* @param json the root of the parse tree of {@link JsonElement}s from which the object is to be
* deserialized
* @param classOfT The class of T
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* @return an object of type T from the JSON. Returns {@code null} if {@code json} is {@code null}
* or if {@code json} is empty.
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* @throws JsonSyntaxException if json is not a valid representation for an object of type
* classOfT
* @since 1.3
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* @see #fromJson(Reader, Class)
* @see #fromJson(JsonElement, TypeToken)
*/
public <T> T fromJson(JsonElement json, Class<T> classOfT) throws JsonSyntaxException {
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
T object = fromJson(json, TypeToken.get(classOfT));
return Primitives.wrap(classOfT).cast(object);
}
/**
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* 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.
*
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* <p>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 <T> the type of the desired object
* @param json the root of the parse tree of {@link JsonElement}s from which the object is to be
* deserialized
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* @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
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* @see #fromJson(Reader, Type)
* @see #fromJson(JsonElement, Class)
* @see #fromJson(JsonElement, TypeToken)
*/
Fix error prone warns (#2320) * Adds `@SuppressWarnings("NarrowingCompoundAssignment")` * Adds `@SuppressWarnings("TypeParameterUnusedInFormals")` * Adds `@SuppressWarnings("JavaUtilDate")` * Adds a limit to `String.split()` * Add `error_prone_annotations` to the `pom.xml` * Adds `@InlineMe(...)` to deprecated methods * Adds `@SuppressWarnings("ImmutableEnumChecker")` * Adds `@SuppressWarnings("ModifiedButNotUsed")` * Adds `@SuppressWarnings("MixedMutabilityReturnType")` * Removes an unused import * Adds `requires` to `module-info.java` * Adds ErrorProne `link` into `pom.xml` * Remove unused imports Removed from: - ParseBenchmark * Adds `@SuppressWarnings("EqualsGetClass")` * Excludes from `proto` just the generated code. Replaces `.*proto.*` with `.*/generated-test-sources/protobuf/.*` in such way will be excluded just the generated code and not the whole `proto` directory * Removes an unused variable Removes the `descriptor` variable because is unused. * Fixes the `BadImport` warn into `ProtosWithAnnotationsTest` * Fixes the `BadImport` warns into `ProtosWithAnnotationsTest` * Enables ErrorProne in `gson/src/test.*` Removes the `gson/src/test.*` path from the `-XepExcludedPaths` parameter of the ErrorProne plugin * Fixes `UnusedVariable` warns This commit fix all `UnusedVariable` warns given by ErrorProne in the `gson/src/test.*` path. Some field is annotated with `@Keep` that means is used by reflection. In some other case the record is annotated with `@SuppressWarnings("unused")` * Fixes `JavaUtilDate` warns This commit fix all `JavaUtilDate` warns given by ErrorProne in the `gson/src/test.*` path. Classes/Methods are annotated with `@SuppressWarnings("JavaUtilDate")` because it's not possible use differente Date API. * Fixes `EqualsGetClass` warns This commit fix all `EqualsGetClass` warns given by ErrorProne in the `gson/src/test.*` path. I have rewrite the `equals()` methods to use `instanceof` * Replaces pattern matching for instanceof with casts * Fixes `JdkObsolete` warns This commit fix all `JdkObsolete` warns given by ErrorProne in the `gson/src/test.*` path. In some cases I have replaced the obsolete JDK classes with the newest alternatives. In other cases, I have added the `@SuppressWarnings("JdkObsolete")` * Fixes `ClassCanBeStatic` warns This commit fix all `ClassCanBeStatic` warns given by ErrorProne in the `gson/src/test.*` path. I have added the `static` keyword, or I have added `@SuppressWarnings("ClassCanBeStatic")` * Fixes `UndefinedEquals` warns This commit fix all `UndefinedEquals` warns given by ErrorProne in the `gson/src/test.*` path. I have added `@SuppressWarnings("UndefinedEquals")` or fixed the asserts Note: In this commit I have also renamed a test from `testRawCollectionDeserializationNotAlllowed` to `testRawCollectionDeserializationNotAllowed` * Fixes `GetClassOnEnum` warns This commit fix all `GetClassOnEnum` warns given by ErrorProne in the `gson/src/test.*` path. I have replaced the `.getClass()` with `.getDeclaringClass()` * Fixes `ImmutableEnumChecker` warns This commit fix all `ImmutableEnumChecker` warns given by ErrorProne in the `gson/src/test.*` path. I have added the `final` keyword, or I have added the `@SuppressWarnings("ImmutableEnumChecker")` annotation * Fixes `StaticAssignmentOfThrowable` warns This commit fix all `StaticAssignmentOfThrowable` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `AssertionFailureIgnored` warns This commit fix all `AssertionFailureIgnored` warns given by ErrorProne in the `gson/src/test.*` path. I have added the `@SuppressWarnings("AssertionFailureIgnored")` annotation * Fixes `ModifiedButNotUsed` warns This commit fix all `ModifiedButNotUsed` warns given by ErrorProne in the `gson/src/test.*` path. I have added the `@SuppressWarnings("ModifiedButNotUsed")` annotation * Fixes `MissingSummary` warns This commit fix all `MissingSummary` warns given by ErrorProne in the `gson/src/test.*` path. I have remove the Javadoc `@author` * Fixes `FloatingPointLiteralPrecision` warns This commit fix all `FloatingPointLiteralPrecision` warns given by ErrorProne in the `gson/src/test.*` path. I have added the `@SuppressWarnings("FloatingPointLiteralPrecision")` annotation * Fixes `StringSplitter` warns This commit fix all `StringSplitter` warns given by ErrorProne in the `gson/src/test.*` path. I have replaced the `String.split(...)` with `Splitter` * Fixes `EmptyCatch` warns This commit fix all `EmptyCatch` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `UnicodeEscape` warns This commit fix all `UnicodeEscape` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `EmptyBlockTag` warns This commit fix all `EmptyBlockTag` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `LongFloatConversion` warns This commit fix all `LongFloatConversion` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `LongDoubleConversion` warns This commit fix all `LongDoubleConversion` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `TruthAssertExpected` warns This commit fix all `TruthAssertExpected` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `UnusedMethod` warns This commit fix all `UnusedMethod` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `UnusedTypeParameter` warns This commit fix all `UnusedTypeParameter` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `CatchFail` warns This commit fix all `CatchFail` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `MathAbsoluteNegative` warns This commit fix all `MathAbsoluteNegative` warns given by ErrorProne in the `gson/src/test.*` path. * Fixes `LoopOverCharArray` warns This commit fix all `LoopOverCharArray` warns given by ErrorProne in the `gson/src/test.*` path. `toCharArray` allocates a new array, using `charAt` is more efficient * Fixes `HidingField` warns This commit fix all `HidingField` warns given by ErrorProne in the `gson/src/test.*` path. * Implements code review feedback * Implements code review feedback This commit implements some other code review feedback * Enable ErrorProne in `extra` Thi commit removes the `.*extras/src/test.*` path from the `-XepExcludedPaths` parameter of ErrorProne. * Fix the `JavaUtilDate` warns This commit fix all `JavaUtilDate` warns given by ErrorProne in the `extras/src/test.*` path. * Implements code review feedback * Removes redundant new-line * Implements code review feedback * Adds `JDK11` to run test with `--release 11` * Revert "Adds `JDK11` to run test with `--release 11`" This reverts commit a7cca386098ae847a10a31c09c3ab9b11eee5920.
2023-03-01 23:23:27 +01:00
@SuppressWarnings({"unchecked", "TypeParameterUnusedInFormals"})
public <T> T fromJson(JsonElement json, Type typeOfT) throws JsonSyntaxException {
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
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 <T> the type of the desired object
* @param json the root of the parse tree of {@link JsonElement}s from which the object is to be
* deserialized
* @param typeOfT The specific genericized type of src. You should create an anonymous subclass of
* {@code TypeToken} with the specific generic type arguments. For example, to get the type
* for {@code Collection<Foo>}, you should use:
* <pre>
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* new TypeToken&lt;Collection&lt;Foo&gt;&gt;(){}
* </pre>
*
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* @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
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
* @see #fromJson(Reader, TypeToken)
* @see #fromJson(JsonElement, Class)
* @since 2.10
*/
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
public <T> T fromJson(JsonElement json, TypeToken<T> typeOfT) throws JsonSyntaxException {
if (json == null) {
return null;
}
Add Gson.fromJson(..., TypeToken) overloads (#1700) * Add Gson.fromJson(..., TypeToken) overloads Previously only Gson.fromJson(..., Type) existed which is however not type-safe since the generic type parameter T used for the return type is not bound. Since these methods are often used in the form gson.fromJson(..., new TypeToken<...>(){}.getType()) this commit now adds overloads which accept a TypeToken and are therefore more type-safe. Additional changes: - Fixed some grammar mistakes - Added javadoc @see tags - Consistently write "JSON" in uppercase - More precise placement of @SuppressWarnings("unchecked") * Add to Gson.fromJson javadoc that JSON is fully consumed The newly added documentation deliberately does not state which exception is thrown because Gson.assertFullConsumption could throw either a JsonIOException or a JsonSyntaxException. * Remove unnecessary wrapping and unwrapping as TypeToken in Gson.fromJson Since the actual implementation of Gson.fromJson is TypeToken based, the TypeToken variant overloads are now the "main" implementation and the other overloads delegate to them. Previously the Type variant overloads were the "main" implementation which caused `TypeToken.getType()` followed by `TypeToken.get(...)` when the TypeToken variant overloads were used. * Trim source code whitespaces * Fix Gson.fromJson(JsonReader, Class) not casting read Object To be consistent with the other Gson.fromJson(..., Class) overloads the method should cast the result. * Replace User Guide link in Gson documentation * Remove more references to fromJson(..., Type) * Extend documentation for fromJson(JsonReader, ...) * Replace some TypeToken.getType() usages * Address feedback; improve documentation * Remove fromJson(JsonReader, Class) again As noticed during review adding this method is source incompatible.
2022-09-19 15:47:11 +02:00
return fromJson(new JsonTreeReader(json), typeOfT);
2008-09-01 05:13:32 +02:00
}
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.
*
* <p><b>Important:</b> Setting the delegate adapter is not thread-safe; instances of {@code
* FutureTypeAdapter} must only be published to other threads after the delegate has been set.
*
* @see Gson#threadLocalAdapterResults
*/
static class FutureTypeAdapter<T> extends SerializationDelegatingTypeAdapter<T> {
private TypeAdapter<T> delegate = null;
public void setDelegate(TypeAdapter<T> typeAdapter) {
if (delegate != null) {
throw new AssertionError("Delegate is already set");
}
delegate = typeAdapter;
}
private TypeAdapter<T> delegate() {
TypeAdapter<T> 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<T> getSerializationDelegate() {
return delegate();
}
@Override
public T read(JsonReader in) throws IOException {
return delegate().read(in);
}
2011-12-03 20:46:25 +01:00
@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
+ "}";
}
2008-09-01 05:13:32 +02:00
}