2017-09-08 117 views
1

我的服務器團隊定義了一個可怕的響應,它可能是一個像{key1=value1, key2=value2}這樣的json對象,可能是一個像[{key3=value3, key4=value4}, {key3=value3a, key4=value4a}]這樣的json數組。Retrofit/GSON:如何處理兩種類型的響應:JSON對象和JSON數組?

兩種類型的具有邏輯關係如下:對於單一的API時,服務器將:

  • 發送,如果有一定的誤差,或
  • 發送JSON數組,如果有有效數據JSON對象。

我不能告訴他們改變這個,因爲這個響應被PC和iOS等其他端使用。

那麼我應該如何處理這個四個字母的單詞響應呢?我使用網絡和GSON的改進來進行響應反序列化。

回答

1
static class Entity { 
    String name; 
    // other fields 
} 

static class Error { 
    String errorName; 
    // other fields 
} 

public static void main(String[] args) throws Exception { 
    // no error 
    String jsonString = "[{'name': 'one'}, {'name': 'two'}]"; 
    // error 
    // String jsonString = "{'errorName': 'Not Found'}"; 

    Gson gson = new Gson(); 
    JsonElement jsonElement = new JsonParser().parse(jsonString); 
    if (jsonElement.isJsonArray()) { 
     // no error 
     Entity[] entities = gson.fromJson(jsonElement, Entity[].class); 
     System.out.println(entities[0].name); 
    } else if (jsonElement.isJsonObject()) { 
     // error 
     Error error = gson.fromJson(jsonElement, Error.class); 
     System.out.println(error.errorName); 
    } else { 
     throw new IOException("Server response is not jsonElement array or jsonElement object"); 
    } 
}