How to Parse JSON in iOS App

How to parse JSON in iOS App

I haven't done JSON parsing myself in an iOS App, but you should be able to use a library like the json-framework. This library will allow you to easily parse JSON and generate json from dictionaries / arrays (that's really all JSON is composed of).

SBJson docs:

JSON is mapped to Objective-C types in the following way:

  • null -> NSNull
  • string -> NSString
  • array -> NSMutableArray
  • object -> NSMutableDictionary
  • true -> NSNumber's -numberWithBool:YES
  • false -> NSNumber's -numberWithBool:NO
  • integer up to 19 digits -> NSNumber's -numberWithLongLong:
  • all other numbers -> NSDecimalNumber

Since Objective-C doesn't have a dedicated class for boolean values,
these turns into NSNumber instances. However, since these are
initialised with the -initWithBool: method they round-trip back to JSON
properly. In other words, they won't silently suddenly become 0 or 1;
they'll be represented as 'true' and 'false' again.

As an optimisation integers up to 19 digits in length (the max length
for signed long long integers) turn into NSNumber instances, while
complex ones turn into NSDecimalNumber instances. We can thus avoid any
loss of precision as JSON allows ridiculously large numbers.

@page objc2json Objective-C to JSON

Objective-C types are mapped to JSON types in the following way:

  • NSNull -> null
  • NSString -> string
  • NSArray -> array
  • NSDictionary -> object
  • NSNumber's -initWithBool:YES -> true
  • NSNumber's -initWithBool:NO -> false
  • NSNumber -> number

@note In JSON the keys of an object must be strings. NSDictionary
keys need not be, but attempting to convert an NSDictionary with
non-string keys into JSON will throw an exception.

NSNumber instances created with the -numberWithBool: method are
converted into the JSON boolean "true" and "false" values, and vice
versa. Any other NSNumber instances are converted to a JSON number the
way you would expect.

Tutorials

Are there any tutorials? Yes! These are all tutorials provided by
third-party people:

JSON Framework for iPhone - a Flickr tutorial in three parts by John
Muchow. JSON Over HTTP On The iPhone - by Dan Grigsby. AS3 to Cocoa touch: JSON by Andy Jacobs.

There are other libraries you can check out as well like TouchJSON, JSONKit, Yet Another JSON Library

how to parse json data from local files?

Please note that variable JSON in your code is an array of objects.
You have to cast it properly.

func jsonTwo(){
let url = Bundle.main.url(forResource: "car_list", withExtension: "json")!
let data = try! Data(contentsOf: url)
let JSON = try! JSONSerialization.jsonObject(with: data, options: [])
print(".........." , JSON , ".......")
if let jsonArray = JSON as? [[String: Any]] {
for item in jsonArray {
let brand = item["brand"] as? String ?? "No Brand" //A default value
print("=======",brand,"=======")
}
}
}

How to parse a JSON file in swift?

This answer was last revised for Swift 5.3 and iOS 14.4 SDK.


Given some already obtained JSON data, you can use JSONDecoder to decode it into your Decodable model (or a collection of models).

let data: Data = /* obtain your JSON data */
let model = try JSONDecoder().decode(Model.self, from: data)

Such model must conform to the Decodable protocol and contain correct mapping between properties and JSON dictionary keys. As an example, consider the following JSON array containing search results of cities beginning with "Wa".

[
{
"id": 123,
"city": "Washington",
"region": "D.C.",
"country": "United States"
},
{
"id": 456,
"city": "Warsaw",
"region": "Mazowieckie",
"country": "Poland"
},
...
]

For that, you need to create a model that contains the correct properties of correct types. If you're using a web API, its documentation will be of great help here.

struct SearchResult: Decodable {
let id: Int
let city: String
let region: String
let country: String
}

Then decode the data with JSONDecoder:

let results = try JSONDecoder().decode([SearchResult].self, from: data)

Given a new array of decoded search results, call one of UITableView's functions to reload its data. Note that the decode function can throw an error which you must somehow handle.

To learn more about decoding custom types in Swift and more advanced usage of the Codable APIs, I recommend checking out this documentation article.

Best way to fetch and parse JSON in an iOS App?

I find that the best way to do it is indeed by using json-framework for json parsing and generation, and ASIHTTPRequest for the http communications.

This is my setup, and it's wonderfully simple to work with.

Swift 5 Parse Json data from https request

you need to do.

  1. convert responsedata to json

  2. read the formate(Here you will get dictionary) which you get.

        guard let url = URL(string: "https://sochain.com//api/v2/get_price/DOGE/USD") else { return }

    let task = URLSession.shared.dataTask(with: url) { data, response, error in

    guard let data = data, error == nil else { return }

    do {
    // make sure this JSON is in the format we expect
    // convert data to json
    if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
    // try to read out a dictionary
    print(json)
    if let data = json["data"] as? [String:Any] {
    print(data)
    if let prices = data["prices"] as? [[String:Any]] {
    print(prices)
    let dict = prices[0]
    print(dict)
    if let price = dict["price"] as? String{
    print(price)
    }
    }
    }
    }
    } catch let error as NSError {
    print("Failed to load: \(error.localizedDescription)")
    }

    }

    task.resume()

Using Swift 3, how can I parse a JSON file so that I can access the data globally?

Create a new Swift File like GlobalClass.Swift

import Foundation and UIKit in GlobalClass
make function to read location like this:-

func readLocation() ->[String:Any]?{
do {
if let file = Bundle.main.url(forResource: "locations", withExtension: "json") {
let data = try Data(contentsOf: file)
let json = try JSONSerialization.jsonObject(with: data, options: [.mutableContainers])
if let object = json as? [String: Any] {
return object
}
return nil
}
} catch {
print(error.localizedDescription)
}
return nil
}

and call this function from TableView like this:-

  override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cellIdentifier = "cell"
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! LocationTableViewCell

// Configure the cell
if let locationJson = readLocation(){
if let locations = locationJson["location"] as? [[String:Any]]{
cell.nameLabel.text = locations[indexPath.row]["name"] as! String
cell.thumbnailImageView.image = UIImage(named: (locations[indexPath.row]["image"] as! String))
cell.locationLabel.text = locations[indexPath.row]["location"] as! String
cell.typeLabel.text = locations[indexPath.row]["type"] as! String
cell.accessoryType = (locations[indexPath.row]["isVisited"] as! Bool) ? .checkmark : .none
}
}
return cell
}

and number of rows in section should be

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let locationJson = readLocation(){
if let locations = locationJson["location"] as? [[String:Any]]{
return locations.count
}
}
return 0
}

Make sure your location file should be in correct json format otherwise this function throw an error

Reading in a JSON File Using Swift

Follow the below code :

if let path = NSBundle.mainBundle().pathForResource("test", ofType: "json")
{
if let jsonData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)
{
if let jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSDictionary
{
if let persons : NSArray = jsonResult["person"] as? NSArray
{
// Do stuff
}
}
}
}

The array "persons" will contain all data for key person. Iterate throughs to fetch it.

Swift 4.0:

if let path = Bundle.main.path(forResource: "test", ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
if let jsonResult = jsonResult as? Dictionary<String, AnyObject>, let person = jsonResult["person"] as? [Any] {
// do stuff
}
} catch {
// handle error
}
}

how to parse json in app

use NSJSONSerialization to parse json response

NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:urlData options:NSJSONReadingMutableLeaves error:nil];

NSLog(@"json data is %@",jsonData);

NSInteger success = [[jsonData objectForKey:@"response_code"] integerValue];
NSString *response = [jsonData objectForKey:@"response"];

NSLog(@"success is %d",success);

check the response code here

if(success == 1)
{
// navigate to next or do whatever
// [self alertStatus:@"Logged in Successfully." :@"Login Success!"];

}


Related Topics



Leave a reply



Submit