Replace custom user guide header anchors (#2289)

Looks like GitHub does not support them anymore.
This commit is contained in:
Marcono1234 2022-12-18 00:28:14 +01:00 committed by GitHub
parent 6c12ded70d
commit a19d53f535
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 76 additions and 76 deletions

View File

@ -11,7 +11,7 @@ This guide describes how to troubleshoot common issues when using Gson.
**Solution:** Make sure your code adheres to the following:
- Avoid raw types: Instead of calling `fromJson(..., List.class)`, create for example a `TypeToken<List<MyClass>>`.
See the [user guide](UserGuide.md#TOC-Collections-Examples) for more information.
See the [user guide](UserGuide.md#collections-examples) for more information.
- When using `TypeToken` prefer the `Gson.fromJson` overloads with `TypeToken` parameter such as [`fromJson(Reader, TypeToken)`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/Gson.html#fromJson(java.io.Reader,com.google.gson.reflect.TypeToken)).
The overloads with `Type` parameter do not provide any type-safety guarantees.
- When using `TypeToken` make sure you don't capture a type variable. For example avoid something like `new TypeToken<List<T>>()` (where `T` is a type variable). Due to Java type erasure the actual type of `T` is not available at runtime. Refactor your code to pass around `TypeToken` instances or use [`TypeToken.getParameterized(...)`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/reflect/TypeToken.html#getParameterized(java.lang.reflect.Type,java.lang.reflect.Type...)), for example `TypeToken.getParameterized(List.class, elementClass)`.
@ -101,7 +101,7 @@ Notes:
**Reason:** The `Map` key type is 'complex' and you have not configured the `GsonBuilder` properly
**Solution:** Use [`GsonBuilder.enableComplexMapKeySerialization()`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/GsonBuilder.html#enableComplexMapKeySerialization()). See also the [user guide](UserGuide.md#TOC-Maps-Examples) for more information.
**Solution:** Use [`GsonBuilder.enableComplexMapKeySerialization()`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/GsonBuilder.html#enableComplexMapKeySerialization()). See also the [user guide](UserGuide.md#maps-examples) for more information.
## Parsing JSON fails with `MalformedJsonException`

View File

@ -1,48 +1,48 @@
# Gson User Guide
1. [Overview](#TOC-Overview)
2. [Goals for Gson](#TOC-Goals-for-Gson)
3. [Gson Performance and Scalability](#TOC-Gson-Performance-and-Scalability)
4. [Gson Users](#TOC-Gson-Users)
5. [Using Gson](#TOC-Using-Gson)
* [Using Gson with Gradle/Android](#TOC-Gson-With-Gradle)
* [Using Gson with Maven](#TOC-Gson-With-Maven)
* [Primitives Examples](#TOC-Primitives-Examples)
* [Object Examples](#TOC-Object-Examples)
* [Finer Points with Objects](#TOC-Finer-Points-with-Objects)
* [Nested Classes (including Inner Classes)](#TOC-Nested-Classes-including-Inner-Classes-)
* [Array Examples](#TOC-Array-Examples)
* [Collections Examples](#TOC-Collections-Examples)
* [Collections Limitations](#TOC-Collections-Limitations)
* [Maps Examples](#TOC-Maps-Examples)
* [Serializing and Deserializing Generic Types](#TOC-Serializing-and-Deserializing-Generic-Types)
* [Serializing and Deserializing Collection with Objects of Arbitrary Types](#TOC-Serializing-and-Deserializing-Collection-with-Objects-of-Arbitrary-Types)
* [Built-in Serializers and Deserializers](#TOC-Built-in-Serializers-and-Deserializers)
* [Custom Serialization and Deserialization](#TOC-Custom-Serialization-and-Deserialization)
* [Writing a Serializer](#TOC-Writing-a-Serializer)
* [Writing a Deserializer](#TOC-Writing-a-Deserializer)
* [Writing an Instance Creator](#TOC-Writing-an-Instance-Creator)
* [InstanceCreator for a Parameterized Type](#TOC-InstanceCreator-for-a-Parameterized-Type)
* [Compact Vs. Pretty Printing for JSON Output Format](#TOC-Compact-Vs.-Pretty-Printing-for-JSON-Output-Format)
* [Null Object Support](#TOC-Null-Object-Support)
* [Versioning Support](#TOC-Versioning-Support)
* [Excluding Fields From Serialization and Deserialization](#TOC-Excluding-Fields-From-Serialization-and-Deserialization)
* [Java Modifier Exclusion](#TOC-Java-Modifier-Exclusion)
* [Gson's `@Expose`](#TOC-Gson-s-Expose)
* [User Defined Exclusion Strategies](#TOC-User-Defined-Exclusion-Strategies)
* [JSON Field Naming Support](#TOC-JSON-Field-Naming-Support)
* [Sharing State Across Custom Serializers and Deserializers](#TOC-Sharing-State-Across-Custom-Serializers-and-Deserializers)
* [Streaming](#TOC-Streaming)
6. [Issues in Designing Gson](#TOC-Issues-in-Designing-Gson)
7. [Future Enhancements to Gson](#TOC-Future-Enhancements-to-Gson)
1. [Overview](#overview)
2. [Goals for Gson](#goals-for-gson)
3. [Gson Performance and Scalability](#gson-performance-and-scalability)
4. [Gson Users](#gson-users)
5. [Using Gson](#using-gson)
* [Using Gson with Gradle/Android](#using-gson-with-gradleandroid)
* [Using Gson with Maven](#using-gson-with-maven)
* [Primitives Examples](#primitives-examples)
* [Object Examples](#object-examples)
* [Finer Points with Objects](#finer-points-with-objects)
* [Nested Classes (including Inner Classes)](#nested-classes-including-inner-classes)
* [Array Examples](#array-examples)
* [Collections Examples](#collections-examples)
* [Collections Limitations](#collections-limitations)
* [Maps Examples](#maps-examples)
* [Serializing and Deserializing Generic Types](#serializing-and-deserializing-generic-types)
* [Serializing and Deserializing Collection with Objects of Arbitrary Types](#serializing-and-deserializing-collection-with-objects-of-arbitrary-types)
* [Built-in Serializers and Deserializers](#built-in-serializers-and-deserializers)
* [Custom Serialization and Deserialization](#custom-serialization-and-deserialization)
* [Writing a Serializer](#writing-a-serializer)
* [Writing a Deserializer](#writing-a-deserializer)
* [Writing an Instance Creator](#writing-an-instance-creator)
* [InstanceCreator for a Parameterized Type](#instancecreator-for-a-parameterized-type)
* [Compact Vs. Pretty Printing for JSON Output Format](#compact-vs-pretty-printing-for-json-output-format)
* [Null Object Support](#null-object-support)
* [Versioning Support](#versioning-support)
* [Excluding Fields From Serialization and Deserialization](#excluding-fields-from-serialization-and-deserialization)
* [Java Modifier Exclusion](#java-modifier-exclusion)
* [Gson's `@Expose`](#gsons-expose)
* [User Defined Exclusion Strategies](#user-defined-exclusion-strategies)
* [JSON Field Naming Support](#json-field-naming-support)
* [Sharing State Across Custom Serializers and Deserializers](#sharing-state-across-custom-serializers-and-deserializers)
* [Streaming](#streaming)
6. [Issues in Designing Gson](#issues-in-designing-gson)
7. [Future Enhancements to Gson](#future-enhancements-to-gson)
## <a name="TOC-Overview"></a>Overview
## Overview
Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.
Gson can work with arbitrary Java objects including pre-existing objects that you do not have source code of.
## <a name="TOC-Goals-for-Gson"></a>Goals for Gson
## Goals for Gson
* Provide easy to use mechanisms like `toString()` and constructor (factory method) to convert Java to JSON and vice-versa
* Allow pre-existing unmodifiable objects to be converted to and from JSON
@ -50,7 +50,7 @@ Gson can work with arbitrary Java objects including pre-existing objects that yo
* Support arbitrarily complex objects
* Generate compact and readable JSON output
## <a name="TOC-Gson-Performance-and-Scalability"></a>Gson Performance and Scalability
## Gson Performance and Scalability
Here are some metrics that we obtained on a desktop (dual opteron, 8GB RAM, 64-bit Ubuntu) running lots of other things along-with the tests. You can rerun these tests by using the class [`PerformanceTest`](gson/src/test/java/com/google/gson/metrics/PerformanceTest.java).
@ -62,17 +62,17 @@ Here are some metrics that we obtained on a desktop (dual opteron, 8GB RAM, 64-b
Note: Delete the `disabled_` prefix to run these tests. We use this prefix to prevent running these tests every time we run JUnit tests.
## <a name="TOC-Gson-Users"></a>Gson Users
## Gson Users
Gson was originally created for use inside Google where it is currently used in a number of projects. It is now used by a number of public projects and companies.
## <a name="TOC-Using-Gson"></a>Using Gson
## Using Gson
The primary class to use is [`Gson`](gson/src/main/java/com/google/gson/Gson.java) which you can just create by calling `new Gson()`. There is also a class [`GsonBuilder`](gson/src/main/java/com/google/gson/GsonBuilder.java) available that can be used to create a Gson instance with various settings like version control and so on.
The Gson instance does not maintain any state while invoking JSON operations. So, you are free to reuse the same object for multiple JSON serialization and deserialization operations.
## <a name="TOC-Gson-With-Gradle"></a>Using Gson with Gradle/Android
## Using Gson with Gradle/Android
```gradle
dependencies {
@ -80,7 +80,7 @@ dependencies {
}
```
## <a name="TOC-Gson-With-Maven"></a>Using Gson with Maven
## Using Gson with Maven
To use Gson with Maven2/3, you can use the Gson version available in Maven Central by adding the following dependency:
@ -98,7 +98,7 @@ To use Gson with Maven2/3, you can use the Gson version available in Maven Centr
That is it, now your Maven project is Gson enabled.
### <a name="TOC-Primitives-Examples"></a>Primitives Examples
### Primitives Examples
```java
// Serialization
@ -118,7 +118,7 @@ String str = gson.fromJson("\"abc\"", String.class);
String[] anotherStr = gson.fromJson("[\"abc\"]", String[].class);
```
### <a name="TOC-Object-Examples"></a>Object Examples
### Object Examples
```java
class BagOfPrimitives {
@ -146,7 +146,7 @@ BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
// ==> obj2 is just like obj
```
#### <a name="TOC-Finer-Points-with-Objects"></a>**Finer Points with Objects**
#### **Finer Points with Objects**
* It is perfectly fine (and recommended) to use private fields.
* There is no need to use any annotations to indicate a field is to be included for serialization and deserialization. All fields in the current class (and from all super classes) are included by default.
@ -158,7 +158,7 @@ BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
* Fields corresponding to the outer classes in inner classes are ignored and not included in serialization or deserialization.
* Anonymous and local classes are excluded. They will be serialized as JSON `null` and when deserialized their JSON value is ignored and `null` is returned. Convert the classes to `static` nested classes to enable serialization and deserialization for them.
### <a name="TOC-Nested-Classes-including-Inner-Classes-"></a>Nested Classes (including Inner Classes)
### Nested Classes (including Inner Classes)
Gson can serialize static nested classes quite easily.
@ -197,7 +197,7 @@ public class InstanceCreatorForB implements InstanceCreator<A.B> {
The above is possible, but not recommended.
### <a name="TOC-Array-Examples"></a>Array Examples
### Array Examples
```java
Gson gson = new Gson();
@ -215,7 +215,7 @@ int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class);
We also support multi-dimensional arrays, with arbitrarily complex element types.
### <a name="TOC-Collections-Examples"></a>Collections Examples
### Collections Examples
```java
Gson gson = new Gson();
@ -235,12 +235,12 @@ Collection<Integer> ints2 = gson.fromJson(json, collectionType);
Fairly hideous: note how we define the type of collection.
Unfortunately, there is no way to get around this in Java.
#### <a name="TOC-Collections-Limitations"></a>Collections Limitations
#### Collections Limitations
Gson can serialize collection of arbitrary objects but can not deserialize from it, because there is no way for the user to indicate the type of the resulting object. Instead, while deserializing, the Collection must be of a specific, generic type.
This makes sense, and is rarely a problem when following good Java coding practices.
### <a name="TOC-Maps-Examples"></a>Maps Examples
### Maps Examples
Gson by default serializes any `java.util.Map` implementation as a JSON object. Because JSON objects only support strings as member names, Gson converts the Map keys to strings by calling `toString()` on them, and using `"null"` for `null` keys:
@ -309,7 +309,7 @@ String json = gson.toJson(stringMap); // json is {"key":"value"}
Note that when deserializing enums as Map keys, if Gson is unable to find an enum constant with a matching `name()` value respectively `@SerializedName` annotation, it falls back to looking up the enum constant by its `toString()` value. This is to work around the issue described above, but only applies to enum constants.
### <a name="TOC-Serializing-and-Deserializing-Generic-Types"></a>Serializing and Deserializing Generic Types
### Serializing and Deserializing Generic Types
When you call `toJson(obj)`, Gson calls `obj.getClass()` to get information on the fields to serialize. Similarly, you can typically pass `MyClass.class` object in the `fromJson(json, MyClass.class)` method. This works fine if the object is a non-generic type. However, if the object is of a generic type, then the Generic type information is lost because of Java Type Erasure. Here is an example illustrating the point:
@ -337,7 +337,7 @@ gson.fromJson(json, fooType);
The idiom used to get `fooType` actually defines an anonymous local inner class containing a method `getType()` that returns the fully parameterized type.
### <a name="TOC-Serializing-and-Deserializing-Collection-with-Objects-of-Arbitrary-Types"></a>Serializing and Deserializing Collection with Objects of Arbitrary Types
### Serializing and Deserializing Collection with Objects of Arbitrary Types
Sometimes you are dealing with JSON array that contains mixed types. For example:
`['hello',5,{name:'GREETINGS',source:'guest'}]`
@ -376,7 +376,7 @@ However, deserialization with `fromJson(json, Collection.class)` will not work s
This approach is practical only if the array appears as a top-level element or if you can change the field type holding the collection to be of type `Collection<MyCollectionMemberType>`.
### <a name="TOC-Built-in-Serializers-and-Deserializers"></a>Built-in Serializers and Deserializers
### Built-in Serializers and Deserializers
Gson has built-in serializers and deserializers for commonly used classes whose default representation may be inappropriate, for instance
@ -387,7 +387,7 @@ For many more, see the internal class [`TypeAdapters`](gson/src/main/java/com/go
You can also find source code for some commonly used classes such as JodaTime at [this page](https://sites.google.com/site/gson/gson-type-adapters-for-common-classes-1).
### <a name="TOC-Custom-Serialization-and-Deserialization"></a>Custom Serialization and Deserialization
### Custom Serialization and Deserialization
Sometimes default representation is not what you want. This is often the case when dealing with library classes (DateTime, etc).
Gson allows you to register your own custom serializers and deserializers. This is done by defining two parts:
@ -407,7 +407,7 @@ gson.registerTypeAdapter(MyType.class, new MyInstanceCreator());
`registerTypeAdapter` call checks if the type adapter implements more than one of these interfaces and register it for all of them.
#### <a name="TOC-Writing-a-Serializer"></a>Writing a Serializer
#### Writing a Serializer
Here is an example of how to write a custom serializer for JodaTime `DateTime` class.
@ -421,7 +421,7 @@ private class DateTimeSerializer implements JsonSerializer<DateTime> {
Gson calls `serialize()` when it runs into a `DateTime` object during serialization.
#### <a name="TOC-Writing-a-Deserializer"></a>Writing a Deserializer
#### Writing a Deserializer
Here is an example of how to write a custom deserializer for JodaTime DateTime class.
@ -449,7 +449,7 @@ Often you want to register a single handler for all generic types corresponding
Gson supports registering a single handler for this. You can also register a specific handler for a specific generic type (say `Id<RequiresSpecialHandling>` needed special handling).
The `Type` parameter for the `toJson()` and `fromJson()` contains the generic type information to help you write a single handler for all generic types corresponding to the same raw type.
### <a name="TOC-Writing-an-Instance-Creator"></a>Writing an Instance Creator
### Writing an Instance Creator
While deserializing an Object, Gson needs to create a default instance of the class.
Well-behaved classes that are meant for serialization and deserialization should have a no-argument constructor.
@ -473,7 +473,7 @@ Type could be of a corresponding generic type
* Very useful to invoke constructors which need specific generic type information
* For example, if the `Id` class stores the class for which the Id is being created
#### <a name="TOC-InstanceCreator-for-a-Parameterized-Type"></a>InstanceCreator for a Parameterized Type
#### InstanceCreator for a Parameterized Type
Sometimes the type that you are trying to instantiate is a parameterized type. Generally, this is not a problem since the actual instance is of raw type. Here is an example:
@ -513,9 +513,9 @@ class IdInstanceCreator implements InstanceCreator<Id<?>> {
In the above example, an instance of the Id class can not be created without actually passing in the actual type for the parameterized type. We solve this problem by using the passed method parameter, `type`. The `type` object in this case is the Java parameterized type representation of `Id<Foo>` where the actual instance should be bound to `Id<Foo>`. Since `Id` class has just one parameterized type parameter, `T`, we use the zeroth element of the type array returned by `getActualTypeArgument()` which will hold `Foo.class` in this case.
### <a name="TOC-Compact-Vs.-Pretty-Printing-for-JSON-Output-Format"></a>Compact Vs. Pretty Printing for JSON Output Format
### Compact Vs. Pretty Printing for JSON Output Format
The default JSON output that is provided by Gson is a compact JSON format. This means that there will not be any whitespace in the output JSON structure. Therefore, there will be no whitespace between field names and its value, object fields, and objects within arrays in the JSON output. As well, "null" fields will be ignored in the output (NOTE: null values will still be included in collections/arrays of objects). See the [Null Object Support](#TOC-Null-Object-Support) section for information on configure Gson to output all null values.
The default JSON output that is provided by Gson is a compact JSON format. This means that there will not be any whitespace in the output JSON structure. Therefore, there will be no whitespace between field names and its value, object fields, and objects within arrays in the JSON output. As well, "null" fields will be ignored in the output (NOTE: null values will still be included in collections/arrays of objects). See the [Null Object Support](#null-object-support) section for information on configure Gson to output all null values.
If you would like to use the Pretty Print feature, you must configure your `Gson` instance using the `GsonBuilder`. The `JsonFormatter` is not exposed through our public API, so the client is unable to configure the default print settings/margins for the JSON output. For now, we only provide a default `JsonPrintFormatter` that has default line length of 80 character, 2 character indentation, and 4 character right margin.
@ -526,7 +526,7 @@ Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonOutput = gson.toJson(someObject);
```
### <a name="TOC-Null-Object-Support"></a>Null Object Support
### Null Object Support
The default behaviour that is implemented in Gson is that `null` object fields are ignored. This allows for a more compact output format; however, the client must define a default value for these fields as the JSON format is converted back into its Java form.
@ -566,12 +566,12 @@ System.out.println(json);
The output is:
```
```json
{"s":null,"i":5}
null
```
### <a name="TOC-Versioning-Support"></a>Versioning Support
### Versioning Support
Multiple versions of the same object can be maintained by using [@Since](gson/src/main/java/com/google/gson/annotations/Since.java) annotation. This annotation can be used on Classes, Fields and, in a future release, Methods. In order to leverage this feature, you must configure your `Gson` instance to ignore any field/object that is greater than some version number. If no version is set on the `Gson` instance then it will serialize and deserialize all fields and classes regardless of the version.
@ -601,17 +601,17 @@ System.out.println(jsonOutput);
The output is:
```
```json
{"newField":"new","field":"old"}
{"newerField":"newer","newField":"new","field":"old"}
```
### <a name="TOC-Excluding-Fields-From-Serialization-and-Deserialization"></a>Excluding Fields From Serialization and Deserialization
### Excluding Fields From Serialization and Deserialization
Gson supports numerous mechanisms for excluding top-level classes, fields and field types. Below are pluggable mechanisms that allow field and class exclusion. If none of the below mechanisms satisfy your needs then you can always use [custom serializers and deserializers](#TOC-Custom-Serialization-and-Deserialization).
Gson supports numerous mechanisms for excluding top-level classes, fields and field types. Below are pluggable mechanisms that allow field and class exclusion. If none of the below mechanisms satisfy your needs then you can always use [custom serializers and deserializers](#custom-serialization-and-deserialization).
#### <a name="TOC-Java-Modifier-Exclusion"></a>Java Modifier Exclusion
#### Java Modifier Exclusion
By default, if you mark a field as `transient`, it will be excluded. As well, if a field is marked as `static` then by default it will be excluded. If you want to include some transient fields then you can do the following:
@ -630,11 +630,11 @@ Gson gson = new GsonBuilder()
.create();
```
#### <a name="TOC-Gson-s-Expose"></a>Gson's `@Expose`
#### Gson's `@Expose`
This feature provides a way where you can mark certain fields of your objects to be excluded for consideration for serialization and deserialization to JSON. To use this annotation, you must create Gson by using `new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()`. The Gson instance created will exclude all fields in a class that are not marked with `@Expose` annotation.
#### <a name="TOC-User-Defined-Exclusion-Strategies"></a>User Defined Exclusion Strategies
#### User Defined Exclusion Strategies
If the above mechanisms for excluding fields and class type do not work for you then you can always write your own exclusion strategy and plug it into Gson. See the [`ExclusionStrategy`](https://javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/ExclusionStrategy.html) JavaDoc for more information.
@ -693,7 +693,7 @@ The output is:
{"longField":1234}
```
### <a name="TOC-JSON-Field-Naming-Support"></a>JSON Field Naming Support
### JSON Field Naming Support
Gson supports some pre-defined field naming policies to convert the standard Java field names (i.e., camel cased names starting with lower case --- `sampleFieldNameInJava`) to a JSON field name (i.e., `sample_field_name_in_java` or `SampleFieldNameInJava`). See the [FieldNamingPolicy](https://javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/FieldNamingPolicy.html) class for information on the pre-defined naming policies.
@ -726,7 +726,7 @@ The output is:
If you have a need for custom naming policy ([see this discussion](https://groups.google.com/group/google-gson/browse_thread/thread/cb441a2d717f6892)), you can use the [@SerializedName](https://javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/annotations/SerializedName.html) annotation.
### <a name="TOC-Sharing-State-Across-Custom-Serializers-and-Deserializers"></a>Sharing State Across Custom Serializers and Deserializers
### Sharing State Across Custom Serializers and Deserializers
Sometimes you need to share state across custom serializers/deserializers ([see this discussion](https://groups.google.com/group/google-gson/browse_thread/thread/2850010691ea09fb)). You can use the following three strategies to accomplish this:
@ -736,14 +736,14 @@ Sometimes you need to share state across custom serializers/deserializers ([see
1 and 2 are not thread-safe options, but 3 is.
### <a name="TOC-Streaming"></a>Streaming
### Streaming
In addition Gson's object model and data binding, you can use Gson to read from and write to a [stream](https://sites.google.com/site/gson/streaming). You can also combine streaming and object model access to get the best of both approaches.
## <a name="TOC-Issues-in-Designing-Gson"></a>Issues in Designing Gson
## Issues in Designing Gson
See the [Gson design document](GsonDesignDocument.md "Gson design document") for a discussion of issues we faced while designing Gson. It also include a comparison of Gson with other Java libraries that can be used for JSON conversion.
## <a name="TOC-Future-Enhancements-to-Gson"></a>Future Enhancements to Gson
## Future Enhancements to Gson
For the latest list of proposed enhancements or if you'd like to suggest new ones, see the [Issues section](https://github.com/google/gson/issues) under the project website.