Effortless retrieveJSON() method

SwiftyJSON is a valuable asset for Swift developers. It can be easily imported into projects using different methods such as CocoaPods or Carthage. I frequently utilize SwiftyJSON in my projects since handling JSON files is often necessary. To streamline the process, I created a straightforward function that retrieves the raw String value from my JSON file with just a few arguments.

Answer №1

First Step: Creating a Protocol and Model Class

protocol JSONable {
    init?(parameter: JSON)
}

class Scheme: JSONable {
    let ID              :String!
    let name            :String!

    required init(parameter: JSON) {
        ID            = parameter["id"].stringValue
        name          = parameter["name"].stringValue
    }

    /*  Sample JSON response format
    {
      "status": true,
      "message": "",
      "data": [
        {
          "id": 1,
          "name": "Scheme 1"
        },
        {
          "id": 2,
          "name": "Scheme 2"
        },
        {
          "id": 3,
          "name": "Scheme 3"
        }
      ]
    }
    */
}

Second Step: Converting JSON to Model Object using Extension

extension JSON {
    func convertToType<T>(type: T?) -> Any? {
        if let baseObj = type as? JSONable.Type {
            if self.type == .array {
                var arrObject: [Any] = []
                for obj in self.arrayValue {
                    let object = baseObj.init(parameter: obj)
                    arrObject.append(object!)
                }
                return arrObject
            } else {
                let object = baseObj.init(parameter: self)
                return object!
            }
        }
        return nil
    }
}

Third Step: Using the code with Alamofire or any other library

Alamofire.request(.GET, url).validate().responseJSON { response in
        switch response.result {
            case .success(let value):
                let json = JSON(value)

                var schemes: [Scheme] = []
                if let schemeArr = json["data"].convertToType(type: Scheme.self) {
                    schemes = schemeArr as! [Scheme]
                }
                print("schemes: \(schemes)")
            case .failure(let error):
                print(error)
        }
 }

I hope you found this helpful.

For more information, you can visit the following link:
https://github.com/SwiftyJSON/SwiftyJSON/issues/714

Answer №2

Here's a custom function I've created specifically for integrating SwiftJSON in your Xcode Swift project:

func getJSONData(value: [String], fileName: String) -> String{
    guard let path = Bundle.main.path(forResource: fileName, ofType: "json"),
        let jsonData = NSData(contentsOfFile: path) else{
            print("Failed to locate or read the file on disk.")
            return "ERR."
    }

    let jsonObject = JSON(data: jsonData as Data)

    guard let jsonValue = jsonObject[value].string else{
        print("Failed to find the specified JSON object")
        return "ERR."
    }

    return jsonValue

}

An example usage of this function would be

let myJsonValue = getJSONData(value: ["people","person1"], fileName: "database")
, where it will retrieve the value person1 from the JSON group people within the file named database.json. For instance, if the contents of the database.json file looked like this:

{
    "people" : {
        "person1" : "Bob",
        "person2" : "Steve",
        "person3" : "Alan",
    }
}

The function would return the value "Bob".

I hope this function proves useful to anyone using SwiftJSON integration. If you have any suggestions or constructive criticism, please feel free to share!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to Extract Information from a Table Enclosed in a Div Using HTML Parsing?

I'm new to HTML parsing and scraping, looking for some guidance. I want to specify the URL of a page (http://www.epgpweb.com/guild/us/Caelestrasz/Crimson/) to grab data from. Specifically, I'm interested in extracting the table with class=listing ...

Instructions for converting a JSON string into the proper format for a POST request in Swift

After using significant string interpolation, I have generated this JSON structure: { "headers":{ "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="11747c70787d517469707c617d743f7e6376">[email protect ...

Retrieve a JSON response from within a schema housed in MongoDB

I have a document structure that looks like this: { "id": "someString", "servers": [ { "name": "ServerName", "bases": [ { "name": "Base 1", "status": true }, { "name": "Base 2", ...

json remove unnecessary detailed timestamps

I need to develop a service that only returns JSON with date, time, and minutes, but the current implementation is displaying everything including milliseconds and seconds in the timestamp. How can I remove the milliseconds and seconds from the output? Be ...

Python JSON deep assertion techniques

Currently I am making an API call and the response coming from the server is in JSON format. Here's how the response looks: { "status": 0, "not_passed": 1, "why": [ { "code": 229, "reason": "some reason", } ] } I have tw ...

Include features once JSON has been loaded

Received this JSON data: { "info": [ { "id": 999, "products": [ { "id": 1, }, { "id": 2, } ] } ] } Info -- products -----id Here is the factory code snippet: AppAngular.factory('model', ['$http', f ...

What's preventing me from retrieving the file content for this website using file_get_contents in PHP?

Greetings to you. I have recently created a PHP tool that can extract YouTube video details of all public videos in JSON format. The tool functions flawlessly on both local and live servers. However, I encountered an issue when attempting to retrieve conte ...

Make sure that JSON.stringify is set to automatically encode the forward slash character as `/`

In my current project, I am developing a service using nodejs to replace an old system written in .NET. This new service exposes a JSON API, and one of the API calls returns a date. In the Microsoft date format for JSON, the timestamp is represented as 159 ...

Explore within another map and analyze the node to spot the differences

I have some questions about iterating through a JavaScript Object and using array functions in JavaScript. Let's assume I have the following variables: var json1 = "[{"id": 1, "name":"x"}, {"id": 2, "name":"y"}]"; var json2 = "[{"id": 1, "name":"x"}, ...

Encountering a java.lang.OutOfMemoryError when trying to construct a JSON object in Java/Android development

For my project, I am fetching JSON data from a public database through the URI , and this dataset contains up to 445454 rows. The code snippet below outlines how I'm constructing the JSON object for this extensive dataset. HttpGet get = new HttpGe ...

An error occurred with the m.m.m.a.ExceptionHandlerExceptionResolver

I am getting an error in the backend console related to a value from React. How can I resolve this issue? [36m.m.m.a.ExceptionHandlerExceptionResolver Resolved [org.springframework.web.bind.MethodArgumentNotValidException: Validation failed for argument [ ...

The challenge of receiving AJAX responses in Internet Explorer

My file upload plugin (jQuery Fine Upload) allows me to upload images via AJAX and generate preview images from the response (JSON). While this works smoothly in most browsers, it encounters difficulties in all versions of Internet Explorer. The issue aris ...

How to display JSON object in JSP using Ajax code

I am attempting to print a JavaScript object using AJAX on the client side (.jsp), but I keep getting an error. Here is my code in the servlet: response.setContentType("application/json;charset=utf-8"); JSONObject json = null; try { json = ...

Is it possible to create a JSON object with a hierarchical structure using a recursive

  As much as I hate to admit it, my computer science skills are letting me down on this one :( Dealing with an API that spits out JSON responses like the following is throwing me off: // hit /api/get/200 { id : 200, name : 'France', childNod ...

The process of uploading images functions without any issues with all devices, except for the

Issue with Image Uploading on iPhone Devices in PHP (CodeIgniter) The problem occurs when trying to upload images taken on iPhones, while non-captured or other images fail to upload. Here is a snippet of the code: <?php ..... ..... $thi ...

Appium encountered an error on iOS with the message: "NSCocoaErrorDomain Error Code 260: The file named 'WebDriverAgentRunner-Runner.app' cannot be opened as it does not exist"

While running appium on a real iPhone, I encountered the following error message. Despite searching for a solution, I have not been able to resolve it yet. [XCUITest] Using WDA path: '/Applications/Appium.app/Contents/Resources/app/node_modules/appiu ...

What is preventing the successful insertion of a JSON array into a SQL database?

I am facing an issue with inserting a JSON array into an SQL database. I have an HTML table that stores its data in a JavaScript array, converts it to a JSON array, and then sends it to a PHP file. However, when trying to insert this JSON array into the da ...

Utilizing Postgres, explore the effectiveness of substring indexing and matching on JSON string arrays

I am using PostgreSQL and have a table with a jsonb field defined as json JSONB NOT NULL. Within this jsonb field, I have an array of strings, such as: { "values": ["foo", "bar", "foobar"]} To search for rows that c ...

Obtain information from a JSON file based on a specific field in Angular

The structure of the JSON file is as follows: localjson.json { "Product" :{ "data" : [ { "itemID" : "1" , "name" : "Apple" , "qty" : "3" }, { "itemID" : "2" , "name" : "Banana" , "qty" : "10" } ] ...

From Android JSON array to a list of items

In my android app, I have encountered an issue while trying to parse a JSONArray into an ArrayList. The PHP script returns the expected results correctly, but when attempting to add the results to the ArrayList in Java, a null pointer exception occurs at ...