I would like to be able to parse a JSON file that is structured something like:
[
{
"id": 1,
"name": {
"first": "name",
"secound": "name",
"last": "name"
},
"skills": [
"python",
"javascript"
],
"otherInfo": {
"something": 45,
"something2": 49
}
},
{
"id": 2,
"name": {
"first": "name",
"secound": "name",
"last": "name"
},
"skills": [
"python",
"javascript"
],
"otherInfo": {
"something": 45,
"something2": 49
}
}
etc...
]
into something looking like
array(
[0] => array(
0 => "id"
1 => "firstname"
2 => "otherData"
),
[1] => array(
0 => "id"
1 => "firstname"
2 => "otherData"
),
etc...
)
I'm pretty sure i have an idea on how to convert it into the format I want, but im having trouble actually reading the data from the file.
The two major issues im having:
I tried some examples online, and a couple of the answers on this post but no luck the biggest issue is that all of them are giving examples for reading an external file, while I'm trying to read one that is packaged inside the jar.
My project tree:
MyProject
L src
L myPackage
L MyClass.java
L MyJsonFile.json
The closest thing that I'm guessing almost worked is this (from the link above):
import org.json.JSONArray;
//code
JSONArray myJSONArray = new JSONArray(Main.class.getResourceAsStream("myFile.json"));
But that only seems to throw an error: org.json.JSONException: JSONArray initial value should be a string or collection or array.
Thanks in advance!
The problem is org.json.JSONArray will only accept String
, Collection
or Array
but you are trying to pass the InputStream
object. which is what error messages also says
org.json.JSONException: JSONArray initial value should be a string or collection or array
So first convert the InputStream
into String
InputStream inputStream = Main.class.getResourceAsStream("myFile.json");
InputStreamReader isReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(isReader);
StringBuffer sb = new StringBuffer();
String str;
while((str = reader.readLine())!= null){
sb.append(str);
}
And then convert it into JSONArray
JSONArray myJSONArray = new JSONArray(sb.toString());
After here you can iterate the JSONArray
using for loop, like here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.