-2

I use Jackson to create a JSON file which I forward to a foreign REST service. It took me some hours to find out that that service is very sensitive to how the JSON file is formatted.

This is accepted:

[
  {
    "email": "foo.bar1@domain.com"
  },
  {
    "email": "foo.bar2@domain.com"
  }
]

This (and this is the default behavior of the Jackson pretty printer) is not accepted and causes the REST call to fail:

[ {
  "email": "foo.bar1@domain.com"
}, {
  "email": "foo.bar2@domain.com"
} ]

Can I configure Jackson to use the other format ? Let me stress this: I know that the author of the receiving REST service should fix this but this is out of my range.

There are questions in the field of custom Pretty Printers for Jackson like this one. But perhaps there is a custom made already.

Marged
  • 10,577
  • 10
  • 57
  • 99
  • I think you would have to go with custom implementation of `PrettyPrinter` interface. – Michał Krzywański Jan 30 '20 at 13:48
  • You should check this question https://stackoverflow.com/questions/39475967/serialize-jsonnode-to-a-very-specific-json-format-in-jackson – creekorful Jan 30 '20 at 13:49
  • 1
    Question should be removed because both the answer *and* the question don't yield new information and meanwhile I found out that the described problem with the REST endpoint was not used by the formatting but rather the *line endings*. Perhaps the downvoter can do something *even more useful* and click the close as duplicate button, I will do ;-) – Marged Jan 30 '20 at 15:32

1 Answers1

0

Updating as per the requirement.

If you are open to another library, use Gson to get what you expect.

    Emp emp = new Emp(1);
    List<Emp> emps = new ArrayList<>();
    emps.add(emp);
    emps.add(emp);

    Gson gson = new GsonBuilder().setPrettyPrinting().create();

    System.out.println(gson.toJson(emps));

Output:

[
  {
    "id": 1
  },
  {
    "id": 1
  }
]

class Emp {
    int id;

    public Emp() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public Emp(int id) {
        this.id = id;
    }
}
Shafiul
  • 1,452
  • 14
  • 21