Jackson JSON 格式不正确 [英] Jackson JSON Not Formatting Correctly
问题描述
我有这样的数据:
{
"status": "success",
"data": {
"irrelevant": {
"serialNumber": "XYZ",
"version": "4.6"
},
"data": {
"lib": {
"files": [
"data1",
"data2",
"data3",
"data4"
],
"another file": [
"file.jar",
"lib.jar"
],
"dirs": []
},
"jvm": {
"maxHeap": 10,
"maxPermSize": "12"
},
"serverId": "134",
"version": "2.3"
}
}
}
这是我用来美化 JSON 数据的函数:
Here is the function I'm using to prettify the JSON data:
public static String stringify(Object o, int space) {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(o);
} catch (Exception e) {
return null;
}
}
我正在使用 Jackson JSON 处理器将 JSON 数据格式化为字符串.出于某种原因,JSON 格式不是我需要的格式.将数据传递给该函数时,我得到的格式是这样的:
I am using the Jackson JSON Processor to format JSON data into a String. For some reason the JSON format is not in the format that I need. When passing the data to that function, the format I'm getting is this:
{
"status": "success",
"data": {
"irrelevant": {
"serialNumber": "XYZ",
"version": "4.6"
},
"another data": {
"lib": {
"files": [ "data1", "data2", "data3", "data4" ],
"another file": [ "file.jar", "lib.jar" ],
"dirs": []
},
"jvm": {
"maxHeap": 10,
"maxPermSize": "12"
},
"serverId": "134",
"version": "2.3"
}
}
}
正如您在另一个数据"对象下看到的那样,数组显示为一整行,而不是为数组中的每个项目显示一个新行.我不确定如何修改我的 stringify 函数以正确格式化 JSON 数据.
As you can see under the "another data" object, the arrays are displayed as one whole line instead of a new line for each item in the array. I'm not sure how to modify my stringify function for it to format the JSON data correctly.
推荐答案
你应该检查 DefaultPrettyPrinter 看起来像.这门课真正有趣的是 _arrayIndenter 属性.此属性的默认值为 FixedSpaceIndenter 类.你应该用 Lf2SpacesIndenter 类.
You should check how DefaultPrettyPrinter looks like. Really interesting in this class is the _arrayIndenter property. The default value for this property is FixedSpaceIndenter class. You should change it with Lf2SpacesIndenter class.
您的方法应如下所示:
public static String stringify(Object o) {
try {
ObjectMapper mapper = new ObjectMapper();
DefaultPrettyPrinter printer = new DefaultPrettyPrinter();
printer.indentArraysWith(new Lf2SpacesIndenter());
return mapper.writer(printer).writeValueAsString(o);
} catch (Exception e) {
return null;
}
}
这篇关于Jackson JSON 格式不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!