Swift: how to parse json to a dictionary - json

I have the following as a json output in console
{
cash_machine = "0.08924368023872375488";
dishwasher = "0.06437973678112030029";
modem = "0.04461396858096122742";
monitor = "0.28455805778503417969";
nematode = "0.04982925951480865479";
screen = "0.05664909631013870239";
television = "0.03846205398440361023";
}
My code is
let session = URLSession.shared.dataTask(with: r) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
} catch {
print(error)
}
}
// experiment here
// if statement ends here
} .resume()
I was wondering how I'd parse this into a dictionary: {"key1" : "value1", "key2" : "value2", "key3" : "value3", ..., "key_n", "value_n"}

Try something along these lines
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String: String]
for key in json.keys {
print("\(key) : \(json[key])")
}
}

Related

Get data from array in response in Swift

i'm hitting an API and response is shown like this,
"responseBody": {
"data": [
"{\"AED_USD\":0.272255,\"USD_AED\":3.67305}"
]
}
I'm confuse that how i can take out value of AED_USD and USD_AED from this array data. I have try to take all of the response in array and try to get value from index base but isn't working. How i can get the value? My code is this,
let params = ["sourceCurrency":self.accountFromTxt.text!,
"targetCurrency":self.accountToTxt.text!] as [String : AnyObject]
print(params)
APIService.ExchangePrice(showActivityIndicator: true, parameters: params) { (responseObject) in
if (responseObject?.status)!
{
self.print(responseObject?.data)
self.exchangeRateArray.removeAll()
if let usersDataArray = responseObject?.data as? [[String : Any]] {
for userData in usersDataArray {
self.exchangeRateArray.append(ExchangeRateCurrency(JSON:userData)!)
}
if usersDataArray.count == 0
{
//Empty Message
self.view.showEmptyScreenMessage(text: EmptyScreenMessages.transactionDetailMessage)
}
self.print(self.exchangeRateArray.count,self.exchangeRateArray[0])
}
}
else
{
Utilities.showBar(text: responseObject?.errorObject?.message)
}
}
Your data is in string form, change string to JSON NSdictonary.
try to convert like this
let str = "{\"AED_USD\":0.272257,\"USD_AED\":3.673001}"
if let data = str.data(using: String.Encoding.utf8) {
do {
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:Any]
print(json)
} catch {
print("Something went wrong")
}
}
// In your code.
let params = ["sourceCurrency":self.accountFromTxt.text!,
"targetCurrency":self.accountToTxt.text!] as [String : AnyObject]
print(params)
APIService.ExchangePrice(showActivityIndicator: true, parameters: params) { (responseObject) in
if (responseObject?.status)!
{
self.print(responseObject?.data)
self.exchangeRateArray.removeAll()
if let usersDataArray = responseObject?.data as? [[String : Any]] {
for userData in usersDataArray {
print(userData)
// if you get string from userData
if let data = userData.data(using: String.Encoding.utf8) {
do {
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:Any]
print(json)
} catch {
print("Something went wrong")
}
}
}
if usersDataArray.count == 0
{
//Empty Message
self.view.showEmptyScreenMessage(text: EmptyScreenMessages.transactionDetailMessage)
}
//self.print(self.exchangeRateArray.count,self.exchangeRateArray[0])
}
}
else
{
Utilities.showBar(text: responseObject?.errorObject?.message)
}
}

How to convert Raw dictionary to JSON string?

I have this type of dictionary:
{
“event”: {
“type”: “message_create”, “message_create”: {
“target”: {
“recipient_id”: “RECIPIENT_USER_ID”
}, “message_data”: {
“text”: “Hello World!”,
}
}
}
I want to convert this dictionary into JSON string format, but not able to do it. Please anyone guide me on this.
This is the code till I am trying after sending message I am getting bad authenticating data message from server -
func sendMessage(_ userInfo: String) {
let requestURL = URL(string: "https://api.twitter.com/1.1/direct_messages/events/new.json")
Alamofire.request(requestURL!, method: .post,
encoding: URLEncoding.default,
headers: getRequestHeader()).responseJSON { (response) in
print(response)
switch response.result {
case .success:
print("Validation Successful")
case .failure(let error):
print("FAILURE ERROR : \(error.localizedDescription)")
print("ERROR : \(error)")
if let data = response.data {
print("Print Server Error: " + String(data: data, encoding: String.Encoding.utf8)!)
}
}
}
}
// MARK: - Get Request Header
func getRequestHeader() -> ([String: String]) {
return ["authorization": "","CONSUMER_KEY":"",
"CONSUMER_SECRET":"",
"oauth_secret":"7W2Gx4KEjz7d164NPvJaOktzhaSPpV3VNjvyjpIqaDc02",
"oauth_token":"2605063830-IffuOmn2tEajFXY6khbzmeMwNoUvGkQ8qrYonzw",
"oauth_version":"1.0",
"oauth_signature_method":"HMAC-SHA1",
"Content-Type": "application/json"
]
}
For the purpose of focusing on getting the json string (without caring about how you got the dictionary), I would assume that your myDict is the dictionary that you want to convert to json string:
let json = """
{
"event": {
"type": "message_create", "message_create": {
"target": {
"recipient_id": "RECIPIENT_USER_ID"
},
"message_data": {
"text": "Hello World!"
}
}
}
}
""".data(using: .utf8)
var myDict: [String: Any] = [: ]
do {
if let dict = try JSONSerialization.jsonObject(with: json!, options: []) as? [String: Any] {
myDict = dict
}
} catch {
print(error)
}
So now we want to convert myDict as a json string:
do {
// converting `myDict` to Json Data, and then
// getting our json as string from the `jsonData`:
if let jsonData = try JSONSerialization.data(withJSONObject: myDict, options: []) as? Data,
let jsonString = String(data: jsonData, encoding: .utf8) {
print(jsonString)
}
} catch {
print(error)
}
jsonString is now what are you looking for! you should see on the log:
{"event":{"type":"message_create","message_create":{"target":{"recipient_id":"RECIPIENT_USER_ID"},"message_data":{"text":"Hello
World!"}}}}
which is perfectly valid json.
public extension NSDictionary{
public func toJSONString() -> String{
if JSONSerialization.isValidJSONObject(self) {
do{
let data = try JSONSerialization.data(withJSONObject: self, options: JSONSerialization.WritingOptions(rawValue: 0))
if let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
return string as String
}
}catch {
print("error")
}
}
return ""
}
}

Convert JSON encoded class to dictionary for Alamofire parameters

Let's say I got the following struct
public class Response: Codable {
let status: String
let code: String
let id: String
}
What I want is to get the class properties and values as [String: Any] to send it through Alamofire like this:
let response: Response = Response(status: "A", code: "B", uuid: "C")
let data = try JSONEncoder().encode(res)
//Data to [String : Any]
Alamofire.request("endpoint", method: .post, parameters: params).responseJSON {
// Handle response
}
You can use something like this:
let response: Response = Response(status: "A", code: "B", uuid: "C")
let data = try JSONEncoder().encode(res)
//Data to [String : Any]
do {
let params = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any]
Alamofire.request("endpoint", method: .post, parameters: params).responseJSON {
// Handle response
}
} catch {
print(error)
}
Try using JSONSerialization as below I had used to get data from JSON
func HitApi(){
Alamofire.request(urlToGetTimeTable, method: .get, parameters: nil , encoding:URLEncoding.default).responseJSON { (response) in
if(response.result.isSuccess)
{
if let JSON = response.result.value
{
print("JSON: \(JSON)")
do {
//Clearing values in Array
self.subjectNameArray.removeAll()
//get data and serialise here to get [String:Any]
if let data = response.data,
let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
let dataDict = json["data"] as? [[String: Any]]
{
// iterate an array
for dict in dataDict
{
//get data from JSON Response
let subjectName = dict["subjects_id"] as? String
self.subjectNameArray.append(subjectName!)
}
// TableView Delegate & DataSource
// Reload TableView
self.tableView.dataSource = self;
self.tableView.delegate = self;
self.tableView.reloadData()
}
}
catch
{
//Error case
print("Error deserializing JSON: \(error)")
}
}
}
if(response.result.isFailure)
{
//Show Alert here //reason Failure
}
}
}
Give you an idea to get response as [String:Any] using son serialisation , you can use Above format in Post Method need some Modification. I deleted Rest code and showed main Code that was required

Accessing nested JSON data [duplicate]

I want to make one function in my swift project that converts String to Dictionary json format but I got one error:
Cannot convert expression's type (#lvalue NSData,options:IntegerLitralConvertible ...
This is my code:
func convertStringToDictionary (text:String) -> Dictionary<String,String> {
var data :NSData = text.dataUsingEncoding(NSUTF8StringEncoding)!
var json :Dictionary = NSJSONSerialization.JSONObjectWithData(data, options:0, error: nil)
return json
}
I make this function in Objective-C :
- (NSDictionary*)convertStringToDictionary:(NSString*)string {
NSError* error;
//giving error as it takes dic, array,etc only. not custom object.
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
return json;
}
Warning: this is a convenience method to convert a JSON string to a dictionary if, for some reason, you have to work from a JSON string. But if you have the JSON data available, you should instead work with the data, without using a string at all.
Swift 3
func convertToDictionary(text: String) -> [String: Any]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
let str = "{\"name\":\"James\"}"
let dict = convertToDictionary(text: str)
Swift 2
func convertStringToDictionary(text: String) -> [String:AnyObject]? {
if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
do {
return try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
print(error)
}
}
return nil
}
let str = "{\"name\":\"James\"}"
let result = convertStringToDictionary(str)
Original Swift 1 answer:
func convertStringToDictionary(text: String) -> [String:String]? {
if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
var error: NSError?
let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as? [String:String]
if error != nil {
println(error)
}
return json
}
return nil
}
let str = "{\"name\":\"James\"}"
let result = convertStringToDictionary(str) // ["name": "James"]
if let name = result?["name"] { // The `?` is here because our `convertStringToDictionary` function returns an Optional
println(name) // "James"
}
In your version, you didn't pass the proper parameters to NSJSONSerialization and forgot to cast the result. Also, it's better to check for the possible error. Last note: this works only if your value is a String. If it could be another type, it would be better to declare the dictionary conversion like this:
let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as? [String:AnyObject]
and of course you would also need to change the return type of the function:
func convertStringToDictionary(text: String) -> [String:AnyObject]? { ... }
I've updated Eric D's answer for Swift 5:
func convertStringToDictionary(text: String) -> [String:AnyObject]? {
if let data = text.data(using: .utf8) {
do {
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:AnyObject]
return json
} catch {
print("Something went wrong")
}
}
return nil
}
Swift 3:
if let data = text.data(using: String.Encoding.utf8) {
do {
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:Any]
print(json)
} catch {
print("Something went wrong")
}
}
With Swift 3, JSONSerialization has a method called json​Object(with:​options:​). json​Object(with:​options:​) has the following declaration:
class func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> Any
Returns a Foundation object from given JSON data.
When you use json​Object(with:​options:​), you have to deal with error handling (try, try? or try!) and type casting (from Any). Therefore, you can solve your problem with one of the following patterns.
#1. Using a method that throws and returns a non-optional type
import Foundation
func convertToDictionary(from text: String) throws -> [String: String] {
guard let data = text.data(using: .utf8) else { return [:] }
let anyResult: Any = try JSONSerialization.jsonObject(with: data, options: [])
return anyResult as? [String: String] ?? [:]
}
Usage:
let string1 = "{\"City\":\"Paris\"}"
do {
let dictionary = try convertToDictionary(from: string1)
print(dictionary) // prints: ["City": "Paris"]
} catch {
print(error)
}
let string2 = "{\"Quantity\":100}"
do {
let dictionary = try convertToDictionary(from: string2)
print(dictionary) // prints [:]
} catch {
print(error)
}
let string3 = "{\"Object\"}"
do {
let dictionary = try convertToDictionary(from: string3)
print(dictionary)
} catch {
print(error) // prints: Error Domain=NSCocoaErrorDomain Code=3840 "No value for key in object around character 9." UserInfo={NSDebugDescription=No value for key in object around character 9.}
}
#2. Using a method that throws and returns an optional type
import Foundation
func convertToDictionary(from text: String) throws -> [String: String]? {
guard let data = text.data(using: .utf8) else { return [:] }
let anyResult: Any = try JSONSerialization.jsonObject(with: data, options: [])
return anyResult as? [String: String]
}
Usage:
let string1 = "{\"City\":\"Paris\"}"
do {
let dictionary = try convertToDictionary(from: string1)
print(String(describing: dictionary)) // prints: Optional(["City": "Paris"])
} catch {
print(error)
}
let string2 = "{\"Quantity\":100}"
do {
let dictionary = try convertToDictionary(from: string2)
print(String(describing: dictionary)) // prints nil
} catch {
print(error)
}
let string3 = "{\"Object\"}"
do {
let dictionary = try convertToDictionary(from: string3)
print(String(describing: dictionary))
} catch {
print(error) // prints: Error Domain=NSCocoaErrorDomain Code=3840 "No value for key in object around character 9." UserInfo={NSDebugDescription=No value for key in object around character 9.}
}
#3. Using a method that does not throw and returns a non-optional type
import Foundation
func convertToDictionary(from text: String) -> [String: String] {
guard let data = text.data(using: .utf8) else { return [:] }
let anyResult: Any? = try? JSONSerialization.jsonObject(with: data, options: [])
return anyResult as? [String: String] ?? [:]
}
Usage:
let string1 = "{\"City\":\"Paris\"}"
let dictionary1 = convertToDictionary(from: string1)
print(dictionary1) // prints: ["City": "Paris"]
let string2 = "{\"Quantity\":100}"
let dictionary2 = convertToDictionary(from: string2)
print(dictionary2) // prints: [:]
let string3 = "{\"Object\"}"
let dictionary3 = convertToDictionary(from: string3)
print(dictionary3) // prints: [:]
#4. Using a method that does not throw and returns an optional type
import Foundation
func convertToDictionary(from text: String) -> [String: String]? {
guard let data = text.data(using: .utf8) else { return nil }
let anyResult = try? JSONSerialization.jsonObject(with: data, options: [])
return anyResult as? [String: String]
}
Usage:
let string1 = "{\"City\":\"Paris\"}"
let dictionary1 = convertToDictionary(from: string1)
print(String(describing: dictionary1)) // prints: Optional(["City": "Paris"])
let string2 = "{\"Quantity\":100}"
let dictionary2 = convertToDictionary(from: string2)
print(String(describing: dictionary2)) // prints: nil
let string3 = "{\"Object\"}"
let dictionary3 = convertToDictionary(from: string3)
print(String(describing: dictionary3)) // prints: nil
Swift 5
extension String {
func convertToDictionary() -> [String: Any]? {
if let data = data(using: .utf8) {
return try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
}
return nil
}
}
Swift 4
extension String {
func convertToDictionary() -> [String: Any]? {
if let data = self.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
}
Details
Xcode Version 10.3 (10G8), Swift 5
Solution
import Foundation
// MARK: - CastingError
struct CastingError: Error {
let fromType: Any.Type
let toType: Any.Type
init<FromType, ToType>(fromType: FromType.Type, toType: ToType.Type) {
self.fromType = fromType
self.toType = toType
}
}
extension CastingError: LocalizedError {
var localizedDescription: String { return "Can not cast from \(fromType) to \(toType)" }
}
extension CastingError: CustomStringConvertible { var description: String { return localizedDescription } }
// MARK: - Data cast extensions
extension Data {
func toDictionary(options: JSONSerialization.ReadingOptions = []) throws -> [String: Any] {
return try to(type: [String: Any].self, options: options)
}
func to<T>(type: T.Type, options: JSONSerialization.ReadingOptions = []) throws -> T {
guard let result = try JSONSerialization.jsonObject(with: self, options: options) as? T else {
throw CastingError(fromType: type, toType: T.self)
}
return result
}
}
// MARK: - String cast extensions
extension String {
func asJSON<T>(to type: T.Type, using encoding: String.Encoding = .utf8) throws -> T {
guard let data = data(using: encoding) else { throw CastingError(fromType: type, toType: T.self) }
return try data.to(type: T.self)
}
func asJSONToDictionary(using encoding: String.Encoding = .utf8) throws -> [String: Any] {
return try asJSON(to: [String: Any].self, using: encoding)
}
}
// MARK: - Dictionary cast extensions
extension Dictionary {
func toData(options: JSONSerialization.WritingOptions = []) throws -> Data {
return try JSONSerialization.data(withJSONObject: self, options: options)
}
}
Usage
let value1 = try? data.toDictionary()
let value2 = try? data.to(type: [String: Any].self)
let value3 = try? data.to(type: [String: String].self)
let value4 = try? string.asJSONToDictionary()
let value5 = try? string.asJSON(to: [String: String].self)
Test sample
Do not forget to paste the solution code here
func testDescriber(text: String, value: Any) {
print("\n//////////////////////////////////////////")
print("-- \(text)\n\n type: \(type(of: value))\n value: \(value)")
}
let json1: [String: Any] = ["key1" : 1, "key2": true, "key3" : ["a": 1, "b": 2], "key4": [1,2,3]]
var jsonData = try? json1.toData()
testDescriber(text: "Sample test of func toDictionary()", value: json1)
if let data = jsonData {
print(" Result: \(String(describing: try? data.toDictionary()))")
}
testDescriber(text: "Sample test of func to<T>() -> [String: Any]", value: json1)
if let data = jsonData {
print(" Result: \(String(describing: try? data.to(type: [String: Any].self)))")
}
testDescriber(text: "Sample test of func to<T>() -> [String] with cast error", value: json1)
if let data = jsonData {
do {
print(" Result: \(String(describing: try data.to(type: [String].self)))")
} catch {
print(" ERROR: \(error)")
}
}
let array = [1,4,5,6]
testDescriber(text: "Sample test of func to<T>() -> [Int]", value: array)
if let data = try? JSONSerialization.data(withJSONObject: array) {
print(" Result: \(String(describing: try? data.to(type: [Int].self)))")
}
let json2 = ["key1": "a", "key2": "b"]
testDescriber(text: "Sample test of func to<T>() -> [String: String]", value: json2)
if let data = try? JSONSerialization.data(withJSONObject: json2) {
print(" Result: \(String(describing: try? data.to(type: [String: String].self)))")
}
let jsonString = "{\"key1\": \"a\", \"key2\": \"b\"}"
testDescriber(text: "Sample test of func to<T>() -> [String: String]", value: jsonString)
print(" Result: \(String(describing: try? jsonString.asJSON(to: [String: String].self)))")
testDescriber(text: "Sample test of func to<T>() -> [String: String]", value: jsonString)
print(" Result: \(String(describing: try? jsonString.asJSONToDictionary()))")
let wrongJsonString = "{\"key1\": \"a\", \"key2\":}"
testDescriber(text: "Sample test of func to<T>() -> [String: String] with JSONSerialization error", value: jsonString)
do {
let json = try wrongJsonString.asJSON(to: [String: String].self)
print(" Result: \(String(describing: json))")
} catch {
print(" ERROR: \(error)")
}
Test log
//////////////////////////////////////////
-- Sample test of func toDictionary()
type: Dictionary<String, Any>
value: ["key4": [1, 2, 3], "key2": true, "key3": ["a": 1, "b": 2], "key1": 1]
Result: Optional(["key4": <__NSArrayI 0x600002a35380>(
1,
2,
3
)
, "key2": 1, "key3": {
a = 1;
b = 2;
}, "key1": 1])
//////////////////////////////////////////
-- Sample test of func to<T>() -> [String: Any]
type: Dictionary<String, Any>
value: ["key4": [1, 2, 3], "key2": true, "key3": ["a": 1, "b": 2], "key1": 1]
Result: Optional(["key4": <__NSArrayI 0x600002a254d0>(
1,
2,
3
)
, "key2": 1, "key1": 1, "key3": {
a = 1;
b = 2;
}])
//////////////////////////////////////////
-- Sample test of func to<T>() -> [String] with cast error
type: Dictionary<String, Any>
value: ["key4": [1, 2, 3], "key2": true, "key3": ["a": 1, "b": 2], "key1": 1]
ERROR: Can not cast from Array<String> to Array<String>
//////////////////////////////////////////
-- Sample test of func to<T>() -> [Int]
type: Array<Int>
value: [1, 4, 5, 6]
Result: Optional([1, 4, 5, 6])
//////////////////////////////////////////
-- Sample test of func to<T>() -> [String: String]
type: Dictionary<String, String>
value: ["key1": "a", "key2": "b"]
Result: Optional(["key1": "a", "key2": "b"])
//////////////////////////////////////////
-- Sample test of func to<T>() -> [String: String]
type: String
value: {"key1": "a", "key2": "b"}
Result: Optional(["key1": "a", "key2": "b"])
//////////////////////////////////////////
-- Sample test of func to<T>() -> [String: String]
type: String
value: {"key1": "a", "key2": "b"}
Result: Optional(["key1": a, "key2": b])
//////////////////////////////////////////
-- Sample test of func to<T>() -> [String: String] with JSONSerialization error
type: String
value: {"key1": "a", "key2": "b"}
ERROR: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 21." UserInfo={NSDebugDescription=Invalid value around character 21.}
I found code which converts the json string to NSDictionary or NSArray. Just add the extension.
SWIFT 3.0
HOW TO USE
let jsonData = (convertedJsonString as! String).parseJSONString
EXTENSION
extension String
{
var parseJSONString: AnyObject?
{
let data = self.data(using: String.Encoding.utf8, allowLossyConversion: false)
if let jsonData = data
{
// Will return an object or nil if JSON decoding fails
do
{
let message = try JSONSerialization.jsonObject(with: jsonData, options:.mutableContainers)
if let jsonResult = message as? NSMutableArray {
return jsonResult //Will return the json array output
} else if let jsonResult = message as? NSMutableDictionary {
return jsonResult //Will return the json dictionary output
} else {
return nil
}
}
catch let error as NSError
{
print("An error occurred: \(error)")
return nil
}
}
else
{
// Lossless conversion of the string was not possible
return nil
}
}
}
In 2022 year, I'm using JSONDecoder.
struct GroceryProduct: Codable {
var name: String
var points: Int
var description: String?
}
let json = """
{
"name": "Durian",
"points": 600,
"description": "A fruit with a distinctive scent."
}
""".data(using: .utf8)!
let decoder = JSONDecoder()
do {
let product = try decoder.decode(GroceryProduct.self, from: json)
}
catch { //error handle }
print(product.name) // Prints "Durian"
let JSONData = jsonString.data(using: .utf8)!
let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
guard let userDictionary = jsonResult as? Dictionary<String, AnyObject> else {
throw NSError()}

Not getting expected results parsing JSON in Swift

I have a web service that look like this
[
{
"id_test" : "1",
"title":"test1"
},
{
"id_test" : "2",
"title":"test2"
},{
"id_test" : "3",
"title":"test3"
},
]
I use this code to read the json in my program:
func downloadJsonWithUrl()
{
let url = URL(string:"weserviceurl")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil
{
print("Error")
}
else
{
if let content = data
{
do
{
let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
print(myJson)
}
catch
{
}
}
}
}
task.resume()
}
My question is, at the moment to use use this code below my serialization:
if let info = myJson as? NSArray
{
if let categories = info["title"]
{
print(categories)
}
}
does not work. It returns empty. Why?
Try this
func downloadJsonWithUrl() {
let url = URL(string:"link")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil {
print("Error")
} else {
if let content = data {
do {
let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as! [AnyObject]
var categories: [String] = []
for item in myJson {
categories.append(item["title"] as! String)
}
print(categories)
} catch {
print(error)
}
}
}
}
task.resume()
}
You should use swift Array and Dictionary types. For example, ... as? [[String: Any]] says that you're expecting an array of dictionaries:
let task = URLSession.shared.dataTask(with: url!) { data, response, error in
guard let data = data, error == nil else {
print("\(error)")
return
}
guard let json = try? JSONSerialization.jsonObject(with: data), let array = json as? [[String: Any]] else {
print("not JSON array of dictionaries")
return
}
for dictionary in array {
if let idTest = dictionary["id_test"], let title = dictionary["title"] {
print("\(idTest): \(title)")
}
}
}