I have some kind of JSON (I have no control or ability to change the structure and / or names in JSON ... it is important to keep this in mind), which has a "flat" structure similar to this:
{ "name": "...", "email": "...", "box_background_color": "...", "box_border_color": "...", "box_text_color": "...", ... }
Now I can just create a simple object that holds everything as I like:
public class Settings { @SerializedName("name") private String _name; @SerializedName("email") private String _emailAddress; @SerializedName("box_background_color") private String _boxBackgroundColor; @SerializedName("box_border_color") private String _boxBorderColor; @SerializedName("box_text_color") private String _boxTextColor; ... }
However, I want everything related to box parameters to be in its own class ( BoxSettings ). This is more like what I want:
public class Settings { @SerializedName("name") private String _name; @SerializedName("email") private String _emailAddress; private BoxSettings _boxSettings ... } public class BoxSettings { @SerializedName("box_background_color") private String _boxBackgroundColor; @SerializedName("box_border_color") private String _boxBorderColor; @SerializedName("box_text_color") private String _boxTextColor; ... }
I know that if JSON was structured so that the mailbox settings were nested, then it would be easy to accomplish what I want, however, I have no way to change the JSON structure, so please t assume that (I would do this if I could).
My question is this: Does the entire TypeAdapter create the only way to accomplish what I want, or can I accomplish most of this with annotations? If this is not the only way, how else can I do this without changing the JSON?
The following is an example of what I mean by "creating an integer TypeAdapter":
public class SettingsTypeAdapter implements JsonDeserializer<Settings>, JsonSerializer<Settings> { @Override public JsonElement serialize(Settings src, Type typeOfSrc, JsonSerializationContext context) { // Add _name // Add _emailAddress // Add BoxSettings._boxBackgroundColor // Add BoxSettings._boxBorderColor // Add BoxSettings._boxTextColor return jsonElement; } @Override public Settings deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { // Read _name // Read _emailAddress // Read BoxSettings._boxBackgroundColor // Read BoxSettings._boxBorderColor // Read BoxSettings._boxTextColor return settings; } }