Permalink
Fetching contributors…
Cannot retrieve contributors at this time
180 lines (126 sloc) 6.12 KB

YaGson

Overview

YaGson is a universal type-preserving Java serialization library that can convert (almost) arbitrary Java Objects into JSON and back, with transparent support for circular references of any kind and with a full Java 9 compatibility.

YaGson is based on Google’s Gson, so it inherits all Gson benefits and adds new valuable features. The name YaGson is actually an abbreviation for "yet another Gson".

Compared to other JSON serializers, such as Gson or Jackson, YaGson imposes almost no restrictions on the serialized classes, and requires neither changes to those classes (like adding annotations for Jackson) nor custom Gson adapters for out-of-the-box support of complicated cases like:

  • child to parent references, self-references, and circular references of any other kind

  • mixed-type arrays, collections, and objects

  • inner, local, and anonymous classes.

Thanks to the above versatility, YaGson is a solid choice for implementing REST interfaces between Java server and client machines, e.g. for Java-based microservices.

Sample usage

The basic usage of YaGson is quite simple and is very similar to that of Gson. You just use classes YaGson or YaGsonBuilder instead of Gson/GsonBuilder.

First, create a mapper instance, using either default (1) or custom (2) settings:

  YaGson mapper = new YaGson(); // (1)
  YaGson altMapper = new YaGsonBuilder()
     .setPrettyPrinting()
     // ... set other  custom Settings
     .create(); // (2)

Now you can use the mapper instance to serialize Java primitives, objects, and arrays to JSON, and de-serialize them back:

  // ...
  Person obj = new Person("John", "Doe");

  String objJson = mapper.toJson(obj, Person.class); // (3)
  // objJson = {"name":"John","family":"Doe"}

  Person deserisalizedObj = mapper.fromJson(objJson, Person.class); // (4)
  // deserisalizedObj = Person{name='John', family='Doe'}

(3) Serialize to JSON with the toJson() method, providing the known de-serialization type Person.class

(4) De-serialize a JSON string back to a Java object with the fromJson() method, using the same de-serialization type as the one used in (3)

Warning
The serialization type used in toJson, MUST BE equal to or less specific than the de-serialization type used in fromJson. If the de-serialization type is not known at the time of serialization, just use Object.class.


For example:

  // ...
  String objJson = mapper.toJson(obj, Object.class);
  // objJson = {"@type":"samples.Person","@val":{"name":"John","family":"Doe"}} // (5)

  Person deserisalizedObj = mapper.fromJson(objJson, Person.class);
  // deserisalizedObj = Person{name='John', family='Doe'}

  // or, with the same result:
  Person deserisalizedObj2 = (Person) mapper.fromJson(objJson, Object.class);

(5) Notice the @type/@val wrapper around the first JSON representation of the Person instance. YaGson adds such wrappers when the actual type at run time is more specific than the provided serialization type.

Tip

When working with generic types, it is recommended to provide fully parameterized serialization/deserialization types using Gson’s TypeTokens, like

    Type myMapType = new TypeToken<HashMap<Long, String>>(){}.getType();
    String myMapJson = mapper.toJson(myMap, myMapType);


Finally, let’s see how a simple self-referencing array is serialized.

  Object[] obj = new Object[3];
  obj[0] = "foo";
  obj[1] = obj;
  obj[2] = "bar";

  String objJson = mapper.toJson(obj, Object[].class);
  // objJson = ["foo","@root","bar"]

  Object[] deserisalizedObj = mapper.fromJson(objJson, Object[].class);
  // deserisalizedObj = [foo, [...], bar]


Note
The JSON representation of the second element of the array is @root, meaning a reference to the serialized object itself. There may be more complicated references, describing a path from the root to a referenced object, e.g. @root.0.field1.1-key. Also, there are shortcut references like @.field, which point to a sibling field in the parent object.

New in version 0.4

  • Java 9 compatibility

  • google-gson codebase is updated to release 2.8.2

New in version 0.3.1

  • Bugfixes

New in version 0.3

New features:

  • Ability to specify class loaders to use for de-serialization, see YaGsonBuilder.setPreferredClassLoaders();

  • Ability to limit the output JSON length, see YaGson.toJson(Object src, long charsLimit)

Updates:

  • google-gson codebase is updated to release 2.8.1

  • bugfixes

New in version 0.2

New features:

  • Java 8 support, including:

    • full serialization and de-serialization of serializable lambdas;

    • skipping non-serializable lambdas;

Updates:

  • google-gson codebase is updated to release 2.8.0

New in version 0.1

New features:

  • mapping of (almost) arbitrary objects, with no need for custom adapters, annotations, or any other changes of the serialized classes;

  • preservation of exact types during mapping;

  • preservation of Collections/Maps behavior, including custom Comparators;

  • serialization of self-referencing objects, including collections, maps, and arrays;

  • serialization of inner, local, and anonymous classes;

  • support for mixed-type collections, maps, and arrays;

  • support for multiple fields with the same name in one object (e.g. when "duplicate" fields are declared in super-classes);

License

Licensed under the Apache License, Version 2.0

More

For more information and samples, see the User’s Guide and Q&A. Also, some samples runnable as JUnit tests are available in the yagson-samples GitHub project.

Contact Us

To report a bug or suggest improvements, please open a GitHub issue.

To get in touch with the YaGson author, please write to yagson@gilecode.com