配置杰克逊漂亮打印 JSON 的方式



我使用Jackson创建一个JSON文件,并将其转发到外部REST服务。我花了几个小时才发现该服务对 JSON 文件的格式非常敏感。

这是可以接受的:

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

这(这是杰克逊漂亮打印机的默认行为(被接受,并导致 REST 调用失败:

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

我可以将杰克逊配置为使用其他格式吗?让我强调这一点:我知道接收 REST 服务的作者应该解决这个问题,但这超出了我的范围。

杰克逊的定制漂亮打印机领域存在像这样的问题。但也许已经有一个定制。

根据要求更新。

如果您开放使用其他库,请使用 Gson 获取所需的内容。

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));

输出:

[
{
"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;
}
}

最新更新