1

I'm connecting to some APIs. These calls return an already "prettyprinted" JSON instead of a one-line JSON.

Example:

[
  {
    "Field1.1": "Value1.1",
    "Field1.2": "value1.2",
    "Field1.3": "Value1.3"
  },
  {
    "Field2.1": "Value2.1",
    "Field2.2": "value2.2",
    "Field2.3": "Value2.3"
  }
]

When I try to parse a JSON like this with GSON it throws JsonSyntaxException.

Code example:

BufferedReader br = /*Extracting response from server*/
JsonElement jelement = new JsonParser().parse(br.readLine())

Is there a way to parse JSON files formatted like this?

EDIT:

I tried using Gson directly:

BufferedReader jsonBuf = ....
Gson gson = new Gson();
JsonObject jobj = gson.fromJson(jsonBuf, JsonObject.class)

But jobj is NULL when the code terminates.

I also tried to parse the string contained into the BufferedReader into a single line string and then using JsonParser on that:

import org.apache.commons.io.IOUtils
BufferedReader jsonBuf = ....
JsonElement jEl = new JsonParser().parse(IOUtils.toString(jsonBuf).replaceAll("\\s+", "");

But the JsonElement I get in the end is a NULL pointer...

I can't understand what I'm doing wrong...

jackscorrow
  • 682
  • 1
  • 9
  • 27

1 Answers1

1

BufferedReader::nextLine reads only one line. Either you read whole json from your reader to some String variable or you will use for example Gson::fromJson(Reader, Type) and pass reader directly to this method.

As your json looks like an array of json objects it can be deserialized to List<Map<String,String>> with usage of TypeToken :

BufferedReader bufferedReader = ...
Type type = new TypeToken<List<Map<String,String>>>(){}.getType();
Gson gson = new Gson();
List<Map<String,String>> newMap = gson.fromJson(bufferedReader, type);

You could also use some custom object instead of Map depending on your needs.

Michał Krzywański
  • 15,659
  • 4
  • 36
  • 63
  • If I use Gson::fromJson(Reader, Type) do I have to specify the exact types and subtypes? Because the one I posted is just an example to show how the JSON I get is formatted, the structure can be more complex and I can't know it before parsing the JSON – jackscorrow Jul 18 '19 at 07:20
  • You have to handle this json somehow. Either you read it to pure `String` (but this is not handy at all), you use some available type like `Map` or `List` of Strings or you create a custom POJO class for your json. If you do not know the structure of your json before parsing a `Map` might be suitable. – Michał Krzywański Jul 18 '19 at 18:45
  • I followed your suggestion eventually. I used a JsonArray instead of a custom type and it worked – jackscorrow Jul 22 '19 at 10:25