在Swift中使用排序键编写一个prettyPrinted JSON对象 [英] Write a prettyPrinted JSON object with sorted keys in Swift

查看:108
本文介绍了在Swift中使用排序键编写一个prettyPrinted JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们经常想使用JSON来提高可读性.因此,通常要求按字母顺序(或字母数字)对JSON键进行排序( 在Python中

We often want to use JSON for human readability. As such, it is common to ask to sort the JSON keys alphabetically (or alphanumerically) in Go, in .NET, in Python, in Java, ...

但是如何输出带有Swift中按字母顺序排序的JSON密钥的JSON?

PrettyPrinted输出很容易:

PrettyPrinted output is easy:

JSONSerialization.writeJSONObject(jsonObject, to: outputStream, options: [.prettyPrinted], error: nil)

但是,为了便于阅读,按键并未按字母顺序排序.它们可能按照 NSDictionary.keyEnumerator()给出的顺序.但是可悲的是,我们无法在Swift中将Dictionary,NSDictionary或CFDictionary子类化,因此我们无法覆盖键顺序的行为.

Yet the keys are not alphabetically sorted for human readability. They are likely in the order given by NSDictionary.keyEnumerator(). But sadly, we can't subclass Dictionary, NSDictionary or CFDictionary in Swift, so we can't override the behavior of keys order.

推荐答案

对于iOS 11+和macOS High Sierra(10.13+),有一个新选项

For iOS 11+ and macOS High Sierra (10.13+), a new option .sortedKeys solves the problem easily:

JSONSerialization.writeJSONObject(jsonObject, to: outputStream, options: [.sortedKeys, .prettyPrinted], error: nil)

谢谢您 Hamish 作为提示.

这篇关于在Swift中使用排序键编写一个prettyPrinted JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆