Java 使用哈希映射将数据解析为JSON
我试图将hexmap转换成可用的json代码,但我不知道如何转换Java 使用哈希映射将数据解析为JSON,java,android,android-volley,Java,Android,Android Volley,我试图将hexmap转换成可用的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
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;
}
但现在我明白了:
{
"product": "{item_count=1, id=1}",
"user_id": "2"
}
我正在使用Volly库将数据表单应用程序传递到服务器。toString方法不会返回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;
}
HashMaptoString不会返回JSON,所以直接将foodOrder作为product的值。为什么不使用类似Map的东西呢?数组现在看起来很奇怪{product:{\item\u count\:\1\,\id\:\1\},user_id:2您是如何检查它的?这应该是因为用\来转义。但是应该是一个有效的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;
}