我必须以下面的格式在Http请求中发送请求正文:
{
"flag":false,
"Ids":["xyz","abc"]
}
我当时想:
LinkedHashMap<String, Object> requestParamsMap = new LinkedHashMap<String, Object>();
requestParamsMap.put("flag",false);
ArrayList<String> IdList = new ArrayList<>();
IdList.add("xyz");
IdList.add("abc");
requestParamsMap.put("Ids", IdList.toString());
然后我将requestParamsMap转换为json字符串。但我没有得到所需格式的请求正文。
我想创建一个通用的方法,它可以返回这种格式的数据,这样我就可以在整个应用程序中使用它。
任何帮助将不胜感激.. !!!
答案 0 :(得分:0)
做这样的事情:
JSONObject object=new JSONObject();
try {
object.put("flag","xyz");
JSONArray array=new JSONArray();
array.put("xyz");
array.put("abc");
object.put("Ids",array);
//added a log to see the output
Log.e("output",object.toString());
} catch (JSONException e) {
e.printStackTrace();
}
object.toString()
应该包含字符串格式所需的json。您可以使用循环来填充jsonArray或JSONObject的内容,具体取决于您拥有的项目数
答案 1 :(得分:0)
尽管如此,你想要的输出是JSONObject中的JSONArray和另一个JSONObject中的JSONObject。所以,你可以单独创建它们然后可以放在一起。如下。
<强> CODE 强>
try {
JSONObject parent = new JSONObject();
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
jsonArray.put("lv1");
jsonArray.put("lv2");
jsonObject.put("mk1", "mv1");
jsonObject.put("mk2", jsonArray);
parent.put("root", jsonObject);
Log.d("output", parent.toString(2));
} catch (JSONException e) {
e.printStackTrace();
}
<强>输出强>
{
"root": {
"mk1": "mv1",
"mk2": [
"lv1",
"lv2"
]
}
}