How can I parse this JSON object using Swift 3.0 - ios

I'm trying to parse a JSON string returned from a new API. The returned JSON string looks like this.
QuerySearchResult":{
"StartAt":"1",
"Count":"40",
"TotalAvailable":"500",
"Items":[
{"TITLE":"OST420 Generation",
"PATH":"http:\\Test.pdf",
"WRITE":"2016-12-12T15:47:42",
"RANK":"32286574",
"SIZE":"145091",
"ISDOCUMENT":"true",
"ID":"18548",
"WPTASK":"Onsite Generation",
"WPDOCTYPE":"Local Operating Procedure",
"WPDOCREFID":"304580",
"WPCONTENTTYPE":"Document"},
{"TITLE":"OST420 Measurement",
"PATH":"http:\Test33.pdf",
.
.
I'm using the code below which accepts the JSON variable but fails when I try to load item. I've tried using Array around Dictionary but it still fails. What declaration do I need to read in Items?
if let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as? Dictionary<String, AnyObject> {
for item in json {
if let dict = item as? Dictionary<String, AnyObject> {
if let items = json["Items"] as? Array<Dictionary<String, AnyObject>> {
for rec in items {
if let title = rec["TITLE"] as? String {
let xx = title
}
}
}
}
}

First of all you are not correctly iterating through Dictionary also instead of looping through Dictionary for accessing single value, try by directly accessing it through subscripting and the proper JSON notation of Dictionary in Swift 3 is [String : Any].
if let json = try? JSONSerialization.jsonObject(with: data!, options: []) as? [String : Any],
let queryDic = json["QuerySearchResult"] as? [String : Any],
let items = queryDic["Items"] as? [[String : Any]] {
for item in items {
if let title = item["TITLE"] as? String {
print(title)
}
}
}

In Swift 3.1 :-
func parseJson(anyObj:AnyObject) {
if let anyObj = anyObj as? Array<Dictionary<String,AnyObject>> {
self.yourArrayName = anyObj.flatMap({yourModelName(json:$0) })
}
}

The Json returns the data into the dictionary and array format, so treat the json data like it, it makes you easier to understand.
Data in braces '{' and '}' is dictionary.
and Data in braces '[' or ']' is array.
Now start parsing the json data by the dictionary and array properties it exactly works. Or for confirmation print your json data.

Use SwiftyJSON : which can simply and easily parse the JSON more than your code.
So, how do we parse using that?
First get your response as Data()
let jsonData = JSON(data: results!)
Then here how we parse that JSON.
import Foundation
import SwiftyJSON
enum JSONParseError : ErrorType {
case UnknownField
case EmptyJSON
}
extension JSONParseError : CustomStringConvertible {
var description: String {
switch self {
case .UnknownField:
return "Error when parsing json because there is no field"
case .EmptyJSON:
return "Error when parsing empty json"
}
}
}
guard let querySearchResult : [String : JSON] = jsonData["QuerySearchResult"].dictionary else{
throw JSONParseError.UnknownField
}
guard let startAt : String = querySearchResult["StartAt"].string else{
throw JSONParseError.UnknownField
}
guard let count : String = querySearchResult["Count"].string else{
throw JSONParseError.UnknownField
}
guard let totalAvailable : String = querySearchResult["TotalAvailable"].string else{
throw JSONParseError.UnknownField
}
guard let items : [JSON] = querySearchResult["Items"].array else{
throw JSONParseError.UnknownField
}
if items.count > 0 {
for i in 0 ..< items.count{
guard let title = items[i]["TITLE"].string else{
throw JSONParseError.UnknownField
}.... //So On
}
}else{
throw JSONParseError.EmptyJSON
}

Related

Converting JSON array string to JSON array returns null

I use alamofire for requests. Here on a simple response, I'm getting this JSON string from alamofire
Optional("[{\"nl2br\":\"2019-05-02 19:52:10\",\"nl3br\":\"\",\"nl4br\":\"#lxr\",\"nl5br\":\"1\",\"nl6br\":\"nein\",\"nl7br\":\"bARxrdw9c7WS1RN9c\\/\\/MrA==822b5dd20cb73611:35cab43d0c7e82e73c62818d9f90cfe8\",\"nl8br\":\"tBDSzkQ7eCNERwldgZiwKg==a7590d9d8affdbe5:63b9a9bf6421ea7db2a55f8773990b08\",\"nl9br\":\"fpd17pxVUzcJWNskVWyBeA==cf21783de8334248:a93e8b8a92ef9b238b75ad87a315ce3e\"},{\"nl2br\":\"2019-04-26 21:36:32\",\"nl3br\":\"old\",\"nl4br\":\"\",\"nl5br\":null,\"nl6br\":\"ja\",\"nl7br\":\"emjUIzK92fWwHNLv\\/4xv2Q==8fca202c9a816c7b:655ef8aaaa0212bb9e77a9c35a56c3a7\",\"nl8br\":\"1C5Hy\\/ZhMk3b6SZY8c08lw==cb3b0f4fdd6b5957:034e72d400598fedc43b3111d841a31b\",\"nl9br\":\"KUfLHbih9612dhNCYPOrTg==48da9c3362430e01:3a80ba9fb516e4172aa39b017abcd96e\"},{\"nl2br\":\"2019-04-26 21:20:24\",\"nl3br\":\"holder\",\"nl4br\":\"\",\"nl5br\":null,\"nl6br\":\"ja\",\"nl7br\":\"J59nMBWUMyU9PzdbwQqd0g==f7d3c6c561c33f0b:3465e9131a2577c39cddcc606d0785b0\",\"nl8br\":\"G4rRevk951ZBJJQKzBeJZg==45c0ebcdc1e000e8:dc770c3849fef8b058f85cad42c73e1d\",\"nl9br\":\"338Ud9CIDgnyBV96F2Fx\\/w==d0f825064e0ecf81:0ca00ff27e977ef5f8123d38c643a8b3\"},{\"nl2br\":\"2019-04-10 23:57:17\",\"nl3br\":\"\",\"nl4br\":\"Wasmes, here\'s a video and do ya need?\",\"nl5br\":\"1\",\"nl6br\":\"ja\",\"nl7br\":\"fw17O1L9SuO9FS3qu6U7QQ==706bd09ee3b5ec55:6667d9020a0edcacbd217f631d2305c0\",\"nl8br\":\"2tTE9+0Kr6cVSuEOsq8h0w==3e0e46352da323be:941710bd881546dfa08d3afb6aea2831\",\"nl9br\":\"NAkMx0OsKwXVGndYXbAFmA==1234c0b2992502bf:666f8efd3bdf8ee8b0a2ee4e7222c2ef\"},{\"nl2br\":\"2019-02-22 21:38:16\",\"nl3br\":\"i\'m giving up on you, but don\'t \",\"nl4br\":\"\",\"nl5br\":null,\"nl6br\":\"nein\",\"nl7br\":\"gOv13Dsxf1N2UG46KT3tvQ==dd02a83b1837bb24:4f7c7ab95e873d35685ab7b738626f44\",\"nl8br\":\"40+GOpcNU6M4F688DJyxFA==70bc177842f3f6cf:232b065423bd2683d75ca177775fd352\",\"nl9br\":\"mBc3pEHKBiiPeAEpZRskug==71b353fed6403b99:c58099676beacc146c14867645e29783\"}]")
I get my data like this and convert it like this
if let responseData = response.data {
let responseDataString = String(data: responseData, encoding:String.Encoding(rawValue: String.Encoding.utf8.rawValue))
print(responseDataString) // gives the whole string above
if let obj = responseDataString?.toJSON() as? [String:AnyObject] {
print(obj["nl2br"] as! String) // gives nothing, just nil
}
}
My string extension is like this.
extension String {
func toJSON() -> Any? {
guard let data = self.data(using: .utf8, allowLossyConversion: false) else { return nil }
return try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
}
}
Any idea why this behaviour is expected? I tried printing obj that gives nothing too.
Your root is an array not a dictionary Change responseDataString?.toJSON() as? [[String:Any]]
extension String {
func toJSON() -> Any? {
return try? JSONSerialization.jsonObject(with: Data(self.utf8))
}
}
let responseDataString:String? = """[{\"nl2br\":\"2019-05-02 19:52:10\",\"nl3br\":\"\",\"nl4br\":\"#lxr\",\"nl5br\":\"1\",\"nl6br\":\"nein\",\"nl7br\":\"bARxrdw9c7WS1RN9c\\/\\/MrA==822b5dd20cb73611:35cab43d0c7e82e73c62818d9f90cfe8\",\"nl8br\":\"tBDSzkQ7eCNERwldgZiwKg==a7590d9d8affdbe5:63b9a9bf6421ea7db2a55f8773990b08\",\"nl9br\":\"fpd17pxVUzcJWNskVWyBeA==cf21783de8334248:a93e8b8a92ef9b238b75ad87a315ce3e\"},{\"nl2br\":\"2019-04-26 21:36:32\",\"nl3br\":\"old\",\"nl4br\":\"\",\"nl5br\":null,\"nl6br\":\"ja\",\"nl7br\":\"emjUIzK92fWwHNLv\\/4xv2Q==8fca202c9a816c7b:655ef8aaaa0212bb9e77a9c35a56c3a7\",\"nl8br\":\"1C5Hy\\/ZhMk3b6SZY8c08lw==cb3b0f4fdd6b5957:034e72d400598fedc43b3111d841a31b\",\"nl9br\":\"KUfLHbih9612dhNCYPOrTg==48da9c3362430e01:3a80ba9fb516e4172aa39b017abcd96e\"},{\"nl2br\":\"2019-04-26 21:20:24\",\"nl3br\":\"holder\",\"nl4br\":\"\",\"nl5br\":null,\"nl6br\":\"ja\",\"nl7br\":\"J59nMBWUMyU9PzdbwQqd0g==f7d3c6c561c33f0b:3465e9131a2577c39cddcc606d0785b0\",\"nl8br\":\"G4rRevk951ZBJJQKzBeJZg==45c0ebcdc1e000e8:dc770c3849fef8b058f85cad42c73e1d\",\"nl9br\":\"338Ud9CIDgnyBV96F2Fx\\/w==d0f825064e0ecf81:0ca00ff27e977ef5f8123d38c643a8b3\"},{\"nl2br\":\"2019-04-10 23:57:17\",\"nl3br\":\"\",\"nl4br\":\"Wasmes, here\'s a video and do ya need?\",\"nl5br\":\"1\",\"nl6br\":\"ja\",\"nl7br\":\"fw17O1L9SuO9FS3qu6U7QQ==706bd09ee3b5ec55:6667d9020a0edcacbd217f631d2305c0\",\"nl8br\":\"2tTE9+0Kr6cVSuEOsq8h0w==3e0e46352da323be:941710bd881546dfa08d3afb6aea2831\",\"nl9br\":\"NAkMx0OsKwXVGndYXbAFmA==1234c0b2992502bf:666f8efd3bdf8ee8b0a2ee4e7222c2ef\"},{\"nl2br\":\"2019-02-22 21:38:16\",\"nl3br\":\"i\'m giving up on you, but don\'t \",\"nl4br\":\"\",\"nl5br\":null,\"nl6br\":\"nein\",\"nl7br\":\"gOv13Dsxf1N2UG46KT3tvQ==dd02a83b1837bb24:4f7c7ab95e873d35685ab7b738626f44\",\"nl8br\":\"40+GOpcNU6M4F688DJyxFA==70bc177842f3f6cf:232b065423bd2683d75ca177775fd352\",\"nl9br\":\"mBc3pEHKBiiPeAEpZRskug==71b353fed6403b99:c58099676beacc146c14867645e29783\"}]"""
if let obj = responseDataString?.toJSON() as? [[String:Any]] {
obj.forEach {
print($0["nl2br"])
}
}
Result
Optional(2019-05-02 19:52:10)
Optional(2019-04-26 21:36:32)
Optional(2019-04-26 21:20:24)
Optional(2019-04-10 23:57:17)
Optional(2019-02-22 21:38:16)
Edit: In json this
[{
"name":"ppp"
}]
is an array of dictionaries to be [[String:Any]] notice nested [[]] , while this
{
"name":"ppp"
}
is a dictionary represented by [String:Any] notice only []

JSON Parsing---> Could not cast value of type '__NSCFString' (0x1e5c38f90) to 'NSDictionary' (0x1e5c39bc0)

{"msgType":"UPDATE_S","macAddress":"2F-01-01-01-01-01","deviceName":"vMining","deviceType":"vSensor","groupId":"vMiningYo","param”:”truckDetail","value":"[{'TruckNo':1,'Status':'Moving to crusher','Speed':0,'CheckPointNumber':16,'CurrentLoad':346,'TirePressureIssueWheelNumber':0,'TirePressure':6,'Longitude':36.835072,'Latitude':-109.059769,'Altitude':1.0}]","valueDimension":"JSON","topic":"in/vMiningYo_ios/vMINING","_MessageGateway_TimeMilliseconds":1557471205646,"_MessageGateway_TimeSeconds":1557471205,"_MessageGateway_TimeISO8601":"2019-05-10T06:53:25.646Z","_MessageGateway_MessageClientType":"WS","_MessageGateway_Topic":"in/vMiningYo_ios/vMINING"}
I'm getting above json data in string format and i'm parsing with JSONSerialization like below method. I can able to print value data in console but how can i access inside values based on keys.
func recieveMessage(json:String){
guard let data = json.data(using: .utf16),
let jsonData = try? JSONSerialization.jsonObject(with: data),
let jsonDict = jsonData as? [String: Any],
let param = jsonDict["param"] as? String else {
return
}
if param == "truckDetail"{
print("VALUE:: \(jsonDict["value"]!)")
let truckData = jsonDict["value"]! as! [String:Any]
print(truckData)
print(truckData["Status"])
// if let truckData = jsonDict["value"] as? [String: Any]{
// print(truckData)
// }
}
}
Printing in Console:
VALUE:: [{'TruckNo':1,'Status':'Moving to crusher','Speed':0,'CheckPointNumber':16,'CurrentLoad':346,'TirePressureIssueWheelNumber':0,'TirePressure':6,'Longitude':36.835072,'Latitude':-109.059769,'Altitude':1.0}]
How can I print Status value in this Dictionary? Thanks in advance.
There are two major issues:
The object for key value is a String (apparently JSON). That's what the error clearly says.
But actually it's not valid JSON because JSON strings must be wrapped in double quotes, single quotes are not supported.
You need two extra steps: Replace the single quotes with double quotes and deserialize the JSON string separately.
And the object is an array. Either use a loop or get an item by index
let json = """
{"msgType":"UPDATE_S","macAddress":"2F-01-01-01-01-01","deviceName":"vMining","deviceType":"vSensor","groupId":"vMiningYo","param":"truckDetail","value":"[{'TruckNo':1,'Status':'Moving to crusher','Speed':0,'CheckPointNumber':16,'CurrentLoad':346,'TirePressureIssueWheelNumber':0,'TirePressure':6,'Longitude':36.835072,'Latitude':-109.059769,'Altitude':1.0}]","valueDimension":"JSON","topic":"in/vMiningYo_ios/vMINING","_MessageGateway_TimeMilliseconds":1557471205646,"_MessageGateway_TimeSeconds":1557471205,"_MessageGateway_TimeISO8601":"2019-05-10T06:53:25.646Z","_MessageGateway_MessageClientType":"WS","_MessageGateway_Topic":"in/vMiningYo_ios/vMINING"}
"""
let data = Data(json.utf8)
do {
if let result = try JSONSerialization.jsonObject(with: data) as? [String:Any],
let param = result["param"] as? String {
if param == "truckDetail" {
let value = result["value"] as! String
let valueString = value.replacingOccurrences(of: "\'", with: "\"")
let valueData = Data(valueString.utf8)
if let valueResult = try JSONSerialization.jsonObject(with: valueData) as? [[String:Any]] {
for item in valueResult {
print(item["Status"] as? String ?? "n/a")
}
}
}
}
} catch { print(error)}
jsonDict["value"] is a json string not a dictionary
let truckStr = jsonDict["value"] as! String
let jsonDic = try! JSONSerialization.jsonObject(with:Data(truckStr.utf8)) as! [String: Any]
print(jsonDic["Status"])

What is the different between these two rows in the JSON array which means one isn't being recognised?

I have an API call that retrieves an array from my database featuring countries, divisions, teams.
This output shows the format of the JSON when received in Swift (teams not shown in example:
Optional(["countries": <__NSArrayI 0x6180001f6500>(
{
id = 1;
name = Denmark;
},
{
id = 2;
name = Belgium;
}
)
, "divisions": <__NSArrayI 0x7fc8a34455a0>(
{
Name = "ALKA SUPERLIGA";
"country_id" = 1;
id = 1;
},
{
Name = "PRO LEAGUE";
"country_id" = 2;
id = 2;
}
I am using the following function in swift to sort the countries and divisions into different string arrays to then use in an UITableView.
override func viewDidAppear(_ animated: Bool) {
let myUrl = URL(string: "http://www.quasisquest.uk/KeepScore/getTeams.php?");
var request = URLRequest(url:myUrl!);
request.httpMethod = "POST";
let postString = "";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
DispatchQueue.main.async
{
if error != nil {
print("error=\(error)")
return
}
do{
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]
print (json)
if let arr = json?["countries"] as? [[String:String]] {
self.countryId = arr.flatMap { $0["id"]!}
self.countries = arr.flatMap { $0["name"]!}
self.teamsTableView.reloadData()
print ("Countries: ",self.countries)
}
if let arr = json?["divisions"] as? [[String:String]] {
self.divisions = arr.flatMap { $0["Name"]!}
self.divisionId = arr.flatMap { $0["id"]!}
self.teamsTableView.reloadData()
print ("Divisions: ",self.divisions)
}
} catch{
print(error)
}
}
}
task.resume()
//membersTableView.reloadData()
}
The print ("Countries: ",self.countries) outputs as expected, below:
Countries: [Optional("Denmark"), Optional("Belgium")
But the print ("Divisions: ",self.divisions) doesn't even run. So there must be something wrong with that IF command, yet I am using the same code as what I used from the 'countries' section.
Any ideas?
I have tried replacing [[String : String]] with [[String : String?]] but this did nothing. I have also tried [[String : Any]] but this brought the following error on the arr.flapMap lines:
'(_) -> Any' to expected argument type '(Dictionary) -> SegmentOfResult'
First of all in Swift 3 the common unspecified type is Any rather than AnyObject
In the given JSON
The root object is [String:Any]
The value for divisions is [[String:Any]] because it contains String and <null> types.
The value <null> will be replaced with n/a
if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:Any] {
print (json)
if let arr = json["countries"] as? [[String:String]] {
self.countryId = arr.flatMap { $0["id"]!}
self.countries = arr.flatMap { $0["name"]!}
self.teamsTableView.reloadData()
print ("Countries: ",self.countries)
}
if let arr = json["divisions"] as? [[String:Any]] {
self.divisions = arr.flatMap { $0["Name"] as? String ?? "n/a" }
self.divisionId = arr.flatMap { $0["id"] as? String }
self.teamsTableView.reloadData()
print ("Divisions: ",self.divisions)
}
}
Notes:
Do not use multiple arrays as data source in conjunction with flatMap, this is pretty error-prone, use a custom struct instead.
A POST request is not needed, GET (a data task passing the url) is sufficient.
Probably "country_id" key has integer value and because of that "if let arr = json?["divisions"] as? [[String:String]]" statement is not working.
Always try to set [[String:Any]] to any array of dictionary if you retrieving it from server.
Your dictionary is of type [String:Any], thus the cast fails. Use Any:
if let arr = json?["divisions"] as! [[String:Any]] { ...
It happens because in case of divisions some elements contain empty (null) names. Which means that real type is not [[String:String]], but [[String:String?]]

swift: cannot subscript a value of type [Dictionary<String, AnyObject>] with an index of type string

I am trying to json parsing in swift 3. I am getting the above mentioned error. My parsing technique is as follows:
if let responseData = data {
do {
let json = try JSONSerialization.jsonObject(with: responseData, options: JSONSerialization.ReadingOptions.allowFragments)
if let dict = json as? [Dictionary<String, AnyObject>] {
if let localityName = dict["name"] as? String ,let localityId = dict["_id"] as? String {
}
}
} catch {
print("could not serialize")
}
}
I am getting the error in the line:
if let localityName = dict["name"] as? String ,let localityId = dict["_id"] as? String
please let me know how can I fix this issue
The dict property is an array of dictionaries, not a dictionary.
You could access the first elements name the following:
dict.first?["name"]
dict is actually arr. Create a loop to iterate thru it
if let arr = json as? [Dictionary<String, AnyObject>] {
for item in arr {
if let localityName = item["name"] as? String,
let localityId = item["_id"] as? String {
print(localityName, localityId)
}
}
}

parsing JSON with Swift

I'm coming from android programming to Swift iOS programming and have a hard time parsing a json
here's String I try to parse :
{"response":[{"uid":111,"first_name":"someName","last_name":"someLastName","photo_100":"http:someUrl/face.jpg"}]}
here how I try to parse this :
if let dict = Utils.convertStringToDictionary(response)! as? [String: AnyObject]{
// this part is yet doing ok
if let response = dict["response"] as? [String: AnyObject]{
NSLog("let response \(response)")
if let first_name = response["first_name"] as? String {
NSLog("first_name = \(first_name)")
}
}
else {
NSLog("not an []")
}
the Log message gives me "not an []" as it can't make a response object. As far as I understand, I'm doing right as [String: AnyObject] is what is in "response" body of my json
Just in case, here's my Utils.convertStringToDictionary method:
public static func convertStringToDictionary(text: String) -> [String:AnyObject]? {
if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
do {
let json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) as? [String:AnyObject]
return json
} catch {
NSLog("Something went wrong")
}
}
return nil
}
Array in swift denotes with []
Dictionary in swift denotes with [:]
your response parameter is array of dictionary ... so it denotes with [[:]]
so just parse it with [[String: AnyObject]]
if let response = dict["response"] as? [[String: AnyObject]]{
for user in response{
NSLog("let response \(user)")
if let first_name = user["first_name"] as? String {
NSLog("first_name = \(first_name)")
}
}
}
Problem here is response is an array
if let response = dict["response"] as? NSArray{
for value in response as? NSDictionary{
print(value["uid"]) /// prints 111
print(value["first_name"]) /// prints someName
}
}
Try this code
if let dict = Utils.convertStringToDictionary(response)! as? [String: AnyObject]{
// this part is yet doing ok
if let response = dict["response"] as? NSArray{
NSLog("let response \(response)")
for dict in response{
if let first_name = dict["first_name"] as? String {
NSLog("first_name = \(first_name)")
}
}
}
else{
NSLog("not an []")
}
}

Resources