我有一些要转换为json对象的数据。我想要的数据就像
{"week":"Apr 22, 2019","package_id":23,"weekdata":["2019-05-07##14:00##16:45"]}
工作日是数组类型,其他是json对象类型。我已经完成了一些代码来对其进行转换,但是我能够像
一样对其进行转换{"weekdata":"[\"2019-04-01##5:0##5:0\",\"2019-04-02##5:0##5:0\"]","package_id":"44","week":"Apr 01, 2019"}
此代码:
用于创建weekdata数组的代码:
String firstDay = etDate1.getText().toString() + "##" + etStartTime1.getText().toString() + "##" + etEndTime1.getText().toString();
String secondDay = etDate2.getText().toString() + "##" + etStartTime2.getText().toString() + "##" + etEndTime2.getText().toString();
selectionItems.add(firstDay);
selectionItems.add(secondDay);
String[] blist = new String[selectionItems.size()];
Log.e("tag", "array" + blist.length + selectionItems);
for (int i = 0; i < selectionItems.size(); i++) {
blist[i] = selectionItems.get(i);
}
Log.e("tag", "arrayList" + blist[0]);
weekdata = new JSONArray();
for (int i = 0; i < blist.length; i++) {
weekdata.put( blist[i] );
}
转换为json以将其发送到截击中:
HashMap<String, String> params = new HashMap<String, String>();
params.put("package_id", package_id);
params.put("week", weekName);
params.put("weekdata",weekdata.toString() );
JSONObject obj = new JSONObject(params);
我得到像这样的数据:
{"weekdata":"[\"2019-04-01##5:0##5:0\",\"2019-04-02##5:0##5:0\"]","package_id":"44","week":"Apr 01, 2019"}
如何将其转换为以下格式:
{"week":"Apr 22, 2019","package_id":23,"weekdata":["2019-05-07##14:00##16:45"]}
请帮助。
答案 0 :(得分:0)
之所以会这样,是因为您已将Map定义为Map,并使用toString()方法将列表转换为String。使用生成您的String。您应该将Map定义为Map,并且在将其放入Map时不要使用toString方法。
代码:
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("package_id", package_id);
params.put("week", weekName);
params.put("weekdata",weekdata);
JSONObject obj = new JSONObject(params);
这里的一个问题是,为什么要使用Map?有什么特殊原因吗?
您可以直接从JSONObject创建JSON。
示例代码:
JSONObject jsonObject = new JSONObject();
jsonObject.put("package_id", package_id);
jsonObject.put("week", weekName);
jsonObject.put("weekdata",weekdata);
使用JSONObject,您不必担心泛型。
答案 1 :(得分:0)
根据您的问题,
{“ week”:“ Apr 22,2019”,“ package_id”:23,“ weekdata”:[“ 2019-05-07 ## 14:00 ## 16:45”]}
String firstDay = etDate1.getText().toString() + "##" +
etStartTime1.getText().toString() + "##" + etEndTime1.getText().toString();
String secondDay = etDate2.getText().toString() + "##" +
etStartTime2.getText().toString() + "##" + etEndTime2.getText().toString();
selectionItems.add(firstDay);
selectionItems.add(secondDay);
String[] blist = new String[selectionItems.size()];
Log.e("tag", "array" + blist.length + selectionItems);
for (int i = 0; i < selectionItems.size(); i++) {
blist[i] = selectionItems.get(i);
}
Log.e("tag", "arrayList" + blist[0]);
JsonArray weekdata = new JSONArray();
for (int i = 0; i < blist.length; i++) {
weekdata.put( blist[i] );
}
After this wrap this in the JsonObject
JsonObject jsonObject = new JsonObject();
jsonObject.put("package_id", package_id);
jsonObject.put("week", weekName);
jsonObject.put("weekdata",weekdata);
Log.e("jsonResult",jsonObject.toString());
尝试一下,让我知道@mishti。