AutoValue: Gson Extension


Source link: https://github.com/rharter/auto-value-gson

AutoValue: Gson Extension

An extension for Google's AutoValue that creates a simple Gson TypeAdapterFactory for each AutoValue annotated object.

Usage

Simply include auto-value-gson in your project and add a public static method to your @AutoValue annotated class returning a TypeAdapter. You can also annotate your properties using @SerializedName to define an alternate name for de/serialization.

@AutoValue public abstract class Foo {

abstract String bar();

@SerializedName("Baz") abstract String baz();

abstract int quux();

abstract String with_underscores();

 // The public static method returning a TypeAdapter<Foo> is what
// tells auto-value-gson to create a TypeAdapter for Foo.
public static TypeAdapter<Foo> typeAdapter(Gson gson) {

  return new AutoValue_Foo.GsonTypeAdapter(gson);

}
 
}

Additionally, you can set custom default values. This is disabled by default. See Compiler options on how to enable this.

@AutoValue public abstract class Foo {

abstract String bar();

@SerializedName("Baz") abstract String baz();

abstract int quux();

abstract String with_underscores();

 public static TypeAdapter<Foo> typeAdapter(Gson gson) {

  return new AutoValue_Foo.GsonTypeAdapter(gson)

 // You can set custom default values

 .setDefaultQuux(4711)

 .setDefaultWith_underscores("");

}
 
}

Now build your project and de/serialize your Foo.

The TypeAdapter

To trigger TypeAdapter generation, you need include a non-private static factory method that accepts a Gson parameter and returns a TypeAdapter for your AutoValue type. From within this method you can instantiate a new GsonTypeAdapter which will have been generated as an inner class of your AutoValue generated implementation.

@AutoValue public abstract class Foo {

// properties...

public static TypeAdapter<Foo> typeAdapter(Gson gson) {

  return new AutoValue_Foo.GsonTypeAdapter(gson);

}
 
}

Generics support

If your annotated class uses generics, you'll have to modify your static method a little so AutoValue will know how to generate an appropriate adapter. Simply add a TypeToken parameter and pass it to the generated GsonTypeAdapter class.

To have support for fields with generic parameters (eg. List<B>) you need to upgrade your Gson dependency to at least 2.8.0, which introduces the helper TypeToken.getParameterized() see Gson Changelog.

@AutoValue public abstract class Foo<A, B, C> {

 abstract A data();

abstract List<B> dataList();

abstract Map<String, List<C>> dataMap();

 public static <A, B, C> TypeAdapter<Foo<A, B, C>> typeAdapter(Gson gson,

 TypeToken<? extends Foo<A, B, C>> typeToken) {

  return new AutoValue_Foo.GsonTypeAdapter(gson, typeToken);

}
 
}

Factory

Optionally, auto-value-gson can create a single TypeAdapterFactory so that you don't have to add each generated TypeAdapter to your Gson instance manually.

To generate a TypeAdapterFactory for all of your auto-value-gson classes, simply create an abstract class that implements TypeAdapterFactory and annotate it with @GsonTypeAdapterFactory, and auto-value-gson will create an implementation for you. You simply need to provide a static factory method, just like your AutoValue classes, and you can use the generated TypeAdapterFactory to help Gson de/serialize your types.

@GsonTypeAdapterFactory public abstract class MyAdapterFactory implements TypeAdapterFactory {

 // Static factory method to access the package
// private generated implementation
public static TypeAdapterFactory create() {

  return new AutoValueGson_MyAdapterFactory();

}

 
}

Then you simply need to register the Factory with Gson.

Gson gson = new GsonBuilder()
  .registerTypeAdapterFactory(MyAdapterFactory.create())
  .create();

Compiler options

  • autovaluegson.defaultCollectionsToEmpty - If specified, maps/collections will default to their empty types (e.g. List -> Collections.emptyList()). Value is true or false. By default this is false.
  • autovaluegson.mutableAdaptersWithDefaultSetters - Indicates that the generated TypeAdapter should be mutable with setters for default values. Value is true or false. By default this is false.
android {

// ...
defaultConfig {

  // ...
  javaCompileOptions {

 annotationProcessorOptions {

arguments = ['autovaluegson.defaultCollectionsToEmpty': 'true']

 
}

  
}

}
 
}

Download

Add a Gradle dependency to the apt and provided configuration.

annotationProcessor 'com.ryanharter.auto.value:auto-value-gson:0.6.0' provided 'com.ryanharter.auto.value:auto-value-gson-annotations:0.6.0'

Snapshots of the latest development version are available in Sonatype's snapshots repository.

You will also need a normal runtime dependency for gson itself.

compile 'com.google.code.gson:gson:2.8.0'

License

Copyright 2015 Ryan Harter.  Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License. You may obtain a copy of the License at
  http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 

Resources

A standalone packaging of the annotations from Google's AutoValue library.

A ViewPager that shows items from right to left for RTL locales and behaves like a regular ViewPager otherwise.

Template for Android Studio wizard for projects using Dagger.

An android library which provides a compact calendar view much like the one used in google calenders, following material design.

Simple Android widget that display a loading animation when a user clicks the button.

The android library that is used to manage the preferences.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes