Search code examples
json-simple

How to make a constant json array with JSON Simple


I'm looking to make a very simple object with JSONSimple, that uses a constant array:

{
 "user":"fei0x",
 "permissions":[10,20]
}

How do I construct the array portion?

I tried to use a primitive array, but instead it creates an object with each element it's own attribute.

myJsonObj.put("permissions", [10,20] );

produces

{
 "user":"fei0x",
 "permissions":
    {
      "0":10,
      "1":20
    }
}

Solution

  • You need to create JSONArray object to put array node

    JSONObject obj = new JSONObject();
    obj.put("user", "fei0x");
    
    // if you have const array then loop over to add elements in following object
    JSONArray list = new JSONArray();
    
     //loop over
    for (int index=0; index < constArray.length; index++) {
       list.add(constArray[index]);
    }
    
    obj.put("permissions", list)