0

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
3
  • You should use jsonObj instead of String objects check this POST. Commented Feb 5, 2016 at 13:23
  • @NAIT No, still same problem. add function doesn't work. Commented Feb 5, 2016 at 13:33
  • can you post what you tried please ? Commented Feb 5, 2016 at 13:35

3 Answers 3

0

You may add Json object instead of adding string object.

JSONObject jsonObj = new JSONObject("{\""string",\":\"{}\"}");
JSONArray array = new JSONArray();
array.add(jsonObj);
Sign up to request clarification or add additional context in comments.

Comments

0

Make sure you are using correct JSONArray. The example you posted uses

import org.json.simple.JSONArray;

1 Comment

That was the first thing I checked.
0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.