I have been searching for days to convert a fairly simple JSON string to an object type in Swift but with no avail.
Here is the code for web service call:
func GetAllBusiness() { Alamofire.request(.GET, "http://MyWebService/").responseString { (request, response, string, error) in println(string) } }
I have a swift struct Business.swift:
struct Business { var Id : Int = 0 var Name = "" var Latitude = "" var Longitude = "" var Address = "" }
Here is my test service deployed:
[ { "Id": 1, "Name": "A", "Latitude": "-35.243256", "Longitude": "149.110701", "Address": null }, { "Id": 2, "Name": "B", "Latitude": "-35.240592", "Longitude": "149.104843", "Address": null } ... ]
It would be a delight if someone guide me through this.
Thanks.
Use the JavaScript function JSON. parse() to convert text into a JavaScript object: const obj = JSON.
parse() The JSON. parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.
JSON is a data interchange format that is easy to parse and generate. JSON is an extension of the syntax used to describe object data in JavaScript. Yet, it's not restricted to use with JavaScript. It has a text format that uses object and array structures for the portable representation of data.
for swift 3/4
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) } }
Example Usage:
let dict = myString.toJSON() as? [String:AnyObject] // can be any type here
Here are some tips how to begin with simple example.
Consider you have following JSON Array String (similar to yours) like:
var list:Array<Business> = [] // left only 2 fields for demo struct Business { var id : Int = 0 var name = "" } var jsonStringAsArray = "[\n" + "{\n" + "\"id\":72,\n" + "\"name\":\"Batata Cremosa\",\n" + "},\n" + "{\n" + "\"id\":183,\n" + "\"name\":\"Caldeirada de Peixes\",\n" + "},\n" + "{\n" + "\"id\":76,\n" + "\"name\":\"Batata com Cebola e Ervas\",\n" + "},\n" + "{\n" + "\"id\":56,\n" + "\"name\":\"Arroz de forma\",\n" + "}]" // convert String to NSData var data: NSData = jsonStringAsArray.dataUsingEncoding(NSUTF8StringEncoding)! var error: NSError? // convert NSData to 'AnyObject' let anyObj: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: &error) println("Error: \(error)") // convert 'AnyObject' to Array<Business> list = self.parseJson(anyObj!) //=============== func parseJson(anyObj:AnyObject) -> Array<Business>{ var list:Array<Business> = [] if anyObj is Array<AnyObject> { var b:Business = Business() for json in anyObj as Array<AnyObject>{ b.name = (json["name"] as AnyObject? as? String) ?? "" // to get rid of null b.id = (json["id"] as AnyObject? as? Int) ?? 0 list.append(b) }// for } // if return list }//func
[EDIT]
To get rid of null changed to:
b.name = (json["name"] as AnyObject? as? String) ?? "" b.id = (json["id"] as AnyObject? as? Int) ?? 0
See also Reference of Coalescing Operator (aka ??
)
Hope it will help you to sort things out,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With