Hi I am using JSON simple library. I have a JSON file like this:
[
"string",
{
...
},
{
...
}
...
]
I have no problem parsing it. But when I finish my application and try to save the changes I cannot add a string to new JSONArray.
JSONArray array = new JSONArray();
array.add("string");
It gives me add(E) in ArrayList cannot be applied to (java.lang.String)
error.
There is no put
method in the JSONArray class.
The solution might be converting JSONObject to JSONArray. But how?
Or could I parse the file and change the contects and then overwrite the original file with it?
Look at the Example 2-1
https://code.google.com/archive/p/json-simple/wikis/EncodingExamples.wiki
EDIT: Using the code below always gives an error. I believe JSONArray object is not intented for encoding. I used a LinkedList instead.
JSONObject obj = new JSONObject();
JSONArray array = new JSONArray();
array.add("string"); // gives error
array.add(obj); // gives error
LinkedList list = new LinkedList();
list.add("foo");
list.add(new Integer(100));
list.add(new Double(1000.21));
list.add(new Boolean(true));
list.add(null);
String jsonText = JSONValue.toJSONString(list);
System.out.print(jsonText);
Instead of creating an JSONArray
object and adding other objects to it, we can create a LinkedList
.
Then use it as we intent to use a JSONArray
object. And finally we can convert it to JSON string.
Problem might be as the error text suggest, JSONArray which extends ArrayList don't have a template set. It is still default E
. So when you try to add an object to ArrayList, it gives an error because the object is not an instance of E
. And JSONArray class doesn't accept template.
JSONArray<String> array = new JSONArray<String>();
Just doesn't work.