Java - 返回自定义错误代码

时间:2017-05-24 13:42:25

标签: java

我目前正在开发一个项目,我通过他们的REST API上传文件,他们的服务器在JSON中返回以下内容。

[{"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);

3 个答案:

答案 0 :(得分:1)

由于可能的返回值列表是稳定的,因此可以使用<div class="form-group form-group-sm"> @Html.Label("Items", new { @class = "control-label" }) @Html.ListBoxFor(x => x.SelectedAccountItems, Model.UserItems, new { @class = "form-control", @id = "ddlistaccountitems", @multiple = "multiple" }) </div> 。例如:

enum

答案 1 :(得分: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消息来检索代码:不要。使用适当的JSON API,如Jackson或GSON。 JSON在今天的编码环境中非常重要,可用于学习强大的多功能API。

答案 2 :(得分:-1)

一个简单的解决方案可能是创建一个使用switch case的方法。像这样:

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));

来调用它