How to build a JSONObject with a JSONArray?

Marcos Garcia :

im kinda new using JSON, and everything was fine until i have to make this JSON format.

"function":"ListarHoteles", "parameters":[""]

Right now my code:

        JSONObject JSONarr = new JSONObject();
        JSONArray pam = new JSONArray();
        jo.put("function", "ListarHoteles");
        pam.add(" ");

        JSONObject mainOBJ = new JSONObject();
        mainOBJ.put("parameters", pam);  

And im receiving: {"{\"function\":\"ListarHoteles\"}":{},"parameters":[" "]} Thank you

huytc :

Is this what you want?

JSONObject jsonObject = new JSONObject();
jsonObject.put("function", "ListarHoteles");
JSONArray arr = new JSONArray();
arr.add("");
jsonObject.put("parameters", arr);

System.out.println(jsonObject.toString(2));

Output:

{
    "function":"ListarHoteles",
    "parameters":[
      ""
    ]
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=18573&siteId=1