I have an Array List called getFields:
JavaScript
x
ArrayList getFields = new ArrayList(uniqueFields);
This array list logs out the following:
JavaScript
[{"warehouse":{"editableField":"false"}}, {"documentNo":{"editableField":"true"}}]
I need to convert getFields into a JSON Array called jsArray, so I have done this:
JavaScript
JSONArray jsArray = new JSONArray();
jsArray.put(getFields);
jsArray logs out the following:
JavaScript
[[{"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:
JavaScript
[{"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.
Advertisement
Answer
JavaScript
getFields.forEach(jsArray::put); // java 8+
You need to iterate on getFields
and put the elements one by one.
JavaScript
// java 8 or below
for (int i = 0; i < getFields.size(); i++) {
jsArray.put(getFields.get(i));
}