Home » Ios » How to parse a JSON file in swift?

How to parse a JSON file in swift?

Posted by: admin November 30, 2017 Leave a comment

Questions:

I have a JSON file, want to parse and use list of objects in table view. Can any one share the code to parse JSON file in swift.

Answers:

Couldn’t be more simple:

import Foundation

var error: NSError?
let jsonData: NSData = /* get your json data */

let jsonDict = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as NSDictionary

Questions:
Answers:

How to call a web service and get a response in Swift Check IT

Making the API Request

var request: NSURLRequest = NSURLRequest(URL: url)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)

Preparing for the response

Declare an array as below

var data: NSMutableData = NSMutableData()

Receiving the response

1.

func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
   // Received a new request, clear out the data object
   self.data = NSMutableData()
}

2.

func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
   // Append the received chunk of data to our data object
   self.data.appendData(data)
}

3.

func connectionDidFinishLoading(connection: NSURLConnection!) {
   // Request complete, self.data should now hold the resulting info
   // Convert the retrieved data in to an object through JSON deserialization
   var err: NSError
   var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

   if jsonResult.count>0 && jsonResult["results"].count>0 {
      var results: NSArray = jsonResult["results"] as NSArray
      self.tableData = results
      self.appsTableView.reloadData()

   }
}

When NSURLConnection receives a response, we can expect the didReceiveResponse method to be called on our behalf. At this point we simply reset our data by saying self.data = NSMutableData(), creating a new empty data object.

After a connection is made, we will start receiving data in the method didReceiveData. The data argument being passed in here is where all our juicy information comes from. We need to hold on to each chunk that comes in, so we append it to the self.data object we cleared out earlier.

Finally, when the connection is done and all data has been received, connectionDidFinishLoading is called and we’re ready to use the data in our app. Hooray!

The connectionDidFinishLoading method here uses the NSJSONSerialization class to convert our raw data in to useful Dictionary objects by deserializing the results from your Url.

Questions:
Answers:

I just wrote a class called JSON, which makes JSON handling in Swift as easy as JSON object in ES5.

Turn your swift object to JSON like so:

let obj:[String:AnyObject] = [
    "array": [JSON.null, false, 0, "",[],[:]],
    "object":[
        "null":   JSON.null,
        "bool":   true,
        "int":    42,
        "double": 3.141592653589793,
        "string": "a α\t弾\n?",
        "array":  [],
        "object": [:]
    ],
    "url":"http://blog.livedoor.com/dankogai/"
]

let json = JSON(obj)
json.toString()

…or string…

let json = JSON.parse("{\"array\":[...}")

…or URL.

let json = JSON.fromURL("http://api.dan.co.jp/jsonenv")
Tree Traversal

Just traverse elements via subscript:

json["object"]["null"].asNull       // NSNull()
// ...
json["object"]["string"].asString   // "a α\t弾\n?"
json["array"][0].asNull             // NSNull()
json["array"][1].asBool             // false
// ...

Just like SwiftyJSON you don’t worry if the subscripted entry does not exist.

if let b = json["noexistent"][1234567890]["entry"].asBool {
    // ....
} else {
    let e = json["noexistent"][1234567890]["entry"].asError
    println(e)
}

If you are tired of subscripts, add your scheme like so:

//// schema by subclassing
class MyJSON : JSON {
    init(_ obj:AnyObject){ super.init(obj) }
    init(_ json:JSON)  { super.init(json) }
    var null  :NSNull? { return self["null"].asNull }
    var bool  :Bool?   { return self["bool"].asBool }
    var int   :Int?    { return self["int"].asInt }
    var double:Double? { return self["double"].asDouble }
    var string:String? { return self["string"].asString }
}

And you go:

let myjson = MyJSON(obj)
myjson.object.null
myjson.object.bool
myjson.object.int
myjson.object.double
myjson.object.string
// ...

Hope you like it.

With the new xCode 7.3+ its important to add your domain to the exception list (How can I add NSAppTransportSecurity to my info.plist file?), refer to this posting for instructions, otherwise you will get a transport authority error.

Questions:
Answers:

Here is a code to make the conversions between JSON and NSData in Swift 2.0

// Convert from NSData to json object
func nsdataToJSON(data: NSData) -> AnyObject? {
    do {
        return try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers)
    } catch let myJSONError {
        print(myJSONError)
    }
    return nil
}

// Convert from JSON to nsdata
func jsonToNSData(json: AnyObject) -> NSData?{
    do {
        return try NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.PrettyPrinted)
    } catch let myJSONError {
        print(myJSONError)
    }
    return nil;
}

Questions:
Answers:

I also wrote a small library which is specialized for the mapping of the json response into an object structure. I am internally using the library json-swift from David Owens. Maybe it is useful for someone else.

https://github.com/prine/ROJSONParser

Example Employees.json

{
"employees": [
  {
    "firstName": "John",
    "lastName": "Doe",
    "age": 26
  },
  {
    "firstName": "Anna",
    "lastName": "Smith",
    "age": 30
  },
  {
    "firstName": "Peter",
    "lastName": "Jones",
    "age": 45
  }]
}

As next step you have to create your data model (EmplyoeeContainer and Employee).

Employee.swift

class Employee : ROJSONObject {

    required init() {
        super.init();
    }

    required init(jsonData:AnyObject) {
        super.init(jsonData: jsonData)
    }

    var firstname:String {
        return Value<String>.get(self, key: "firstName")
    }

    var lastname:String {
        return Value<String>.get(self, key: "lastName")            
    }

    var age:Int {
        return Value<Int>.get(self, key: "age")
    }
}

EmployeeContainer.swift

class EmployeeContainer : ROJSONObject {
    required init() {
        super.init();
    }

    required init(jsonData:AnyObject) {
        super.init(jsonData: jsonData)
    }

    lazy var employees:[Employee] = {
        return Value<[Employee]>.getArray(self, key: "employees") as [Employee]
    }()
}

Then to actually map the objects from the JSON response you only have to pass the data into the EmployeeContainer class as param in the constructor. It does automatically create your data model.

 var baseWebservice:BaseWebservice = BaseWebservice();

  var urlToJSON = "http://prine.ch/employees.json"

  var callbackJSON = {(status:Int, employeeContainer:EmployeeContainer) -> () in
    for employee in employeeContainer.employees {
      println("Firstname: \(employee.firstname) Lastname: \(employee.lastname) age: \(employee.age)")
    }
  }

  baseWebservice.get(urlToJSON, callback:callbackJSON)

The console output looks then like the following:

Firstname: John Lastname: Doe age: 26
Firstname: Anna Lastname: Smith age: 30
Firstname: Peter Lastname: Jones age: 45

Questions:
Answers:

Parsing JSON in Swift is an excellent job for code generation. I’ve created a tool at http://www.guideluxe.com/JsonToSwift to do just that.

You supply a sample JSON object with a class name and the tool will generate a corresponding Swift class, as well as any needed subsidiary Swift classes, to represent the structure implied by the sample JSON. Also included are class methods used to populate Swift objects, including one that utilizes the NSJSONSerialization.JSONObjectWithData method. The necessary mappings from the NSArray and NSDictionary objects are provided.

From the generated code, you only need to supply an NSData object containing JSON that matches the sample provided to the tool.

Other than Foundation, there are no dependencies.

My work was inspired by http://json2csharp.com/, which is very handy for .NET projects.

Here’s how to create an NSData object from a JSON file.

let fileUrl: NSURL = NSBundle.mainBundle().URLForResource("JsonFile", withExtension: "json")!
let jsonData: NSData = NSData(contentsOfURL: fileUrl)!

Questions:
Answers:

Step 1. Install Swifty Json https://github.com/SwiftyJSON/SwiftyJSON

Note: if you are looking for this, there’s also a high chance you don’t know how to install swifty. Follow the instructions on https://guides.cocoapods.org/using/getting-started.html#toc_3

sudo gem install cocoapods

cd ~/Path/To/Folder/Containing/ShowTracker

Next enter this command:

pod init

This will create a default Podfile for your project. The Podfile is where you define the dependencies your project relies on.

Type this command to open Podfile using Xcode for editing:

open -a Xcode Podfile

Add the Swifty into the podfile

platform :ios, '8.0'
use_frameworks!

target 'MyApp' do
    pod 'SwiftyJSON', '~> X.X.X'
end

Step 2. Check this example

var mURL = NSURL(string: "http://api.openweathermap.org/data/2.5/weather?q=London,uk&units=metric")


if mURL == nil{
      println("You are stupid")
      return
          }
var request = NSURLRequest(URL: mURL!)

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in


   if data != nil {
                        var mJSON = JSON(data: data!)

                        if let current_conditions = mJSON["weather"][0]["description"].string{
                            println("Current conditions: " + current_conditions)
                        } else {
                            println("MORON!")
                        }

                        if let current_temperature = mJSON["main"]["temp"].double{
                                 println("Temperature: "+ String(format:"%.f", current_temperature)  + "°C"
                        } else {
                            println("MORON!")
                        }

                    }
                })

Step 3. Profit

Questions:
Answers:

SwiftJSONParse: Parse JSON like a badass

Dead-simple and easy to read!

Example: get the value "mrap" from nicknames as a String from this JSON response

{
    "other": {
        "nicknames": ["mrap", "Mikee"]
}

It takes your json data NSData as it is, no need to preprocess.

let parser = JSONParser(jsonData)

if let handle = parser.getString("other.nicknames[0]") {
    // that's it!
}

Disclaimer: I made this and I hope it helps everyone. Feel free to improve on it!

Questions:
Answers:

Using ObjectMapper framework

if let path = Bundle(for: BPPView.self).path(forResource: jsonFileName, ofType: "json") {
        do {
            let data = try Data(contentsOf: URL(fileURLWithPath: path), options: NSData.ReadingOptions.mappedIfSafe)
            let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
            self.levels = Mapper<Level>().mapArray(JSONArray: (json as! [[String : Any]]))!
            print(levels.count)
        } catch let error as NSError {
            print(error.localizedDescription)
        }
    } else {
        print("Invalid filename/path.")
    }

Before you should prepare the set of appropriate :Mappable objects to parse into

import UIKit 
import ObjectMapper
class Level: Mappable {
var levelName = ""
var levelItems = [LevelItem]()

required init?(map: Map) {

}

// Mappable
func mapping(map: Map) {
    levelName <- map["levelName"]
    levelItems <- map["levelItems"]
}
}

 import UIKit 
import ObjectMapper 
class LevelItem: Mappable {
var frontBackSide = BPPFrontBack.Undefined
var fullImageName = ""
var fullImageSelectedName = ""
var bodyParts = [BodyPart]()

required init?(map: Map) {

}

// Mappable
func mapping(map: Map) {
    frontBackSide <- map["frontBackSide"]
    fullImageName <- map["fullImageName"]
    fullImageSelectedName <- map["fullImageSelectedName"]
    bodyParts <- map["bodyParts"]
}}

Questions:
Answers:

Swift 3

let parsedResult: [String: AnyObject]

do {

    parsedResult = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:AnyObject]

} catch {

    // Display an error or return or whatever
}

data – it’s Data type (Structure) (i.e. returned by some server response)

Questions:
Answers:

The entire viewcontroller which show data in collecction view using two methods of json parsig

@IBOutlet weak var imagecollectionview: UICollectionView!
lazy var data = NSMutableData()
var dictdata : NSMutableDictionary = NSMutableDictionary()
override func viewDidLoad() {
    super.viewDidLoad()
    startConnection()
    startNewConnection()
    // Do any additional setup after loading the view, typically from a nib.
}


func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return dictdata.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    let cell  = collectionView.dequeueReusableCellWithReuseIdentifier("CustomcellCollectionViewCell", forIndexPath: indexPath) as! CustomcellCollectionViewCell
    cell.name.text = dictdata.valueForKey("Data")?.valueForKey("location") as? String
    let url = NSURL(string: (dictdata.valueForKey("Data")?.valueForKey("avatar_url") as? String)! )

    LazyImage.showForImageView(cell.image, url:"URL
    return cell
}
func collectionView(collectionView: UICollectionView,
                    layout collectionViewLayout: UICollectionViewLayout,
                           sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    let kWhateverHeightYouWant = 100
    return CGSizeMake(self.view.bounds.size.width/2, CGFloat(kWhateverHeightYouWant))
}

func startNewConnection()
{

   let url: URL = URL(string: "YOUR URL" as String)!
    let session = URLSession.shared

    let request = NSMutableURLRequest(url: url as URL)
    request.httpMethod = "GET" //set the get or post according to your request

    //        request.cachePolicy = NSURLRequest.CachePolicy.ReloadIgnoringCacheData
    request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData

    let task = session.dataTask(with: request as URLRequest) {
        ( data, response, error) in

        guard let _:NSData = data as NSData?, let _:URLResponse = response, error == nil else {
            print("error")
            return
        }

       let jsonString = NSString(data: data!, encoding:String.Encoding.utf8.rawValue) as! String
               }
    task.resume()

}

func startConnection(){
    let urlPath: String = "your URL"
    let url: NSURL = NSURL(string: urlPath)!
    var request: NSURLRequest = NSURLRequest(URL: url)
    var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!
    connection.start()
}

func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
    self.data.appendData(data)
}

func buttonAction(sender: UIButton!){
    startConnection()
}

func connectionDidFinishLoading(connection: NSURLConnection!) {
    do {
        let JSON = try NSJSONSerialization.JSONObjectWithData(self.data, options:NSJSONReadingOptions(rawValue: 0))
        guard let JSONDictionary :NSDictionary = JSON as? NSDictionary else {
            print("Not a Dictionary")
            // put in function
            return
        }
        print("JSONDictionary! \(JSONDictionary)")
        dictdata.setObject(JSONDictionary, forKey: "Data")

        imagecollectionview.reloadData()
    }
    catch let JSONError as NSError {
        print("\(JSONError)")
    }    }

Questions:
Answers:

This parser uses generics to cast JSON to Swift types which reduces the code you need to type.

https://github.com/evgenyneu/JsonSwiftson

struct Person {
  let name: String?
  let age: Int?
}

let mapper = JsonSwiftson(json: "{ \"name\": \"Peter\", \"age\": 41 }")

let person: Person? = Person(
  name: mapper["name"].map(),
  age: mapper["age"].map()
)

Questions:
Answers:

Swift2 iOs9

   let miadata = NSData(contentsOfURL: NSURL(string: "https://myWeb....php")!)

    do{
        let MyData = try NSJSONSerialization.JSONObjectWithData(miadata!, options: NSJSONReadingOptions.MutableContainers) as? NSArray

         print(".........\(MyData)")

    }
    catch let error as NSError{
        // error.description
        print(error.description)
    }

Questions:
Answers:

Below is a Swift Playground example:

import UIKit

let jsonString = "{\"name\": \"John Doe\", \"phone\":123456}"

let data = jsonString.data(using: .utf8)

var jsonObject: Any
do {
    jsonObject = try JSONSerialization.jsonObject(with: data!) as Any

    if let obj = jsonObject as? NSDictionary {
        print(obj["name"])
    }
} catch {
    print("error")
}

Questions:
Answers:

In Swift3

For a Json Like.

   {"GetDetailsResult":{"Id":0,"Password":null,"Social":0,"UserMail":null,"UserName":null}}.

First we need to create the jsonObect .

  let json = try JSONSerialization.jsonObject(with: data!, options: []) as! [String: AnyObject]

Then we Need to take the data from first Key:(GetDetailsResult).

let details = json["GetDetailsResult"]! as! [String: AnyObject]

After that we need to set the Single value into Variables

  let loggedUser = details["UserName"] as! String