Gson Path


Source link: https://github.com/LachlanMcKee/gsonpath

Gson Path

An annotation processor library which generates gson type adapters at compile time which also use basic JsonPath functionality.

Benefits

The benefits of this library are as follows:

Statically generated Gson Type Adapters

By statically generating Gson Type Adapters, the majority of reflection used by the Gson library can be removed. This greatly improves performance and removes code obfuscation issues.

JsonPath syntax

JsonPath syntax can be used to reduce the number of POJOs required to parse a JSON file. See the example section for more details.

This allows for easier integration with other libraries which rely on a flat class structure (such as DBFlow).

POJO immutability via interfaces

You are given the option of using immutable POJOs based off annotated interfaces.

These POJOs are similar to AutoValue, however you do not need to reference the concrete implementation as the Type Adapter creates it on your behalf.

See the interfaces guide for further details.

JsonPath - Path Substitutions

You can reduce the amount of repetition when creating POJOs using Path Substitutions by using straightforward string replacement functionality within the AutoGsonAdapter annotation.

See the path substitution guide for further details.

Optional client side validation

Add optional client side validation to your json using @Nullable and NonNull annotations to add mandatory field constraints.

The client side valiation can also be enhanced through extensions. These extensions are separate annotation processors that register to be notified whenever a field with a specific annotation is encountered.

Notable extensions

Android Support Annotation validation

Example

Given the following JSON:

{

 "person": {

 "names": {

 "first": "Lachlan",

 "last": "McKee"

 
}

 
}
 
}

We can deserialize the content with a single class by using Gson Path. The following class demonstrates the annotations required to create a type adapter which can correctly read the content.

@AutoGsonAdapter(rootField = "person.names") public class PersonModel {

 @SerializedName("first")
 String firstName;

  @SerializedName("last")
 String lastName; 
}

We could also write it as follows (to reduce the number of annotations required):

@AutoGsonAdapter(rootField = "person.names") public class PersonModel {

 String first;
 String last; 
}

Setup

The following steps are required to use the generated TypeAdapters within your project.

AutoGsonAdapterFactory

Create a type adapter factory by annotating an interface as follows:

package com.example;
@AutoGsonAdapterFactory public interface ExampleGsonTypeFactory extends TypeAdapterFactory {
 
}

Gson Path can be used across multiple modules by defining a factory within each.

Note: Only one @AutoGsonAdapterFactory annotation may be used per module/project. If you do this accidentally, the annotation processor will raise a helpful error.

AutoGsonAdapter

Create any number of type adapters by annotating a class or interface as follows:

package com.example;
@AutoGsonAdapter public class ExampleModel {

  String value; 
}

or

package com.example;
@AutoGsonAdapter public interface ExampleModel {

  String getValue();
 
}

Gson Integration

For each type adapter factory interface, register it with your Gson builder as follows:

return new GsonBuilder()

  .registerTypeAdapterFactory(GsonPath.createTypeAdapterFactory(ExampleGsonTypeFactory.class))

  .create();

Proguard

To use proguard within your project, you must add the generated type adapter factory. Using the example above, this would be:

-keep public class com.example.ExampleGsonTypeFactoryImpl 

Download

This library is available on Maven, you can add it to your project using the following gradle dependencies:

compile 'net.lachlanmckee:gsonpath:2.3.0' apt 'net.lachlanmckee:gsonpath-compiler:2.3.0'

Resources

A native Java class library, which provides your Android application with rich capabilities for creating, editing and visualizing graphs, networks, flowcharts, algorithms, genealogy trees and much more.

'Path' has a very attractive menu sitting on the left bottom corner of the screen. Satellite Menu is the open version of this menu.

Python script to highlight adb logcat output in console.

The HttpResponseCache library provides transparent and automatic caching of HTTP and HTTPS requests that use the java.net.HttpUrlConnection classes.

For information on how to use HttpUrlConnection, refer to the Android documentation - don't worry, the information also applies to non-Android Java.

Smooth activity switch animation.

PoppyView is a library which implements view on the bottom which come and go relative to the user scroll.

Just add the library to your application as a library project. And don't forget that your project must use NineOldAndroids.

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