json - 创建用于 key 签名的有序 json 字符串

标签 json swift xcode dictionary data-structures

为了理解这个问题,我需要提供一些我想要实现的目标的背景。

我正在尝试用这个 library 创建一个 JWT将使用私钥进行签名。

我的问题是,我用来创建 JSON 的字典是无序的,因此会产生无序的 JSON 字符串。

下面的代码以任意顺序打印 JSON 字符串。

let dictionary = ["aKey": "aValue", "anotherKey": "anotherValue"]

    if let theJSONData = try?  JSONSerialization.data(
      withJSONObject: dictionary,
      options: .prettyPrinted
      ),
      let theJSONText = String(data: theJSONData,
                               encoding: String.Encoding.ascii) {
          print("JSON string = \n\(theJSONText)")
    }
let privateKey = theJSONText.data(using: .utf8)
let jwtSigner = JWTSigner.hs256(privateKey: privateKey)
let signedJWT = try myJWT.sign(using: jwtSigner) // This produces a JWT with an invalid signature

这样做的结果是我的 JWT 产生了无效的签名。如何生成有顺序的 JSON 字符串?

最佳答案

JSONEncoder 始终以相同的顺序对字典进行编码(但可能不是是字典的给定顺序)。但也许它能满足您的需求。

if let theJSONData = try? JSONEncoder().encode(dictionary) {
    let theJSONText = String(data: theJSONData, encoding: .utf8)!
    print("JSON string = \n\(theJSONText)")
}

还有OutputFormattingsortedKeys选项

并且——再一次——从不prettyPrint任何将要发送到服务器的东西。

关于json - 创建用于 key 签名的有序 json 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57832459/

相关文章:

ios - 在 Swift 中注册远程通知时未收到设备 token

swift - 覆盖核心数据(如果存在)

ios - 生成 .ipa 文件后未显示更改

ios - 自动布局约束和堆栈 View

java - 用 Jackson 解析 JSON 让我抓狂

javascript,来自json的嵌套导航栏

json - 使用 Swift 读取 JSON 文件

php - 在数组内部创建 php json 对象数组

java - 如何读取Json文件中超过1个JsonObject

swift - 如何在不同情况下以编程方式快速限制 View 多次?