【发布时间】:2019-09-07 09:38:28
【问题描述】:
为了理解这个问题,我需要提供一些我想要达到的目标的背景。
我正在尝试使用此 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 字符串?
【问题讨论】:
-
字典根据定义是无序的,因此顺序无关紧要。但是,您应该删除添加不必要的空白字符的
prettyPrinted选项。服务器根本不关心人类的可读性。privateKey是可选的,这也可能是一个问题。使用非可选的let privateKey = Data(theJSONText.utf8)创建数据 -
顺序很重要,因为我需要我的 JSON 字符串按照这个确切的顺序
"{"aKey": "aValue", "anotherKey": "anotherValue"}"否则privateKey数据无效 -
您确定是字典顺序导致了您的问题吗?
-
我敢肯定,它毕竟是创建字符串的字典,如果字典是无序的,那么字符串也是
标签: json swift xcode dictionary data-structures