为了理解这个问题,我需要提供一些我想要实现的目标的背景。
我正在尝试用这个 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)")
}
还有OutputFormatting
的sortedKeys
选项
并且——再一次——从不prettyPrint任何将要发送到服务器的东西。
关于json - 创建用于 key 签名的有序 json 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57832459/