Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple and clean way to convert JSON string to Object in Swift

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.

like image 664
Hasan Nizamani Avatar asked Sep 02 '14 10:09

Hasan Nizamani


People also ask

How can I convert JSON to object?

Use the JavaScript function JSON. parse() to convert text into a JavaScript object: const obj = JSON.

What is JSON parse () method?

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.

Is JSON easy to parse?

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.


2 Answers

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 
like image 51
Just a coder Avatar answered Sep 20 '22 14:09

Just a coder


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,

like image 34
Maxim Shoustin Avatar answered Sep 18 '22 14:09

Maxim Shoustin