Volley:如何通过HashMap解析带有整数的数据字符串

时间:2018-11-18 20:57:24

标签: java android json android-volley

如何通过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结构中,它是一个整数, 我怎样才能像整数值一样解析这些数据?

1 个答案:

答案 0 :(得分:1)

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

要从struct X { int x; } std::vector<X> src; std::vector<int> dst; ... auto it_dst = dst.begin(); for (auto& element : src) { *(it_dst++) = element.x; } 方法中移动地图(并可能将其完全删除),然后在Volley调用之前创建有效负载

getParams

如果要解析响应,则可以直接调用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>() { ,例如

如果您愿意,可以将Volley与Gson结合使用,如Android文档中所述,这可以使该实现更简洁,或者Retrofit w / Gson也可以类似地工作