0

I have an unusual qustion which looks as the following:

Question 1: How can i split a String the right way so that i get the json-File Entries separated from one another.

Or Question: How do i convert a String to JSONArray.

The JSON:

[
   {
   "id":"123483",
      "content":{
         "amount":"460",
         "price":"2.15",
         "name":"Post-it Block weiß",
         "weight":"0.3",
         "category":"Notizzettel"
 } 
},
   {
      "id":"501993",
      "content":{
         "amount":"83",
         "price":"25.0",
         "name":"Trennstreifen 5x 100 bunt",
         "weight":"0.024",
         "category":"Register"

   }

}
]

What i tried: // content succesfully encapsulates all the json content.

Path path = Paths.get("src/com/json/inventory.json");
String content = new String(Files.readAllBytes(path), Charset.defaultCharset());


JSONArray jsonArray = new JSONArray(); 
JSONObject jsnobject = new JSONObject(content);
jsonArray.put(jsnobject);

The Errors with JSONArray: Errors

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245

2 Answers2

2

Your content is an array, not a single object.

Try new JSONArray(content);

Or use a library like Jackson or Gson to read the file into a list of POJO classes

Also note that the src folder does not exist at runtime for your code. The standard layout for placing resource files looks like this

src
  main
    java 
      Code.java 
  resources
    file.json

And you use ClassLoader to read the file

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • It did worked greatly, now i need to find a way to acces the contents within. What do i mean: if you do jsonArray.get(0) = you get the first Entrie in the json Array, however i seem to not be able to get things such as Id, content etc. You know how to do that? –  Feb 19 '20 at 14:51
  • I would recommend researching jsonpath – OneCricketeer Feb 19 '20 at 15:20
0

You must do new JSONArray(content); not new JSONObject(content);

Because if you do the second way, java try to cast the array into a single object.

You can see more information in this post

Adrian Lagartera
  • 442
  • 1
  • 3
  • 17