This line
error : Unexpected character (N) at position 0.
in your 2nd way code fragment / quote kind of states that you're parsing invalid JSON.
JSONObject name1 = (JSONObject) parser.parse(key);
the key
in this line probably contains invalid JSON. That is why the parser throws an exception.
You can try to debug the code and see what the key
strings look like and you should find out which one (if not all) contain invalid JSON.
I created a minimalistic program which parses a valid JSONArray
(or a JSONObject
, if the file contains only a single JSON object) from a file (which you mentioned under @Sepx3's answer). I tried to use names from your code snippets for the relevant code, so that it stays a bit clear.
The content of my C:/Users/Envy/Documents/company.json
example file:
[
{
"key": "value"
},
{
"key1": "value1"
},
[
{
"key2": "value2"
},
{
"key3": "value3"
}
]
]
And the code which parses it, stores it into the object and then checks whether a JSONArray
or a single JSONObject
has been parsed (in my example it is a JSONArray
).
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.FileReader;
public class DemoApplication {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
Object obj = null;
try {
obj = parser.parse(new FileReader("C:/Users/Envy/Documents/company.json"));
} catch (Exception e) {
// Handle possible exceptions
e.printStackTrace();
}
// If the parsed string was a single json object
if (obj instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) obj;
// Do something with jsonObject, in this example it prints the content of jsonObject
System.out.println(jsonObject);
}
// Or else if the parsed string was a json array
else if (obj instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) obj;
// Do something with jsonArray, in this example it prints the content of jsonArray
System.out.println(jsonArray);
}
}
}
I hope this helps you at least a bit and sets you on the right track.