2

これが私が期待したJSON文字列です:

{
    "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;
}

課題は、同じレベルにない 2 つのマップ文字列をどのように組み合わせるかです。私のコードの結果は次のとおりです。

[{"startDate":"2013-01-01","columns":"mode , event","endDate":"2013-02-01","selection":"[{\"selectionMatch\":\"123456789012\",\"selectionType\":\"smart\"}]"}]

誰かがそれを手伝ってくれますか?

4

2 に答える 2

3

これがあなたが望むコードです、

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"
   }
}

JSONArray が必要な場合は、Map の代わりに JSONObject を使用してください。それも使用できます。

于 2013-08-20T16:36:22.297 に答える