首页 > 解决方案 > Volley:如何通过 HashMap 解析带整数的数据字符串

问题描述

如何通过 HashMap 解析带有整数的数据字符串 我有 json 的字符串和整数数据,而 HashMap 中的问题他只接受字符串或整数值 这是 Json 的结构

   {
   "status":true,
   "message":"Get Products Successfully",
   "products":[
      {
         "p_id":48,
         "p_name":"Ford Red",
         "p_descrption":"rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr",
         "p_price":15000,
         "p_offer_price":12000,
         "p_image":"myLinkimage"
      }
     ]
   }

这是我的java代码

 final ProgressDialog pDialog = new ProgressDialog(getActivity());
    pDialog.setMessage("Loading...");
    pDialog.show();

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, "myLink", null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {


                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String,String> params = new HashMap<>();
            params.put("p_name","mac");
            params.put("p_descrption","mac mac 2018");
            params.put("p_price","10000");
            params.put("p_offer_price","8000");
            params.put("p_image","https://d.top4top.net/p_105212t9r1.jpg");
            return params;
        }
    };


    AppController.getInstance().addToRequestQueue(jsonObjectRequest);

params.put("p_price","10000");
params.put("p_offer_price","8000");

在我的 json 结构中它是一个整数,我怎样才能像整数值一样解析这些数据?

标签: javaandroidjsonandroid-volley

解决方案


您不需要解析任何内容,而是按预期使用 JsonObjectRequest。

这是从getParams方法中移动地图(并可能完全删除该方法),然后在 Volley 调用之前创建您的有效负载

JSONObject payload = new JSONObject();
JSONArray products = new JSONArray();

JSONObject product = new JSONObject();
product.putInt("price", 100);
products.add(product);

payload.putArray("products", products);

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, "myLink", payload,
        new Response.Listener<JSONObject>() {

如果你想解析响应,你可以直接调用response.getInt,例如

如果需要,您可以将 Volley 与 Gson 结合使用,正如 Android 文档中所指出的那样,这使得该实现更简洁,或者使用 Gson 进行改造也可以类似地工作


推荐阅读