Categories

  • Development

Tags

  • swift
  • tutorial
  • mobile
  • ios
  • json

Next step for me is composed of two things:

1 - Change code towards Clean Architecture 2 - Implement API connection

And I know this is going to sound controverse but I´m going to show JSON parsing, I rather talk about this first as I´m getting back to this project and API interaction is going to be piece of cake.

Easy way

To create our JSONInteractor, which will be responsible for parsing JSON for us we only need JSONSerialization class, really simple and just a few lines of code.

public class JSONInteractor {
    
    public init() {}
    
    public func parseJsonObject(data: Data) -> [String: Any]? {
        do {
            let json = try JSONSerialization.jsonObject(with: data) as? [String:Any]
            return json
        }  catch {
            return nil
        }
    }
    
    public func parseJsonArray(data: Data) -> [Any]? {
        do {
            let json = try JSONSerialization.jsonObject(with: data) as? [Any]
            return json
        }  catch {
            return nil
        }
    }
    
}

The alternative with empty object/array instead of returning nil is also great.

public class JSONInteractor {
    
    public init() {}
    
    public func parseJsonObject(data: Data) -> [String: Any] {
        do {
            let json = try JSONSerialization.jsonObject(with: data) as! [String:Any]
            return json
        }  catch {
            return [String:Any]()
        }
    }
    
    public func parseJsonArray(data: Data) -> [Any] {
        do {
            let json = try JSONSerialization.jsonObject(with: data) as! [Any]
            return json
        }  catch {
            return []
        }
    }
    
}

Just decide how you want to handle errors and exceptions.

Fancy way

Use a pod to do the job for you, handle edge cases, represent JSON null and other JSON related stuff our simple code can´t right now. For instance SwiftyJSON, which is the one I use normally will reduce your code to:

let json = JSON(data: dataFromNetworking)
if let userName = json[0]["user"]["name"].string {
  //Now you got your value
}

No need for JSONInteractor.

Conclusion

  1. Using JSON in Swift is simple and easy.
  2. Mapping JSON in swift is tedious