English 中文(简体)
快速 JSONONEN 编码器设置元素序列
原标题:swift JSONEncoder set element order

是否有一种方法可以设置 Jookonencoder 元素的自定义顺序? 例如, 如果我有一个 < code> 编码 , 包含元素 < code> 、 消息和错误 < / code >, 是否有办法确保 Jookonencoder 返回这些元素的顺序? 目前它似乎只是按照它选择的顺序返回数据 。

我知道使用 Jsonenncoder. outputformatting .sordedkeys 来按字母顺序排列有一个选项,但这不是我所要寻找的(也似乎只在ios 11中有效),我试图在比较json 字符串的地方进行单位测试,因此顺序是必要的。

问题回答

如果有人在看这个(6年后),你可以简单地写一个函数,用两个数据对象(假设有效的JSON)来比较:

import Foundation

func areJSONEqual(_ json1: Data, _ json2: Data) -> Bool {
    guard let jsonObject1 = try? JSONSerialization.jsonObject(with: json1, options: []),
          let jsonObject2 = try? JSONSerialization.jsonObject(with: json2, options: []) else {
        return false
    }
    
    guard let sortedJSONData1 = try? JSONSerialization.data(withJSONObject: jsonObject1, options: .sortedKeys),
          let sortedJSONData2 = try? JSONSerialization.data(withJSONObject: jsonObject2, options: .sortedKeys) else {
        return false
    }
    
    return sortedJSONData1 == sortedJSONData2
}

然后把它放进你的XCTSCase,

XCTAssertTrue(areJSONEqual(jsonData1, jsonData2))

可以在XCtestCase上做一个扩展, 并随时随地使用。

干杯! 干杯! 干杯! 干杯!





相关问题
List Contents of Directory in a UITableView

I am trying to list the contents of Ringtones directory in a TableView, however, I am only getting the last file in the directory in ALL cells, instead of file per cell. This is my code: - (...

iPhone NSUserDefaults persistance difficulty

In my app i have a bunch of data i store in the NSUserdefaults. This information consists of an NSObject (Object1) with NSStrings and NSNumbers and also 2 instances of yet another object (Object2). ...

Writing a masked image to disk as a PNG file

Basically I m downloading images off of a webserver and then caching them to the disk, but before I do so I want to mask them. I m using the masking code everyone seems to point at which can be found ...

Resize UIImage with aspect ratio?

I m using this code to resize an image on the iPhone: CGRect screenRect = CGRectMake(0, 0, 320.0, 480.0); UIGraphicsBeginImageContext(screenRect.size); [value drawInRect:screenRect blendMode:...

Allowing interaction with a UIView under another UIView

Is there a simple way of allowing interaction with a button in a UIView that lies under another UIView - where there are no actual objects from the top UIView on top of the button? For instance, ...

热门标签