0

I want to read a JSON object from a JSON file in Java, as a string without any processing. The problem is that in the JSON file, the objects are not on a single line. (else it would have been easy to read them with scanner.nextLine() ) Also, in the program I will need to read the objects based on their ID, which is one of the object key.

If I map them to the corresponding POJO, later to convert it into a JSON string, I'll end up with a default value for attributes not present in a particular object and the key-value pair will show up in the string, which I don't want. I just need the original string as it as.

Any suggestion on the approach I can go with?

Thanks in advance!

Kuldeep Ghate
  • 231
  • 1
  • 2
  • 8
  • Possible duplicate of [How to parse JSON in Java](http://stackoverflow.com/questions/2591098/how-to-parse-json-in-java) – michaelsnowden Jul 29 '16 at 00:57
  • You will either need to give meaningful values for "not present" in your POJO, make a different POJO for each object, or use a parser that allows arbitrary JSON. (Unless you want to write code that looks at tokens from `JsonParser`) – 4castle Jul 29 '16 at 01:07

1 Answers1

0

Assuming your problem is as stated in your sentence:

The problem is that in the JSON file, the objects are not on a single line

There is a way to read the whole file as a single String using a Scanner:

String contents = scanner.useDelimiter("\\Z").next();

The pattern \Z means "end of input", so the entire InputStream is read to the end.

To remove linefeed chars, replacing them with a space, so you get a single line to parse:

String contents = scanner.useDelimiter("\\Z").next().replaceAll("\\R+", " ");
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • @4castle right. `\Z` is probably less obtuse. I'll edit that in. – Bohemian Jul 29 '16 at 01:01
  • Thanks for the reply. Agreed I'll get the whole file contents in the string. But I want to retrieve any particular object from that string based on the ID. How can I do that? – Kuldeep Ghate Jul 29 '16 at 04:02