Search code examples
rest-assured

How to pass an array object in post request


I am new to rest assured and trying to pass the following body in the post request.

JSON Payload :

{
    "apikey": "****",
    "collectortoken": "***",
    "medium": "*",
    "uniquekey": "tcode",
    "contacts": [{
            "email": "[email protected]",
            "tcode": "2597566"
        },
        {
            "tcode": "9990"
        }
    ]
}

I even had tried the following code:

    JSONObject obj = new JSONObject();
    
    obj.put("apikey", "****");
    
    obj.put("collectortoken", "***");

    obj.put("medium", "2");

    obj.put("uniquekey", "tcode");

    obj.put("contacts", Arrays.asList(new LinkedHashMap<String, String>() {
        
        {
                
            put("email",name);

            put("tcode",tcode);
        }
        {

            put("tcode",tcode);
        }

Can someone help me on this.

Thanks


Solution

  • A couple of ways you can generate this payload, JSONObject / Map / Serialization

    Using JSONObject :

    import org.json.simple.JSONArray;

    import org.json.simple.JSONObject;

    JSONObject jo = new JSONObject();
    jo.put("email", "[email protected]");
    jo.put("tcode", "2597566");
    
    JSONObject jo1 = new JSONObject();
    jo1.put("tcode", "9990");
    
    JSONArray ja = new JSONArray();
    ja.add(jo);
    ja.add(jo1);
    
    JSONObject mainObj = new JSONObject();
    mainObj.put("apikey", "123");
    mainObj.put("collectortoken", "456");
    mainObj.put("medium", "2");
    mainObj.put("uniquekey", "tcode");
    mainObj.put("contacts", ja);
    

    Using Map :

    LinkedHashMap<String, Object> map = new LinkedHashMap<>();
    map.put("apikey", "124");
    map.put("collectortoken", "456");
    map.put("medium", "789");
    map.put("uniquekey", "111");
    
    map.put("contacts", Arrays.asList(new LinkedHashMap<String, Object>() {
        {
            put("email", "[email protected]");
            put("tcode", "2597566");
        }
    }, new LinkedHashMap<String, Object>() {
        {
            put("tcode", "9990");
        }
    }));