You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何设置从API获取的商品总金额文本 解决JSON转换报错问题

报错原因

你使用JsonArrayRequest发起请求时,框架要求接口返回内容必须是标准JSON数组结构,但你调用的接口实际返回的是纯字符串Final:92,不符合JSONArray格式要求,因此触发类型转换异常。

解决步骤

  1. 替换请求类型:将JsonArrayRequest改为StringRequest,适配接口返回的字符串格式
  2. 简化解析逻辑:直接拆分返回字符串提取总金额数值,不需要JSONArray相关解析逻辑

修改后的getTotal方法

private void getTotal(Integer intquantity) {
    strproquantity = qty.getText().toString();
    String url = Config.URL + "apiurl.aspx?msg=CalculateFnMRPWithQty%20" + strprocode + "%20" + intquantity;
    Log.d("TAG" + "quantity url", url);
    
    StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
        @RequiresApi(api = Build.VERSION_CODES.O)
        @Override
        public void onResponse(String response) {
            Log.d("TAG", "返回结果-----------" + response);
            parseAmountData(response);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("TAG", "请求错误: ", error);
            loading.dismiss();
        }
    });
    // 此处补全将请求添加到你的Volley请求队列的代码
    // 示例:RequestQueue queue = Volley.newRequestQueue(this); queue.add(stringRequest);
}

新增金额解析方法

private void parseAmountData(String response) {
    loading.dismiss();
    try {
        // 拆分返回字符串Final:xxx的格式,提取冒号后的金额数值
        if(response.contains(":")){
            strprototal = response.split(":")[1].trim();
            totalprize.setText(strprototal);
            // 如需处理数量逻辑可在此处自行补充
        }
    } catch (Exception e) {
        Log.e("TAG", "金额解析失败: ", e);
    }
}

注意事项

如果后续接口调整为返回JSON结构,再换回对应JSON请求类型即可。

内容的提问来源于stack exchange,提问作者Shweta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 23:45:04