skip to Main Content

I have a pretty complex objects(I’m not posting the code because of that) I’m trying to serialize with these calls:

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    PrintWriter output = new PrintWriter(new FileOutputStream("Hotels.json"));
    output.write(gson.toJson(myObject););

The program terminates with no failure but the output I get is not complete and after ~8000 lines ends like this:

            ],
        "rate": 1.5,
        "ratings": {
          "cleaning": 1.5,
          "position": 4.0,
          "services": 1.5,
          "quality": 2.0
        },
        "rankScore": 1.5,
        "reviewsNum": 2,
        "reviews"

With a lot of data missing and brackets left unclosed.
I tried to make sure no circular references were present, but even if there were it still seems strange that no exception is being thrown.
Someone knows what might be happening?

2

Answers


  1. It is hard to analyze this problem without the complete code. I suggest that you try to reproduce the problem with a unit test or "small" program that does nothing else.

    No database access, etc., just create the object tree "manually" in the code and serialize it. A unit test would then have to compare the result not in a file but in a String against an expected string, so you may want to start without a real test, but with a small program that writes the file and you can check it manually.

    Then reduce the object structure that you serialize – I would try it with just "half" the size, but it really depends on your structure. Try to find out if there is a change that "switches" from a weird result to a result that is reasonable. Maybe this is then small enough that you can post it here with a reproducible example, or you find an error in GSon or in your own object structure.

    Login or Signup to reply.
  2. You can use Gson.toJson(Object, Appendable) in combinattion with try-with-resouces to simplify the writing – no need to reinvent the wheel, use provided functionality to take care of the actual writing, closing and releasing resources, etc.

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    try (PrintWriter output = new PrintWriter(new FileOutputStream("Hotels.json"))) {
      gson.toJson(obj, output);
    } catch (FileNotFoundException exc) {
      throw new RuntimeException(exc);
    }
    

    As a bonus this approach won’t load the entire json string in memory, but will write it in chunks. Still, Gson documentation does not guarantee you such behaviour, but any sensible implementation will do it like this.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search