Java 将两个映射字符串组合成JSON
以下是我所期望的JSON字符串:Java 将两个映射字符串组合成JSON,java,json,Java,Json,以下是我所期望的JSON字符串: { "startDate": "2013-01-01", "columns": "mode , event", "endDate": "2013-02-01", "selection": { "selectionMatch": "123456789012", "selectionType": "smart" } } 下面是JAVA代码,但我没有成功: public static Strin
{
"startDate": "2013-01-01",
"columns": "mode , event",
"endDate": "2013-02-01",
"selection": {
"selectionMatch": "123456789012",
"selectionType": "smart"
}
}
下面是JAVA代码,但我没有成功:
public static String BuildJson() throws JSONException{
Map<String, String> map1 = new HashMap<String, String>();
map1.put("startDate", "2013-01-01");
map1.put("endDate", "2013-02-01");
map1.put("columns", "mode , event");
Map<String, String> map2 = new HashMap<String, String>();
map2.put("selectionType", "smart");
map2.put("selectionMatch", "123456789012");
JSONArray ja2 = new JSONArray();
ja2.put(map2);
System.out.println(ja2.toString());
map1.put("selection", ja2.toString());
System.out.println();
JSONArray ja = new JSONArray();
ja.put(map1);
System.out.println(ja.toString());
return null;
}
有人能帮我吗?这是你想要的代码
JSONObject object = new JSONObject(map1);
object.put('selection', map2);
System.out.println(object.toString());
public static String BuildJson() throws JSONException
{
JSONObject map1 = new JSONObject();
map1.put("startDate", "2013-01-01");
map1.put("endDate", "2013-02-01");
map1.put("columns", "mode , event");
JSONObject map2 = new JSONObject();
map2.put("selectionType", "smart");
map2.put("selectionMatch", "123456789012");
map1.put("selection",map2);
System.out.println(map1.toString());
return null;
}
输出将是
{
"startDate":"2013-01-01",
"columns":"mode , event",
"endDate":"2013-02-01",
"selection":{
"selectionMatch":"123456789012",
"selectionType":"smart"
}
}
使用JSONObject而不是Map,如果您需要JSONArray,您也可以使用它。它可以工作!非常感谢你,这花了我很多时间。我不熟悉JSONObject,所以现在您给了我完全正确的方向,我将浏览api。
{
"startDate":"2013-01-01",
"columns":"mode , event",
"endDate":"2013-02-01",
"selection":{
"selectionMatch":"123456789012",
"selectionType":"smart"
}
}