-1

[techno: java spring boot]

there is a file .txt containing :

{ "foo": "one" }
{ "bar": "two" }
  1. In java, is there a way to transform the content file in json like this ? :
[
{ "foo": "one" },
{ "bar": "two" }
]
  1. Or get each line via a loop
loop(contentFile as line) {
 // line = { "foo": "one" }
}
nico38
  • 29
  • 6

2 Answers2

0

You could iterate over every line, then try to parse the content of the line into an JSONObject, and collect all those JSONObjects into a JSONArray, and then write the serialized Array into your json-file.

For example with json-simple, or with javax.json.

0

You can read file in Java line by line like below:

try {
    BufferedReader reader = new BufferedReader(new FileReader(path-to-json-file));
    String line = reader.readLine(); //here line = { "foo": "one" }
    while (line != null) {
        //do required opertaion and read next line
        line = reader.readLine();
    }
    reader.close();
} catch (IOException e) {
    e.printStackTrace();
}
Armen Michaeli
  • 8,625
  • 8
  • 58
  • 95
Nitin Zadage
  • 633
  • 1
  • 9
  • 27
  • Tell me -- what is the benefit of catching the exception (an *exceptional*, often fatal, condition unless *properly* handled) and just printing the stack trace? Hint: NEVER do that. If I would have seen such code in production, I'd raise a code review alert. Printing a stack trace and just moving on is *not* handling an exceptional condition. It also doesn't add any value to your example, on the contrary it draws the reader's attention to some extra code they have to read which has in itself nothing to do with parsing JSON text. – Armen Michaeli Nov 15 '19 at 10:10
  • @amn This is sample code and not full implementation. Whosoever needs to use code can have their custom exception handling in place. – Nitin Zadage Nov 15 '19 at 12:04
  • I understand this is sample code -- you can't possibly write full implementation given as little context as there is in the question. However, with that unnecessary try-catch block, you make it worse for pretty much everyone to use your code -- those who know how to use exceptions will have to remove or adapt the try catch block anyway -- fitting their application. And those who don't will be left with a program that simply prints the stack trace and moves on. Exceptions signal well, exceptional conditions -- if you're going to just eat them up by printing something, the whole benefit is gone. – Armen Michaeli Nov 16 '19 at 14:16