如何对json串按key排序
- 原JSON串
{
"key-a": "val-a",
"key-b": "val-b",
"key-c": "val-c",
"key-e": [
{
"key-e-4": "val-e-4",
"key-e-3": "val-e-3"
},
{
"key-e-2": "val-e-2",
"key-e-1": "val-e-1"
}],
"key-d":
{
"key-d-3": "val-d-3",
"key-d-4": "val-d-4",
"key-d-1": "val-d-1",
"key-d-2": "val-d-2"
}
}
- pom引入
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.70</version>
</dependency>
- 执行操作
final JSONObject jsonObject = JSON.parseObject(jsonString);
final String keySortedJson = JSONObject.toJSONString(jsonObject, SerializerFeature.MapSortField);
- 输出结果
{
"key-a": "val-a",
"key-b": "val-b",
"key-c": "val-c",
"key-d":
{
"key-d-1": "val-d-1",
"key-d-2": "val-d-2",
"key-d-3": "val-d-3",
"key-d-4": "val-d-4"
},
"key-e": [
{
"key-e-3": "val-e-3",
"key-e-4": "val-e-4"
},
{
"key-e-1": "val-e-1",
"key-e-2": "val-e-2"
}]
}