Search code examples
javajsonparsingpretty-printorg.json

Cannot correctly pretty print entire JSON array with JSON libraries in Java


I have an unformatted JSON string which I want to format using Java. I already added the org.json dependency and I wrote the following code:

String json = "[{...}, {...}]"; // Placeholder for my actual large JSON array string
JsonArray jsonArray = new JSONArray(json);
json = jsonArray.toString(4);

After formatting, the JSON became much smaller than it should be (originally ~10MB, after formatting ~3MB).

Why? Clearly, a lot of data is missing.

I also tried Gson but it failed with

Caused by: com.google.gson.JsonIOException: Failed making field 'java.io.Reader#lock' accessible; either increase its visibility or write a custom TypeAdapter for its declaring type.
    at com.google.gson.internal.reflect.ReflectionHelper.makeAccessible(ReflectionHelper.java:38)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:286)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:130)
    at com.google.gson.Gson.getAdapter(Gson.java:556)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:160)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:294)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:130)
    at com.google.gson.Gson.getAdapter(Gson.java:556)
    at com.google.gson.Gson.toJson(Gson.java:834)
    at com.google.gson.Gson.toJson(Gson.java:812)
    at com.google.gson.Gson.toJson(Gson.java:759)
    at com.google.gson.Gson.toJson(Gson.java:736)

since I'm using Java 19.

Used code:

Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonReader jsonReader = new JsonReader(new StringReader(json));
jsonReader.setLenient(true); // Enable lenient mode to handle malformed JSON
json = gson.toJson(jsonReader);

Finally, I tried Jackson:

ObjectMapper mapper = new ObjectMapper();
json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(mapper.readTree(json));

Same problem as org.json, the output JSON is about 1/3 of the original.


Solution

  • My mistake ended up being that I concatenated different JSONs into a big JSON in the wrong way by doing e.g. "[{...}, {...}]" + "[{...}, {...}]" ... Of course, that didn't work correctly and JSON parsing stopped after the first array as expected. After fixing my concatentation logic, even the 10MB JSON is parsed and formatted correctly using e.g. the Jackson library.