JSON Simple – Encoding Array Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of JSON Simple – Encoding Array without wasting too much if your time.

The question is published on by Tutorial Guruji team.

Hi I am using JSON simple library. I have a JSON file like this:


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();

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

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(new Integer(100)); 
list.add(new Double(1000.21)); 
list.add(new Boolean(true)); 
String jsonText = JSONValue.toJSONString(list); 

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.

We are here to answer your question about JSON Simple – Encoding Array - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji