7

fastjson 如何按照 key 顺序解析 JSONObject 对象?

 2 years ago
source link: https://hellodk.cn/post/771
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

fastjson 如何按照 key 顺序解析 JSONObject 对象?

com.alibaba.fastjson 如何按照顺序解析 JSONObject 对象?应用场景:比如按照顺序输出各个 key 的名称。

<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.30</version>
</dependency>

本次读取本地的一个文件 OwO.json,文件有接近 6000 行,有 18 个大对象。

public static void main(String[] args) throws IOException {
Path path = Paths.get("/Users/xxx/Downloads/OwO.json");
File file = new File(String.valueOf(path));
String content = FileUtils.readFileToString(file, "UTF-8");
LinkedHashMap<String, Object> map = JSON.parseObject(content,
new TypeReference<LinkedHashMap<String, Object>>() {
for (Map.Entry<String, Object> entry : map.entrySet()) {
System.out.println("- " + entry.getKey());

如何保证有序遍历?关键是靠 LinkedHashMap,引入的包有这些

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.LinkedHashMap;
import java.util.Map;

上述程序运行的结果如下,观察文件发现,这些 key 的确是有序的。

  • Emoji
  • Bilibili
  • Bilibili 小电视
  • Bilibili 2333 娘
  • Bilibili 蛆音娘
  • Bilibili 小黄脸
  • Bilibili HotKey
  • 嗷大喵小表情
  • Paopao
  • 阿鲁/aru

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK