2017-05-24 81 views
1

我目前正在開發一個項目,通過他們的REST API上傳文件,並且他們的服務器在JSON中返回以下內容。Java - 返回自定義錯誤代碼

[{"code":0,"id":"19348139481","name":"file.bin"}] 

用 「代碼」 有可能的3個值:

  • 0上傳成功
  • 1文件太大
  • 2無法保存文件

我能在刪除括號後得到每對鍵/值,但是有什麼方法可以將「代碼」與其消息相關聯嗎?我想這樣做是在C++

define 0 UPLOAD_SUCCESSFUL 
define 1 FILE_TOO_BIG 
define 2 COULDNT_SAVE_FILE 

所以定義代碼像這樣,當我得到的「代碼」我可以顯示像對應的消息:

System.out.println(code.msg); 
+0

你可以使用一個數組,你可以在一個函數中使用switch語句,你可以使用'enum',你可以用一個'地圖<整數,字符串>'...你有很多可能性:)我個人會避免使用一個數組,因爲它會迫使你使用連續的代碼號(你不能在'0','1'和'2'後面使用'99'代碼)。 switch語句不是很優雅......如果你關心性能,也許'Map'將是最好的選擇 – Oneiros

+0

@Oneiros你應該把它放在答案中,並添加一段代碼來說明你的Mpa建議。 – fvu

+0

您可能的值的枚舉列表的最佳解決方案是一個枚舉。 – chrylis

回答

1

由於可能的返回值的列表中把它叫做穩定的enum都可以使用。例如:

public class App { 

    public static void main(String[] args) { 
     for (int responseCode = 0; responseCode <= 2; responseCode++) { 
      UploadResponse response = UploadResponse.getUploadResponse(responseCode); 
      System.out.println(response.getMessage()); 
     } 
    } 

    private enum UploadResponse { 
     SUCCESS(0, "upload successful"), 
     FILE_SIZE_ERROR(1, "file too big"), 
     FILE_SAVE_ERROR(2, "could not save file"); 

     private int code; 
     private String message; 

     private UploadResponse(int code, String message) { 
      this.code = code; 
      this.message = message; 
     } 

     public String getMessage() { 
      return message; 
     } 

     public static UploadResponse getUploadResponse(int code) { 
      for (UploadResponse response : UploadResponse.values()) { 
       if (response.code == code) { 
        return response; 
       } 
      } 

      throw new IllegalArgumentException("Unsupported UploadResponse code: " + code); 
     } 
    } 
} 
0

一個簡單的解決方案可能是,如果當然返回代碼實際上是0,1和2:

String message[] = {"upload successful","file too big","could not save file"}; 
... 
System.out.println(message[code]); 

旁註:如果I am able to get each pair of key/value after removing the brackets實際上意味着通過手動打破JSON消息檢索代碼:不。使用像Jackson或GSON這樣的適當的JSON API。在今天的編碼領域,JSON足夠重要,可以投資學習強大的多功能API。

+0

實際上我使用GSON但​​括號[]圍繞JSON會產生錯誤。 JsonObject repCode = new Gson()。fromJson(result.toString()。replaceAll(「[\\ [\\]]」,「」),JsonObject.class); \t \t System.out.println(repCode.get(「code」)。getAsInt()); 顯示:0(例如) – retArdos

+0

對於上傳響應是的代碼是0 1和2.但是對於其他功能,它不是我不能使用它。 – retArdos

+0

錯誤是由於您返回的是**數組**而引起的,因此應該這樣處理。您可以將您的代碼更改爲'JsonObject [] repCode = new Gson()。fromJson(result,JsonObject []。class); System.out.println(repCode [0] .get(「code」)。getAsInt());'。比改變輸入字符串更清潔。 – fvu

-1

一個簡單的解決方案可能是創建一個使用開關盒的方法。事情是這樣的:

public static String getCodeMessage(int code) { 
    switch (code) { 
    case 0: return "UPLOAD_SUCCESSFUL"; 
    case 1: return "FILE_TOO_BIG"; 
    case 2: return "COULDNT_SAVE_FILE"; 
    default: return "Uknown code"; 
    } 
} 

然後,你可以通過使用System.out.println(getCodeMessage(code));

+0

當您使用退貨時,您不需要這樣做。 –

+0

謝謝,這就是我一開始會做的,但我認爲它會太重,特別是因爲我查詢的網站有其他功能的方式更多的錯誤代碼。 大概跟enum一起,我會看看我能做些什麼。 – retArdos