0

I'm trying to create a JSONArray but having difficulties cause the format I need to create is as follows:

"header": [
    {
        "name": "x",
        "id": "x",
        "boolean": "false",
        "data": {
            "x": {
                "a": "05",
                "b": "01" ,
                "c": "246",
                "d": "Y"
            }
        }
    }
]
2
  • How does this relate to testing or QA? This seems more like a question for StackOverflow.
    – Lee Jensen
    Mar 30 at 13:58
  • Voted to reopen , the question is closely related to restassured or any other tools
    – PDHide
    Mar 31 at 7:08
0
package extendreport_2;

import org.json.JSONException;
import org.json.JSONObject;

public class printsomething {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
        try {
             JSONObject jsonObject = new JSONObject("{\"header\": [\r\n" + 
                    "    {\r\n" + 
                    "        \"name\": \"x\",\r\n" + 
                    "        \"id\": \"x\",\r\n" + 
                    "        \"boolean\": \"false\",\r\n" + 
                    "        \"data\": {\r\n" + 
                    "            \"x\": {\r\n" + 
                    "                \"a\": \"05\",\r\n" + 
                    "                \"b\": \"01\" ,\r\n" + 
                    "                \"c\": \"246\",\r\n" + 
                    "                \"d\": \"Y\"\r\n" + 
                    "            }\r\n" + 
                    "        }\r\n" + 
                    "    }\r\n" + 
                    "]}");
             System.out.println("output: "+ jsonObject.toString(2));
        }catch (JSONException err){
            System.out.println("Error: "+ err.toString());
        }

    }

}

you can use jsonarray and jsonobject separately but easier method would be to convert string to jsonobject as shown above

if you still want to do it :

    JSONObject headerarray = new JSONObject();
    JSONObject xobject = new JSONObject();
    JSONObject dataobject = new JSONObject();
    JSONObject headerarrayitem1 = new JSONObject();
    
    
    
    xobject.put("a", "05");
    xobject.put("b", "01");
    xobject.put("c", "246");
    xobject.put("d", "Y");
    
    dataobject.put("x", xobject);
    
    headerarrayitem1.put("name", "x");
    headerarrayitem1.put("id", "x");
    headerarrayitem1.put("boolean", "false");
    headerarrayitem1.put("data", dataobject);
    
    headerarray.append("header",headerarrayitem1);
            
    System.out.println(headerarray.toString(2));
1
  • 1
    Works like a charm! Thanks! Mar 31 at 1:25

Not the answer you're looking for? Browse other questions tagged or ask your own question.