gson-flatten

Additional

Language
Java
Version
0.7 (Jun 29, 2017)
Created
May 19, 2016
Updated
Apr 28, 2019 (Retired)
Owner
Andrey Tikhonov (Tishka17)
Contributors
Tom Insam (tominsam)
Andrey Tikhonov (Tishka17)
Raja Baz (raja-baz)
Souvik Hazra (souvikhazra1)
4
Activity
Badge
Generate
Download
Source code

gson-flatten

Library to collapse inner objects when parsing json

  1. To use library you should add it in your build.gradle:

        compile 'org.itishka.gson-flatten:gson-flatten:0.8.1'
  2. Then register it in your gson builder:

    final Gson gson = new GsonBuilder()
              .registerTypeAdapterFactory(new FlattenTypeAdapterFactory())
              .create();
  3. Define your class and use @Flatten annotation to get data from embedded objects. For example class

    class Weather {
      @Flatten("temperature::min")
      int min_temperture;
      @Flatten("temperature::max")
      int max_temperture;
    }

    will be filled with data from json

    {
      "temperature": {
         "min": -273,
         "max": 1000
      }
    }
  4. Then just parse or serialize json as your usually do:

      String json = gson.toJson(weather);
      Weather weather2 = gson.fromJson(json, Weather.class);

Additional features

  • You can skip field name if it equlas in inner object and outer one. E.g.:
class Weather {
    @Flatten("temperature::")
    int min;
    @Flatten("temperature::")
    int max;
}
  • You can get array items as well (tnx @tominsam):
class SomeClass {
    @Flatten("some_array::0")
    int first_value;
}
  • If you are using Gson 2.7 with some FieldNamingStrategies with and gson-flatten 0.6 you do not need to do anything more!

With previous versions of gson and gson-flatten you should provide FieldNamingStrategy to FlattenTypeAdapterFactory:

final Gson gson = new GsonBuilder()
          .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
          .registerTypeAdapterFactory(new FlattenTypeAdapterFactory(FieldNamingPolicy.UPPER_CAMEL_CASE))
          .create();

License

Based on https://github.com/noties/Flatten

Gson-flatten is released under LGPL 3.0 license