我有一些JSON進來(我沒有任何控制或能力來改變結構和/或命名內JSON ...重要的是要記住在這個問題),有一個「扁平」結構類似於這樣的:gson flat json嵌套對象需要串行器/解串器嗎?
{
"name": "...",
"email": "...",
"box_background_color": "...",
"box_border_color": "...",
"box_text_color": "...",
...
}
現在,我就可以創建一個簡單的對象,使一切平,像這樣:
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;
...
}
但是,我希望與box
設置相關的所有內容都位於其自己的類中(BoxSettings
)。這更像是我想要的:
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;
...
}
我知道,如果JSON結構使得箱設置被嵌套那麼這將是很容易做到我想要的東西,但是,我不沒有能力改變JSON的結構,所以請不要暗示(如果可以的話,我會這麼做的)。
我的問題是這樣的:正在創建一個整個TypeAdapter 來完成我想還是我還可以完成大部分的這種帶有註釋的唯一途徑?如果它不是唯一的方法,我怎麼能在不改變JSON的情況下做到這一點?
以下是我的意思是「創建整個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;
}
}
你找到任何解決方案? – Umair 2017-03-02 07:30:05
@Umair不,還沒有。還在等待。抱歉。 – bsara 2017-03-02 19:47:42