介面返回JSON資料的封裝類
這串程式碼免去了每個介面都要封裝的煩惱,直接封裝成統一格式,也避免了不同人開發,返回格式不統一的問題,不多說直接開程式碼:
Result類:
public class Result implements Serializable {
private Integer state = 0;
private String msg = "成功";
private Object data;
public static Result assembly() {
return new Result();
}
public static Result assembly(Object data) {
Result result = new Result();
result.data = data;
return result;
}
public static Result assembly(Integer state, String msg, Object data) {
Result result = new Result();
result.state = state;
result.msg = msg;
result.data = data;
return result;
}
@Override
public String toString() {
Map<String, Object> map = new HashMap<>();
map.put("state", state);
map.put("msg", msg);
map.put("data", data);
return JSONObject.fromObject(map).toString();
}
}
測試類:
public class Test {
public static void main(String[] args) {
int[] a = { 1, 2, 3 };
List<String> l = new ArrayList<String>();
l.add("a");
l.add("b");
l.add("c");
Map<String, Object> map = new HashMap<>();
map.put("a", "aa");
map.put("b", 1);
map.put("c", l);
map.put("d", a);
System.out.println(Result.assembly(0, "這裡是msg", map));
}
}
測試結果:
好了到此結束,程式碼不多但是簡單實用!!!