java - 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 结构中它是一个整数,我怎样才能像整数值一样解析这些数据?
解决方案
您不需要解析任何内容,而是按预期使用 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 进行改造也可以类似地工作
推荐阅读
- python - 读取 csv 文件中的列但输出错误
- rbenv - 无法在 Mac Big Sur 上安装 Ruby 1.9.1
- .net - 没有输出时 Process.StandardOutput.Readline() 挂起
- python - 迭代太慢:找到了更快的替代方案,但 'sqlite3.Row' 而不是值
- php - 表格无法识别
- apache-spark - Apache Beam java.lang.IllegalArgumentException:无效的 lambda 反序列化
- sql - 仅选择新更新/受影响行的触发器
- sql-server - 如何找到 Azure 数据资源管理器数据库 (Playfab) 的 SQL Server 连接
- python - 使用 lambda 生成字典
- dns - 多少 DNS SRV 记录太多了?