Gson is a complete tutorial for realizing the mutual conversion between Java objects and JSON format objects

Gson is a Java library used to realize the mutual conversion between JSON and Java objects. Gson is a hosted https://github.com/google/gson Open source projects.

The main class in gson is gson. You can also use class gsonbuilder to set some options while creating gson objects. The gson object will not save any state when processing JSON, so the user can easily serialize and deserialize the same gson object multiple times.

Example: basic usage

Example: conversion between object and JSON

Define bagofprimititives class:

Serialized as JSON:

Do not serialize objects with circular references, otherwise infinite recursion will result.

Deserialization:

Some details when working with objects:

Handling of nested classes (including inner classes)

Gson can easily serialize nested classes and can deserialize static nested classes. Gson cannot automatically deserialize a pure inner class because its parameterless constructor needs to reference the object containing it (that is, the instance of the outer class). To deserialize a static class, you can staticize the inner class or provide a custom instance creator. Here is an example:

Class B above cannot be serialized by gson. Since class B is a (non static) inner class, gson cannot deserialize {"B": "ABC"} into an instance of class B. if B is declared as static class B, gson can deserialize this string.

Another solution is to write an instance creator for B:

This method is feasible, but it is not recommended. (the translator said he didn't understand the instance creator and didn't know how to use it)

Example: array

Gson also supports multidimensional arrays with complex data types.

Example: Collection

Limitations when processing Collections:

Serialize / deserialize generics

When tojson (obj) is used, gson calls obj GetClass () gets the field information for use in serialization. Similarly, the object MyClass Class is passed as a parameter to the fromjason (JSON, MyClass. Class) method, which can be used when the object is not generic. However, when the object is a generic type object, the generic type information will be lost due to the type erase mechanism in Java. The following example will illustrate this:

The above code interprets value as a bar type because gson calls foo GetClass () gets the class information, but this method returns an original class, foo class。 This means that gson cannot know that this is an object of type foo < bar >.

To solve this problem, you can specify the correct parameterized types for your generics. You can use the typetoken class to:

Footype actually defines an anonymous inner class that contains a GetType () method that returns all parameterized types.

Serialize / deserialize a collection of objects of any type

Sometimes the JSON processed contains mixed types, such as:

The corresponding set should be:

The event class is defined as follows:

Through gson, you can serialize collections without doing anything special: tojson (Collection) will output satisfactory results.

However, deserialization through from JSON (JSON, collection. Class) is not possible because gson cannot correspond the content in JSON to the type. Gson requires you to provide a general version of the collection type in fromjason. You have three choices:

Scheme 1: use the API of gson parser (low-level stream parser or DOM parser jsonparser) to parse array elements, and then use gson. Fromjason() to process each array element. This is the preferred solution. Scheme 2: collection Class registers a type adapter to map the elements in the array to the appropriate object. The disadvantage of this method is that it will make it inconvenient for you to deal with other collection types. Scheme 3: register a type adapter for mycollectionmembertype and use collection < mycollectionmembertype > in fromjason. This method is feasible only when the array looks like an advanced element or you can change the field type to collection < mycollectionmembertype >. Built in serializer / deserializer

Gson provides a serializer / deserializer for classes that are commonly used but whose default representation may not be appropriate. Here is a list of these classes:

Custom serialization / deserialization

Sometimes, the default implementation of gson is not what you want, which is common when dealing with some class libraries (such as datetime).

Gson allows you to register custom serializers / deserializers. To do this, you need to implement the following parts:

JSON serializer: you need to customize the serialization for an object. JSON deserializer: you need to customize the deserialization class creator for a type: if there is a parameterless constructor or a deserializer has been registered, you don't need it.

Registertypeadapter checks whether the type adapter implements multiple interfaces and registers the type adapter for these interfaces.

Write a serializer

The following is an example of a custom serializer for datetime:

Gson calls tojson() when serializing datetime instances.

Write a deserializer

The following example shows how to write a deserializer of datetime class:

When gson needs to deserialize a JSON string into a datetime object, it will call fromjason().

For serializers / deserializers, note:

Write an instance Creator

When deserializing an object, gson needs to create an instance of the class. A class that performs well in serialization / deserialization means that the class has a parameterless constructor. Usually, when dealing with a class without a parameterless constructor in the class library, you need to use the instance creator.

Instance creator example:

Instance creator for parameterized types

Sometimes the type to be instantiated is a parameterized type. In general, since the real instance is a primitive type, this is not a problem. Here is an example:

However, sometimes you need to create instances based on real parameterized types. In this case, you can pass the type parameter to the createinstance method. Here is an example:

In the above example, if the real type is not passed to the parameterized type, the instance of ID class cannot be created. We can solve this problem by passing the parameter type to the method. Here, the type object can be regarded as the representation of Java parameterized type with ID < foo >, and the corresponding instance should be bound to ID < foo >. Since the class ID has only one parameter t of parameterized type, we use the 0th element of the type array returned by getactualtypeargument(), which is foo. In this example class。

Compact output vs beautiful output

The default output of JSON in gson is compact JSON format. That is, there is no extra white space in JSON. Therefore, there is no blank space between field names and field values, between fields, and between array elements in the output of JSON. In addition, null fields are not output (Note: null is reserved in collection and array objects).

If you want to output more beautiful, you need to use gsonbuilder to configure the instance of gson. The jsonformatter does not exist in the public API, so the client cannot configure the default output settings. Now we only provide the jsonprintformatter. By default, each line is 80 characters, the indentation is 2 characters, and the right margin is 4 characters.

The following example shows how to make the gson instance use the jsonprintformatter instead of the default jsoncompactformatter.

Empty object

In the default implementation of gson, null objects are ignored. This makes the output format (which can be regarded as the result of serialization) more compact; however, the client must define a default value for it so that JSON can be deserialized normally.

If you want the gson instance to be serializable to null, you can:

Note that when serializing null, a jsonnull element is added to the jsonelement structure. Therefore, we can use this object (gson) in a custom serializer / deserializer.

Here is an example:

Output:

Version support

You can use the @ since annotation to maintain multiple versions of the same object. This annotation can be used on classes and fields, and will be supported on Methods in the future. To use this feature, you need to configure the gson instance to ignore fields and objects larger than a version number. If the version is not set in the gson object, all fields and classes will be used during serialization / deserialization.

Output:

Exclude fields from serialization / deserialization

Gson supports many methods to divide classes, fields and field types. If the following method cannot meet your needs, you can use the method of custom serializer / deserializer.

1.Java Modifier Exclusion

By default, if a field is declared transient, it will be excluded. In addition, if a field is declared as static, it will also be excluded by default. If you want to include some fields declared transient, you can do this:

Note that you can use any number of modifier constants in the excludefieldswithmodifiers method. For example:

2. Use the @ expose field to exclude

This feature allows you to mark specific fields in the class so that they are not excluded / excluded in serialization / deserialization. To use this annotation, you should use new gsonbuilder() excludeFieldsWithoutExposeAnnotation(). Create() creates the gson. The gson instance will exclude all fields in the class that are not marked by @ expose.

3. User defined exclusion policy

If the above exclusion method cannot meet the requirements, you can also customize your own exclusion strategy. For more information, please refer to the exclusionstrategy Javadoc.

The following example shows how to exclude the fields marked with @ foo, the top-level type of string class or the declared field type:

Output:

JSON field naming support

Some predefined field naming strategies of gson can convert the standard Java field name (i.e. hump naming method, such as samplefieldnameinjava) into a field name of JSON (i.e. sample_field_name_in_java or samplefieldnameinjava). For more information, please refer to fieldnaming policy.

Gson also has a label based strategy that allows the client to customize the name of the field. Under this strategy, if an illegal field name is provided as the annotation value, it will cause gson to throw a runtime exception.

The following example shows how to use these two gson naming strategies:

Output:

If you want to customize the name, you can use the @ serializedname annotation.

Share state between serializer and deserializer

Sometimes you need to share state between serializer and deserializer. You can use the following three methods to achieve this goal:

The first two methods are not thread safe, and the third is.

Gson parsing null error solution gson has a disadvantage that it is unable to set null replacement. We can only manually replace the null returned by the server in batch. The server is absolutely not allowed to return null during normal interface definition, but null will always appear in the background result! If you search, there is a common answer,

But this can not solve the inverse sequence problem. How to solve it? The solution is as follows:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>