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"
}
]
}
}
JSON Parsing in swift 4 using Decodable Protocol :
I create a mocky file using your json object :
http://www.mocky.io/v2/5a280c282f0000f92c0635e6
Here is the code to parse the JSON :
Model Creation :
You can use optional in the model if you are uncertain that something might be missing in JSON file.
This is the parsing Logic :
The Print Output :
This the github Project link. You can check.
Shoving JSON into a string manually is a pita. Why don't you just put the JSON into a file and read that in?
Swift 3:
JSON Parsing using Swift 4 in Simple WAY
Have you tried
JSONSerialization.jsonObject(with:options:)
?Swift sometimes produces some very odd syntax.
Everything in the JSON object hierarchy ends up getting wrapped as an optional (ie.
AnyObject?
).Array<T>
subscript returns a non-optionalT
. For this JSON, which is wrapped in an optional, array subscript returnsOptional<AnyObject>
. However,Dictionary<K, V>
subscript returns anOptional<V>
. For this JSON, subscript returns the very odd lookingOptional<Optional<AnyObject>>
(ie.AnyObject??
).json
is anOptional<AnyObject>
.json?["Language"]
returns anOptional<Optional<AnyObject>>
.json?["Language"]??["Field"]
returns anOptional<Optional<AnyObject>>
.json?["Language"]??["Field"]??[0]
returns anOptional<AnyObject>
.json?["Language"]??["Field"]??[0]?["Number"]
returns anOptional<Optional<AnyObject>>
.json?["Language"]??["Field"]??[0]?["Number"] as? String
returns anOptional<String>
.The
Optional<String>
is then used by theif let
syntax to product aString
.Final note: iterating the field array looks like this.
Swift 4 Update
Swift 4 makes this all much easier to deal with. Again we will start with your test data (
"""
makes this so much nicer).Next we can define classes around the objects used in your JSON.
The
CodingKeys
enum is how struct properties are mapped to JSON object member strings. This mapping is done automagically byDecodable
.Parsing the JSON now is simple.