Creating model for complex json in swift

Abhayjeet Singh
2 min readFeb 14, 2021

--

Using model is a good practice while API calling but it’s not easy when there is very nested tree json but don’t worry it’s very easy if you use some online tools. There is http://www.jsoncafe.com/ website by which we can convert our json response into swift code very easily, no matter how much complex it is. I am going to use ObjectMapper library to create our model & we need pod ‘ObjectMapper’, ‘~> 3.4’ for this now install the pod.

# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
target 'Auth' do
# Comment the next line if you don't want to use dynamic frameworks
use_frameworks!
# Pods for Auth
pod 'Alamofire', '~> 5.2'
pod 'ObjectMapper', '~> 3.4'
end

we want to show news article which has nested json response from below url

http://newsapi.org/v2/everything?q=tesla&from=2021-01-13&sortBy=publishedAt&apiKey=99b660498f9345c2bf359c4d6c4fd2cf

now convert the response in swift struct (Mapper).

// News modelimport Foundationimport ObjectMapperstruct News: Mappable {var articles: [Article]?var status: String?var totalResults: Int?init?(map: Map) { }mutating func mapping(map: Map) {articles <- map["articles"]status <- map["status"]totalResults <- map["totalResults"]}}struct Article: Mappable {var author: AnyObject?var content: String?var description: String?var publishedAt: String?var source: Source?var title: String?var url: String?var urlToImage: String?init?(map: Map) { }mutating func mapping(map: Map) {author <- map["author"]content <- map["content"]description <- map["description"]publishedAt <- map["publishedAt"]source <- map["source"]title <- map["title"]url <- map["url"]urlToImage <- map["urlToImage"]}}struct Source: Mappable {var id: AnyObject?var name: String?init?(map: Map) { }mutating func mapping(map: Map) {id <- map["id"]name <- map["name"]}}
view controller
import Alamofireimport UIKitclass ViewController: UIViewController {@IBOutlet weak var newsLabel: UILabel!let newsUrl = "http://newsapi.org/v2/everything?q=tesla&from=2021-01-13&sortBy=publishedAt&apiKey=99b660498f9345c2bf359c4d6c4fd2cf"override func viewDidLoad() {super.viewDidLoad()}func getNews() {let header:HTTPHeaders = [.contentType("application/json")]AF.request(newsUrl, method: .get, parameters: nil, encoding: URLEncoding.default, headers: header).response { response inswitch response.result {case .success(let data):do {let data = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)let responsedata = data as? [String:Any] ?? [:]let a = News(JSON: responsedata)self.newsLabel.text = a?.articles?[0].description} catch {debugPrint(error)}breakcase .failure(let error):print(error)}}}@IBAction func newsButtonAction(_ sender: UIButton) {getNews()}}

--

--

Abhayjeet Singh
Abhayjeet Singh

Written by Abhayjeet Singh

iOS lover; Sharing & Writing strengthen my knowledge!

No responses yet