Home > Net >  Add contents of Array List to a JSON Array: Java
Add contents of Array List to a JSON Array: Java

Time:10-13

I have an Array List called getFields:

ArrayList getFields = new ArrayList(uniqueFields);

This array list logs out the following:

[{"warehouse":{"editableField":"false"}}, {"documentNo":{"editableField":"true"}}]

I need to convert getFields into a JSON Array called jsArray, so I have done this:

JSONArray jsArray = new JSONArray();
jsArray.put(getFields);

jsArray logs out the following:

[[{"warehouse":{"editableField":"false"}},{"documentNo":{"editableField":"true"}}]]

The problem is, I do not want jsArray to have a nested array (i.e. I don't want it to have double square brackets). I want it to be like this:

[{"warehouse":{"editableField":"false"}},{"documentNo":{"editableField":"true"}}]

How can I convert getFields into jsArray without the double brackets? Have tried converting to a string but then I get backslashes. Any help would be appreciated. Thanks.

CodePudding user response:

getFields.forEach(jsArray::put);  // java 8 

You need to iterate on getFields and put the elements one by one.


// java 8 or below
for (int i = 0; i < getFields.size(); i  ) {
    jsArray.put(getFields.get(i));
}
  • Related