简体   繁体   中英

Convert list<MapObject> into JSONObject

I have a list of RequestBodyObject , something like this:

List<RequestBodyObject> body = new ArrayList<>();

RequestBodyObject is something like this:

Map<String, String> requestBodyElements;

I am creating HashMap something like below:

    HashMap<String, Object> params = new HashMap<>();
    
    Map<String, String> requestBodyElements = new HashMap<>();
    List<RequestBodyObject> body = new ArrayList<>();
    
    requestBodyElements.put("xyz", "abc");
    requestBodyElements.put("def", "pqr");
    
    RequestBodyObject requestBodyObject = new RequestBodyObject();
    requestBodyObject.setRequestBodyElements(requestBodyElements);
    body.add(requestBodyObject);
    
    params.put("key1", body);
    params.put("key2", "value2");

Now I want to convert it to JSONObject to pass as a request body in a REST call

I am trying to do something like this but not able to pass Map as a List

private static JSONObject getJsonFromMap(Map<String, Object> map) throws JSONException {
    JSONObject jsonData = new JSONObject();
    for (String key : map.keySet()) {
        Object value = map.get(key);
        if (value instanceof Map<?, ?>) {
            value = getJsonFromMap((Map<String, Object>) value);
        }
        jsonData.put(key, value);
    }
    return jsonData;
}

Desired JSONObject is:

{
   "format":"HTML",
   "requestBodyElements":[
    {
       "abc":"zyv",
       "def":"ghi"
     }]
  }

My function was able to make it something like:

{
   "format":"HTML",
   "requestBodyElements":
    {
       "abc":"zyv",
       "def":"ghi"
     }
  }

I need to convert requestBodyElements into array of elements. Any help much appreciated

There is a class JSONArray which can be used to represent an Array [] json value. I think you can consider using it. Code can look like this:

private static JSONArray getJsonFromMap(Map<String, Object> map) {
    JSONObject jsonData = new JSONObject();
    for (String key : map.keySet()) {
        Object value = map.get(key);
        if (value instanceof Map<?, ?>) {
            value =  getJsonFromMap((Map<String, Object>) value);
        }
        jsonData.put(key, value);
    }
    JSONArray jsonArray = new JSONArray();
    jsonArray.add(jsonData);
    return jsonArray;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM