【问题标题】:Send Parameters in Volley Using GSON使用 GSON 在 Volley 中发送参数
【发布时间】:2019-12-04 13:12:51
【问题描述】:

我知道的 我可以在JsonObjectRequest 的帮助下使用Volley 而不使用GSON 来提出请求。现在我正在学习GSON,所以我可以在没有参数的情况下发出请求。

示例代码

    HashMap<String, String> params = new HashMap<String, String>();
        params.put("user",userId);

        Log.d(TAG + "pp", String.valueOf(params));




        String Url = Constants.Base_URL + "getcoupons/";

        JsonObjectRequest request = new JsonObjectRequest(Url,  new JSONObject(params),
                response -> {
                    Log.d(TAG, "respCoupan" + String.valueOf(response));

                    try {
                        String statusResponseObject = response.getString("status");
                        String msgObject = response.getString("msg");

                        if (statusResponseObject.equals("200")){

                            JSONArray jsonArray = response.getJSONArray("response");

                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject pendingFragResponse = jsonArray.getJSONObject(i);

                                String codeObject = pendingFragResponse.getString("code");
                                String typeObject = pendingFragResponse.getString("type");
                                String amountObject = pendingFragResponse.getString("amount");
                                String descriptionObject = pendingFragResponse.getString("description");
                                String leagueObject = pendingFragResponse.getString("league");
                                String expireObject = pendingFragResponse.getString("expire");

                                //

                                couponArrayList.add(new Coupon(codeObject, typeObject, amountObject,
                                        descriptionObject, leagueObject, expireObject));
                                couponAdapter = new CouponAdapter( couponArrayList, CoupanActivity.this);
                                recyclerView.setAdapter(couponAdapter);
                                wp10ProgressBar.hideProgressBar();
                                wp10ProgressBar.setVisibility(View.GONE);

                            }
                            couponAdapter.notifyDataSetChanged();
//                            wp10ProgressBar.hideProgressBar();
                        }else {
                            wp10ProgressBar.hideProgressBar();
                            wp10ProgressBar.setVisibility(View.GONE);
                            Toast.makeText(CoupanActivity.this, msgObject, Toast.LENGTH_SHORT).show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(this, "Server didn't response, Try after some time", Toast.LENGTH_LONG).show();
                    }



                }, error -> {
            error.printStackTrace();
            Log.d(TAG + "error", String.valueOf(error.getMessage()));
            Toast.makeText(this, "Server didn't response, Try after some time", Toast.LENGTH_LONG).show();

        });

        MySingleton.getInstance(CoupanActivity.this).addToRequestQueue(request);

JSON

{
"status": "200",
"msg": "Successfully",
"response": [
    {
        "code": "YUDH20",
        "type": "Flat",
        "amount": "2",
        "description": "Flat 20% credit Discount",
        "league": "0",
        "league_name": "",
        "expire": "2019-08-22"
    }
]

}

我想要什么

我想要一个清晰的示例来使用 GSON 和参数发出请求(意味着使用 GSON 在请求中发送 Hashmap 值)。
我可以使用GSON 作为 java 类的参数吗?
如何将 GSON 用于标头?

【问题讨论】:

    标签: java android json gson android-volley


    【解决方案1】:

    您必须创建数据类“ModelClass”和ResponseClass gson 转换“ModelClass”中的数据,您可以简单地使用这个类:

          public class ModelClass {
           private String status;
           private String msg;
           private JSONArray response;
            ...
    
        }
    

    并创建一个ResponseClass.class

        public class ResponseClass {
        private String code;
        private String type;
        private int amount;
        private String description;
        private String league;
        private String league_name;
        private String expire;
            ...
    
    }
    

    并将您的代码更改为:

      HashMap<String, String> params = new HashMap<String, String>();
            params.put("user", userId);
    
            Log.d(TAG + "pp", String.valueOf(params));
    
    
            String Url = SyncStateContract.Constants.Base_URL + "getcoupons/";
    
            JsonObjectRequest request = new JsonObjectRequest(Url, new JSONObject(params),
                    response -> {
                        Log.d(TAG, "respCoupan" + String.valueOf(response));
    
                        try {
    
                            Gson gson = new GsonBuilder()
                                    .serializeNulls()
                                    .create();
                            Type type = new TypeToken<ModelClass>() {
                            }.getType();
    
                            ModelClass result = gson.fromJson(response.toString(), type);
    
    
                            if (result.getMsg().equals("200")) {
                                for (int i = 0; i < result.getResponse().size(); i++) {
    
                            result.getResponse().get(i).getAmount()
                            result.getResponse().get(i).getCode()
                            result.getResponse().get(i).getExpire()
                                    ...
                            }}
    
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Toast.makeText(this, "Server didn't response, Try after some time", Toast.LENGTH_LONG).show();
                        }
    
    
                    }, error -> {
                error.printStackTrace();
                Log.d(TAG + "error", String.valueOf(error.getMessage()));
                Toast.makeText(this, "Server didn't response, Try after some time", Toast.LENGTH_LONG).show();
    
            });
    
            MySingleton.getInstance(CoupanActivity.this).addToRequestQueue(request);
    

    【讨论】:

    • 你的答案是对的,但我想要高效的代码和更少的代码行。喜欢通过响应自动设置所有东西
    猜你喜欢
    • 2015-08-10
    • 2017-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多