gson-flatten
Library to collapse inner objects when parsing json
-
To use library you should add it in your build.gradle:
compile 'org.itishka.gson-flatten:gson-flatten:0.7'
-
Then register it in your gson builder:
final Gson gson = new GsonBuilder() .registerTypeAdapterFactory(new FlattenTypeAdapterFactory()) .create();
-
Define your class and use
@Flatten
annotation to get data from embedded objects. For example classclass 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 } }
-
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