Search code examples
javajsongsonpretty-print

How to parse prettyprinted JSON with GSON


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...


Solution

  • 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.