Nas5296 Nas5296 - 5 months ago 2047
JSON Question

JSON Parsing in Swift 3

Has anyone been able to find a way to parse through JSON files in Swift 3? I have been able to get the data to return but I am unsuccessful when it comes to breaking the data down into specific fields. I would post sample code but I've gone through so many different methods unsuccessfully and haven't saved any. The basic format I want to parse through is something like this. Thanks in advance.

{
"Language": {

"Field":[
{
"Number":"976",
"Name":"Test"
},
{
"Number":"977",
"Name":"Test"
}
]
}
}

Answer

Have you tried JSONSerialization.jsonObject(with:options:)?

var jsonString = "{" +
    "\"Language\": {" +
    "\"Field\":[" +
    "{" +
    "\"Number\":\"976\"," +
    "\"Name\":\"Test\"" +
    "}," +
    "{" +
    "\"Number\":\"977\"," +
    "\"Name\":\"Test\"" +
    "}" +
    "]" +
    "}" +
    "}"

var data = jsonString.data(using: .utf8)!

let json = try? JSONSerialization.jsonObject(with: data)

Swift sometimes produces some very odd syntax.

if let number = json?["Language"]??["Field"]??[0]?["Number"] as? String {
    print(number)
}

Everything in the JSON object hierarchy ends up getting wrapped as an optional (ie. AnyObject?). Array<T> subscript returns a non-optional T. For this JSON, which is wrapped in an optional, array subscript returns Optional<AnyObject>. However, Dictionary<K, V> subscript returns an Optional<V>. For this JSON, subscript returns the very odd looking Optional<Optional<AnyObject>> (ie. AnyObject??).

  • json is an Optional<AnyObject>.
  • json?["Language"] returns an Optional<Optional<AnyObject>>.
  • json?["Language"]??["Field"] returns an Optional<Optional<AnyObject>>.
  • json?["Language"]??["Field"]??[0] returns an Optional<AnyObject>.
  • json?["Language"]??["Field"]??[0]?["Number"] returns an Optional<Optional<AnyObject>>.
  • json?["Language"]??["Field"]??[0]?["Number"] as? String returns an Optional<String>.

The Optional<String> is then used by the if let syntax to product a String.

Comments