JSON comparison

Sometimes you are writing test code such as Codable in the Model layer and want to compare the expected JSON strings. However, the KeyValue format such as JSON is in no particular order and cannot be simply compared.

Then I came up with a method of making a Dictionary type and comparing.

extension String {
    func jsonDictionary() throws -> [String: AnyHashable]? {
        guard let data = self.data(using: .utf8) else { return nil }
        return try data.jsonDictionary()
    }
}

extension Data {
    func jsonDictionary() throws -> [String: AnyHashable]? {
        return try JSONSerialization.jsonObject(with: self, options: []) as? [String: AnyHashable]
    }
}

If you prepare a func that returns the result of JSONSerialization.jsonObject as a Data extension and add a func that passes it even in the String extension, you can evaluate it with XCTAssertEqual even with the following test code, for example.

    func test_HogeEncode() {
        let object = Hoge(value: 123, flag: true)
        let expectation = """
            {
                "value": "123",
                "flag": "true"
            }
        """
        let data = try? JSONEncoder().encode(object)
        XCTAssertNotNil(data)
        
        XCTAssertEqual(try? expectation.jsonDictionary(), try? data!.jsonDictionary())
    }

Recommended Posts

JSON comparison
MyBatis string comparison
[Java] Map comparison
Diffed with JSON
Java framework comparison