-1

Can some one please help me where I am wrong in my code:

public void request_Body_From_Data(String json, DataTable requestBody)   throws Throwable {
    List<Map<String, String>> body = requestBody.asMaps(String.class, String.class);
    String converted_Json = convert_listmap_to_json_string(body);
    printJson(converted_Json);
}

public String convert_listmap_to_json_string(List<Map<String, String>> map) {
    JSONArray json_arr = new JSONArray();
    for (Map<String, String> list : map) {
        JSONObject json_obj = new JSONObject();
        for (Map.Entry<String, String> entry : list.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            try {
                if (key.equals("C")) {
                    break;
                } else {
                    json_obj.put(key, value);
                }
            } catch (JSONException jsone) {
                jsone.printStackTrace();
            }
            json_arr.put(json_obj);
        }
    }
    return json_arr.toString();
}

Question:

I would like to convert JSON, which are coming in list to Maps.

And I am reading List from Cucumber feature file. Feature file looks like below:

   | A        | B    | C  |
  | trade     | test | ID |
  | Code      | 789  | ORDER|

I got below json format: [{"B":"test","A":"trade"},{"B":"test","A":"trade"}

Expected result should be:

"A": {
  "trade": "test",
  "Code": "789",
  }
MWiesner
  • 8,868
  • 11
  • 36
  • 70
Eric
  • 23
  • 5

1 Answers1

0

Use Jackson Library. You can simply do this:-

ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT); // If pretty-print is required
System.out.println(mapper.writeValueAsString(body));
Kaushik
  • 3,371
  • 3
  • 23
  • 32