我编写了以下代码,以便将ArrayList输出为JSON。运行代码时,我得到如下所示的输出:


  {uniteids:= [{“ UniteId:”:“ gsheetyr”,“消息:”:“给定的用户已经是给定DL的成员。”},{“ UniteId:”:“ spokuri”,“消息: “:”给定的用户已经是给定DL的成员。“}]}


但是,我希望输出采用以下格式。您能否让我知道我需要对代码进行哪些更改?


  {“ uniteids”:[{“ UniteId:”:“ gsheetyr”,“消息:”:“给定的用户已经是给定DL的成员。”},{“ UniteId:”:“ spokuri”,“消息:“:”给定的用户已经是给定DL的成员。“}]}


码:

package com.uniteid.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;

public class JsonResponse {

  public static void main(String[] args) {
    List<String> retStatus = new ArrayList<String>();
    Map<String, String> stat = new HashMap<String, String>();
    String jsonInString = "NORESPONSE";
    String jsonInString2 = "";
    Map<String, String> uniteidshashMap = new HashMap<String, String>();
    JSONArray ja = new JSONArray();
    retStatus.add("gsheetyr: The given user is already a member of the given DL.,");
    retStatus.add("spokuri : The given user is already a member of the given DL.,");

    if (retStatus.size() > 0) {
        for (int i = 0; i < retStatus.size(); i++) {
            String splited[] = retStatus.get(i).split("\\:");

            stat.put("UniteId:", splited[0]);
            stat.put("Message:",splited[1]);
            ja.put(stat);

            System.out.println(ja);
        }

        jsonInString = ja.toString();
        uniteidshashMap.put("uniteids:", jsonInString);
        jsonInString2 = uniteidshashMap.toString();

        System.out.println(jsonInString2);
    }
  }
}

最佳答案

尝试这个

JSONArray arrayHolder = new JSONArray();
if (retStatus.size() > 0) {
    for (int i = 0; i < retStatus.size(); i++) {
        String splited[] = retStatus.get(i).split("\\:");

        JSONObject innerObj = new JSONObject();

        innerObj.put("UniteId:", splited[0]);
        innerObj.put("Message:",splited[1]);
        arrayHolder.put(innerObj);
    }

    JSONObject finalObject = new JSONObject();
    finalObject.put("uniteids:", arrayHolder);

    System.out.println(finalObject.toString());
}

10-05 20:33