天天看點

通用傳回對象 - 傳回指定類型資料

分享知識 傳遞快樂

根據參數中指定的對象類型傳回目前類性的資料。

public class AppDemo {

    public static void main(String[] args) {

        OrderVO order = getOrderById("15065");
        System.out.println(order.toString());

    }

    public static OrderVO getOrderById(String orderId) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("id", orderId);
        try {
            String url = ConfigConstants.MAIN_URL;
            // 關鍵點
            ResultSetDTO<OrderVO> accountVO = getObject(url, params, OrderVO.class);
            if (accountVO != null) {
                return accountVO.getObj();
            }
        } catch (BusinessException e) {
            throw new BusinessException(StrUtil.format("擷取客戶時發生異常!異常原因:{}", e.getMessage()));
        }
        return null;
    }


    public static <T> ResultSetDTO<T> getObject(String url, Map<String, Object> params, Class<T> clazz) {
        try {
            System.out.println("擷取對象資料 >>> " + JSON.toJSONString(params));
            String data = HttpRequest.get(url)
                    .header("Authorization", "")
                    .form(params)
                    .execute()
                    .body();
            System.out.println("請求查詢資料清單傳回結果:>>>> " + data);
            if (data != null) {
                ResultSetDTO<T> resultSetDTO = JSON.parseObject(data, ResultSetDTO.class);
                if (resultSetDTO == null || resultSetDTO.getError_code() != null) {
                    throw new BusinessException(JSON.toJSONString(resultSetDTO));
                }
                // 關鍵點
                JSONObject jsonObject = JSON.parseObject(data);
                T t = JSONObject.toJavaObject(jsonObject, clazz);
                resultSetDTO.setObj(t);
                return resultSetDTO;
            }
        } catch (BusinessException e) {
            throw new BusinessException("查詢資料清單時發生異常!異常原因:" + e.getMessage());
        }
        return null;
    }
}