Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active April 2, 2017 11:27
Show Gist options
  • Save KentarouKanno/a390189514be3bf35d06efdad1fc23bc to your computer and use it in GitHub Desktop.
Save KentarouKanno/a390189514be3bf35d06efdad1fc23bc to your computer and use it in GitHub Desktop.

JSONSerialization

★ Dictionary → Data

let dict: [String: Any] = [
    "foo": "bar",
    "baz": [
        "a": 1,
        "b": 20,
        "c": 300
    ]
]

do {
    let d = try JSONSerialization.data(withJSONObject: dict, options: [])
    dump(d)
    //=> 42 bytes
} catch {
    
}

★ NSDictionary → Data

var nsDict: [AnyHashable: Any] = [
    "key1": "abc",
    "key2": 1,
    "key3": true
]

do {
    let d = try JSONSerialization.data(withJSONObject: nsDict, options: [])
    dump(d)
    //=> 35 bytes
} catch {
    
}

★ Array → Data

var array: [Any] = [
    "abc",
    1,
    true
]

do {
    let d = try JSONSerialization.data(withJSONObject: array, options: [])
    dump(d)
    //=> 14 bytes
} catch {
    
}

★ JSONをシリアライズする Data → Any

let dict: [String: Any] = [
    "foo": "bar",
    "baz": [
        "a": 1,
        "b": 20,
        "c": 300
    ]
]

do {
    let data = try JSONSerialization.data(withJSONObject: dict, options: [])
    dump(data)
    //=> 42 bytes
    
    // JSONシリアライズ
    
    let object = try JSONSerialization.jsonObject(with: data, options: [])
    //object
} catch {
    print("catch")
}

★ 有効なJSONかどうかを判定する

let dict: [String: Any] = [
    "foo": "bar",
    "baz": [
        "a": 1,
        "b": 20,
        "c": 300
    ]
]

//=> true
if JSONSerialization.isValidJSONObject(dict) {
    print("有効なJSON")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment