Save JSON Response as Variable to Deserialise with SwiftyJSON - json

I'm going to use either SwiftyJSON or EasyFastMapping to deserialise JSON data into variables and constants but I'm not sure on how to save the whole JSON file into its own object, if it is even possible.
I will be using Alamofire to handle the GET request and pull the JSON data down, is it possible to do it like this?
How I want it to work:
1. Alamofire pulls down the JSON data
Alamofire puts the data into an object
SwiftyJSON accesses the downloaded data and allows me to put individual parts of the data into separate variables and constants.

You could take a look at the documentation for SwiftyJSON and Alamofire and you will find plenty of examples.
From Alamofire Readme:
Alamofire.request("https://httpbin.org/get").responseJSON { response in
debugPrint(response)
if let json = response.result.value {
print("JSON: \(json)")
}}
From SwiftJSON Readme:
let json = JSON(data: dataFromNetworking)
if let userName = json[0]["user"]["name"].string {
//Your implementation here
}
You can also create a separate response object and deserialize all the response JSON into the object. Also take a look at the built-in JSONSerialization API in the Foundation framework.

Related

Swifty JSON Response Parsing

I am using SwiftyJson. I am getting a response from printing.
{ "coin" : 120 }
I want to store this response in a variable. How can I store this value in a variable?
To get the specific value from response, it's related with type of response.
https://grokswift.com/json-swift-4/
For example, if response is JSON Array, Please try this.
let val = response[index][key]
otherwise,
let val = response[key1][key2][..]

Printing out MongoDB Documents in JSON Format

I am retrieving documents from my mongoDB database, but I need to print it out in JSON format. I store all of the relevant information in an array as the MongoKitten documentation suggests. I want to print out the entire contents of each element in the array, which is remember a document from MongoDB. My code is as follows:
import Foundation
import MongoKitten
let myDatabase = try MongoKitten.Database("mongodb://taylor:starwars1#ds129374.mlab.com:29374/taylorswiftengine")
let myCollection = myDatabase["my_collection"]
Request.addHandler(forMethod: "GET", withRoute: "/:resource/:id1")
{
(routeParams:RouteParams) in
let myTopics = try! myCollection.find("topic" == "\(routeParams["id1"]!)")
let allTopics = Array(myTopics)
}
MongoKitten comes with an Extended JSON module, which you can import:
import ExtendedJSON
You can convert an array of documents ([Document]) to Extended JSON using makeExtendedJSON():
myArrayOfDocuments.makeExtendedJSON()
This returns a Cheetah.Value. Cheetah is OpenKittens JSON library. To get a JSON String, you can use the serializedString() method on Cheetah.Value.
To sum things up, use this to convert your array of BSON Documents to a JSON String:
myArrayOfDocuments.makeExtendedJSON().serializedString()
If your myTopics object a dictionary you could convert it to json like this:
let dict = ["key1": "B", "key2": "A", "key3": "C"]
let jsonData = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)
Otherwise you could manually convert the myTopics object to a [String:String] dictionary and than convert it to json like above but I'm not sure if thats the way to handle with mongodb objects.

JSON API Document de-serializing and serializing using Spine Swift Library

I'm using Spine A Swift library for working with JSON:API
I want to understand how to serialize the data to take full advantage of the JSON API's
I'm using Serializer to achieve this as:
let serializer = Serializer()
serializer.registerResource(MyModel.self)
What i have got ?
let document = try! serializer.deserializeData(data) //data is my response as NSData
I'm able to get the JSON API Document with all the included relationships and data as
document.included
For this I'm casting MyModel to the required data as
MyModel = document.included[0] as! MyModel
As this is not the intended way to fully utilize the JSON :API, any suggestions and what am i missing ?

AlamoFire 4.0 + SwiftyJSON Unwrapping deeply nested JSON

I'm having issues parsing the JSON I'm getting back from the Wiki API.
Podfile:
platform :ios, ’10.0’
inhibit_all_warnings!
use_frameworks!
target 'GemFinder' do
pod 'Alamofire', '~> 4.0’
pod 'SwiftyJSON', :git => 'https://github.com/appsailor/SwiftyJSON.git', :branch => 'swift3'
end
Swift Code:
import UIKit
import Alamofire
import SwiftyJSON
class WikiAPI: NSObject {
func MineralRequest(minID: (String)) {
Alamofire.request("https://en.wikipedia.org/w/api.php?action=query&titles=\(minID)&exintro=1&prop=pageimages%7Cextracts&format=json&pithumbsize=300", parameters: ["query": "pages"]).responseJSON { response in
if let values = response.result.value as? [String: AnyObject] {
let json = JSON(values)
// Returns null
print("otherJSON: \(json["query"]["pages"][0]["extract"])")
let JSONvalues = values as NSDictionary
print("JSONvalues: \(JSONvalues)")
// This is also working to retrieve everything from below "query"
let parse = JSONvalues.object(forKey: "query")
print("Parse: \(parse)")
let queryValues = values["query"]
// Returns nested "pages" object, but I need to go deeper.
print("queryvalues: \(queryValues?["pages"])")
}
}
}
}
I'm able to get a response, of course, and trying to go deeper, but I keep getting null values when trying to unwrap.
What am I missing? Here's an image of the tree. I'm trying to pull title, images and the extract out.
JSON response preview
Following this format, as seen here, still yields null values. Parameters didn't seem to benefit either: How do I access a nested JSON value using Alamofire and SwiftyJSON?
"pages" value is a dictionary so using [0] on it won't work, you need to use the key instead:
print("otherJSON: \(json["query"]["pages"]["1895477"]["extract"])")
Or if there are many items in pages and you want them all you can iterate through it like:
let pages = json["query"]["pages"]
for (_,page) in pages {
print(page["extract"])
}

Swift - Create data model from JSON response

I'm learning Swift lang and one of the things that would be great to hear others input about is "How you handle models from JSON responses"? For example -
I have User.swift model:
class User: NSObject {
var user_token:String?
var email:String?
}
and also I would like to use KeyValueObjectMapping as I do in Obj-C projects. Unfortunately this doesn't work here:
let parser = DCKeyValueObjectMapping.mapperForClass(User)
let user = parser.parseDictionary(data.objectForKey("user") as NSDictionary) as User
println(user.user_token) // returns nil
How do you create your models in Swift?
I recommend using code generation to generate models in Swift based on JSON. To that end, I've created a tool at http://www.guideluxe.com/JsonToSwift to make modeling and parsing JSON as easy as possible.
After you've submited a sample JSON object with a class name to the tool, it 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.
After copying the generated code into your project as a Swift class(es), 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.
Here's how to create an NSData object from a JSON file to test with.
let fileUrl: NSURL = NSBundle.mainBundle().URLForResource("JsonFile", withExtension: "json")!
let jsonData: NSData = NSData(contentsOfURL: fileUrl)!
I would suggest using SwiftyJSONModel there your model would look something like:
import SwiftyJSONModel
class User: NSObject, JSONObjectInitializable {
enum PropertyKey : String {
case user_token, email
}
var user_token:String?
var email:String?
required init(object: JSONObject<PropertyKey>) throws {
user_token = object.value(for: .user_token)
email = object.value(for: .email)
}
}
This library has 3 nice things:
You don't have to explicitly cast to String as library will infer the type
You can have non-optional properties and library will tell you which exact field was wrong
All the keys to the model are incapsulated in enum which gives you auto-complition when you type the keys and guarantees that you cannot access keys, that are not in enum
I'm using jsoncafe easiest and customizable template base model class generator with different framwroks like SwiftyJSON, Codable, Gloss, Simple Swift Class even you can make your own template
jsoncafe.com
Here is some example code for Model Class and parsing JSON response with out any library.
Model Class
class User: NSObject{
var user_token: String = ""
var email: String = ""
}
Example code to call web-service api and Parsing.
NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var err: NSError
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
//println("Result : \(jsonResult)")
let model = User()
model. user_token = jsonResult["user_token"] as NSString
model. email = jsonResult["email"] as NSString
})
If you want a more rigorous approach and have access to JSON schemas as meta description for your JSON documents, I wrote a code generator which can handle those (JSON schema, draft 4):
https://github.com/werner77/MappableObjectGenerator
My tools supports basically any programming language, because it is based on code generation templates, but is focussed on ObjectiveC and Swift 4 support right now.
May be its too late.
You can also try using the link
http://www.json4swift.com/results.php
Where in you just need to paste the JSON values and it gives you the swift files instead.