我最後的解決方案 - 定製
JsonDeserializer
的Json消息:
1)成功消息
{"data": ["success"],
"message": "message_text"
}
2)錯誤信息
{"message": { "name": ["message_text"], "email": ["message_text"], "subject": ["message_text"], "body": ["message_text"] }}
也許它可以幫助別人。
public static class GeneralResponceDeserializer implements JsonDeserializer {
@Override
public Object deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
JsonObject jobject = (JsonObject) jsonElement;
Gson googleJson = new Gson();
ArrayList<String> dataList = null;
if (jobject != null && jobject.get("data") != null) {
JsonArray dataArray = jobject.get("data").getAsJsonArray();
dataList = googleJson.fromJson(dataArray, new TypeToken<List<String>>(){}.getType());
}
String message = null;
Message messageObject = null;
if (jobject != null && jobject.get("message") != null) {
try {
message = jobject.get("message").getAsString();
} catch (UnsupportedOperationException e) {
JsonElement messageObjectJson = (JsonObject) jobject.get("message").getAsJsonObject();
JsonObject jMessageobject = (JsonObject) messageObjectJson;
if (jMessageobject != null) {
JsonArray name = jMessageobject.getAsJsonArray("name");
JsonArray subject = jMessageobject.getAsJsonArray("subject");
JsonArray body = jMessageobject.getAsJsonArray("body");
JsonArray email = jMessageobject.getAsJsonArray("email");
ArrayList<String> nameDataList = null;
ArrayList<String> subjectDataList = null;
ArrayList<String> bodyDataList = null;
ArrayList<String> emailDataList = null;
if (name != null) {
nameDataList = googleJson.fromJson(name, new TypeToken<List<String>>(){}.getType());
}
if (subject != null) {
subjectDataList = googleJson.fromJson(subject, new TypeToken<List<String>>(){}.getType());
}
if (body != null) {
bodyDataList = googleJson.fromJson(body, new TypeToken<List<String>>(){}.getType());
}
if (email != null) {
emailDataList = googleJson.fromJson(email, new TypeToken<List<String>>(){}.getType());
}
messageObject = new Message(nameDataList, subjectDataList, bodyDataList, emailDataList);
}
}
}
return new GeneralResponceObject(dataList, message, messageObject);
}
}
的問題是,它是未知的什麼類型的「消息」的將是 – Natali
這是一個不平凡的問題,你需要增加更多的細節和代碼,你有這麼遠... [SO]是不是一個服務來產生你的代碼你,但我們會幫助解決的問題,必須花心思雖然 – Merlin
我並不需要大量的代碼,我只是想知道我怎麼可以設置兩種類型,以一個變量,礦點別的。 – Natali