Given the following class hierarchy, I would like Foo to be serialized differently depending on the context it is used in my class hierarchy.
public class Foo {
I would use the google code gson
documentation in here https://code.google.com/p/google-gson/
Maven dependency is:
com.google.code.gson
gson
2.2.1
The annotations are like this:
To expose the field user the @Expose
annotation
To generate a special name for the field in the parsed json user the @SerializedName("fieldNameInJSON")
annotation
So your classes would look like this:
public class Foo {
@SerializedName("bar")
@Expose
public String bar;
@SerializedName("biz")
@Expose
public String biz;
}
public class FooContainer {
@SerializedName("fooA")
@Expose
public Foo fooA;
@SerializedName("fooB")
@Expose
public Foo fooB;
}
To serialize to JSON you will use a code that looks like this:
public String convertToJSON(FooContainer fc) {
if (fc != null) {
GsonBuilder gson = new GsonBuilder();
return gson.excludeFieldsWithoutExposeAnnotation().create().toJson(fc);
}
return "";
}
It would look the same for Lists for example:
public String convertToJSON(List fcs) {
if (fcs != null) {
GsonBuilder gson = new GsonBuilder();
return gson.excludeFieldsWithoutExposeAnnotation().create().toJson(fcs);
}
return "";
}