从 LinkedHashMap 构建有序 JSON 字符串
问题描述
我需要按插入顺序排列键/值对,因此我选择使用 LinkedHashMap
而不是 HashMap
.但我需要将 LinkedHashMap
转换为 JSON 字符串,其中 LinkedHashMap
中的顺序保留在字符串中.
I had a need for having Key/Value pairs in the order of my insertion, so I opted to use LinkedHashMap
over HashMap
. But I need to convert the LinkedHashMap
into a JSON String where the order in the LinkedHashMap
is maintained in the string.
但目前我正在通过以下方式实现它:
But currently I'm achieving it by:
- 首先将 LinkedHashMap 转换为 JSON.
然后将 JSON 转换成字符串.
- First converting the LinkedHashMap into JSON.
Then converting the JSON into a string.
输出是:
但我希望它按插入键的顺序,如下所示:
But I want it in the order of insertion of the keys, like this:
一旦我将 LinkedHashMap
转换为 JSON,它就会失去它的顺序(很明显 JSON 没有顺序的概念),因此字符串也是无序的.现在,如何生成与 LinkedHashMap
顺序相同的 JSON 字符串?
Once I convert the LinkedHashMap
into a JSON it loses it order (it's obvious that JSON doesn't have the notion of order) and hence the string too is out of order. Now, how do I generate a JSON string whose order is same as the LinkedHashMap
?
推荐答案
Gson 如果你的朋友.这会将有序的地图打印成有序的 JSON 字符串.
Gson if your friend. This will print the ordered map into an ordered JSON string.
如果要保留插入顺序,请使用 LinkedHashMap
.
If you want to preserve insertion order, use a LinkedHashMap
.
我使用的是最新版本的Gson(2.8.5),您可以通过本文底部的以下选项进行下载.
I used the latest version of Gson (2.8.5), you can can download it via the following options at the bottom of this post.
如果您希望项目始终插入正确的位置,请改用 TreeMap
.
If you want the items to always be inserted at the right place, use a TreeMap
instead.
依赖选项
Maven
分级
或者您可以访问 Maven 中心 获取更多下载选项.
Or you can visit Maven Central for more download options.
这篇关于从 LinkedHashMap 构建有序 JSON 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!