【问题标题】:Print a java object as JSON string after sorting its keys and values在对其键和值进行排序后,将 java 对象打印为 JSON 字符串
【发布时间】:2021-02-10 11:22:29
【问题描述】:

我有一个带有多个键的 java 对象,值可以是数组列表。我想将对象打印为 JSON 字符串,但输出应该对键和值进行排序。在值的情况下,排序应该在数组本身(如果有的话)

例如,我有这个 JSON 表示的 POJO

{
"d": ["d","a", "r"],
"c": "arr",
"a": "2020-10-01:00:00"
}

预期的输出应该是这样的:

{"a": "2020-10-01:00:00", "c": "arr", "d": ["d","a", "r"]}

在输出中,键是相对于彼此排序的,但值数组是在自身内部排序的。

【问题讨论】:

  • 你能分享一下代表这个 JSON 的 POJO 吗?

标签: java json string sorting


【解决方案1】:

如果您想根据键排序,请仅使用以下代码和 JSON Dependency (https://mvnrepository.com/artifact/org.json/json/20140107)-

String[] arr = { "d", "a", "r" };

Map<String, Object> data = new TreeMap<>();
data.put("d", arr);
data.put("c", "arr");
data.put("a", "2020-10-01:00:00");

JSONObject sortedDate = new JSONObject(data);
System.out.println(sortedDate);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-09
    • 2021-05-14
    相关资源
    最近更新 更多