使用哈希映射将数据解析为 JSON
Parse data to JSON using hash maps
我正在尝试将十六进制图转换为可用的 json 代码,但我不知道如何实现
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", userID );
Map<String, String> foodOrder = new HashMap<String, String>();
foodOrder.put("id",productID);
foodOrder.put("item_count",numberOfItems.getText().toString());
params.put("product", foodOrder.toString());
Arrays.deepToString(new JSONObject[]{new JSONObject(params)});
return params;
}
它应该看起来像这样:
{
"user_id": 2,
"product": {
"id": 15,
"item_count": 99
}
}
但现在我明白了:
{
"product": "{item_count=1, id=1}",
"user_id": "2"
}
我正在使用 Volly 库将数据表单应用程序传递到服务器。
toString() 方法不会 return 一个 json 除非你以这种方式实现它。在您的情况下,您使用的是 hashMap 的 toString,所以它不会。
尝试使用 Gson:
将地图转换为 json 字符串
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", userID );
Map<String, String> foodOrder = new HashMap<String, String>();
foodOrder.put("id",productID);
foodOrder.put("item_count",numberOfItems.getText().toString());
Gson gson = new Gson();
params.put("product", gson.toJson(foodOrder));
Arrays.deepToString(new JSONObject[]{new JSONObject(params)});
return params;
}
我正在尝试将十六进制图转换为可用的 json 代码,但我不知道如何实现
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", userID );
Map<String, String> foodOrder = new HashMap<String, String>();
foodOrder.put("id",productID);
foodOrder.put("item_count",numberOfItems.getText().toString());
params.put("product", foodOrder.toString());
Arrays.deepToString(new JSONObject[]{new JSONObject(params)});
return params;
}
它应该看起来像这样:
{
"user_id": 2,
"product": {
"id": 15,
"item_count": 99
}
}
但现在我明白了:
{
"product": "{item_count=1, id=1}",
"user_id": "2"
}
我正在使用 Volly 库将数据表单应用程序传递到服务器。
toString() 方法不会 return 一个 json 除非你以这种方式实现它。在您的情况下,您使用的是 hashMap 的 toString,所以它不会。 尝试使用 Gson:
将地图转换为 json 字符串protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", userID );
Map<String, String> foodOrder = new HashMap<String, String>();
foodOrder.put("id",productID);
foodOrder.put("item_count",numberOfItems.getText().toString());
Gson gson = new Gson();
params.put("product", gson.toJson(foodOrder));
Arrays.deepToString(new JSONObject[]{new JSONObject(params)});
return params;
}