how to use SwiftyJSON framework to read a locally declared JSON - json

I am trying to read a locally declared JSON, since I still do not have the network ready to send me JSON examples for the app we are developing.
For some reason I get a null when trying to print the json created by SwiftyJSON framework.
This is my class:
import Foundation
import SwiftyJSON
let mockShifts = "{\"numOfShiftsInDay\": 3,\"shifts\": [{\"StartTime\": \"06:30\",\"EndTime\": \"14:00\"},{\"StartTime\": \"14:00\",\"EndTime\": \"19:00},{\"StartTime\": \"19:00\",\"EndTime\":\"01:00\"}]}"
class WeeklySchedule {
var shifts: [Shift] = []
var shiftsAmount: Int = 3
var relative: Int = 0
func setShiftsAmount(amount: Int){
self.shiftsAmount = amount
for _ in 1...amount{
self.shifts.append(Shift())
}
getShifts()
}
func getRelative() -> Int{
return relative
}
func getShifts(){
let data = mockShifts.data(using: .utf8)!
let json = JSON(data: data)
print(mockShifts) //This prints out a JSON that looks OK to me
print(json) //This prints NULL
if let numOfShifts = json["numOfShiftsInDay"].string {
print(numOfShifts) //This code is unreachable
}
}
}
And this is my console output, when calling setShiftsAmount() which calls getShifts():
{"numOfShiftsInDay": 3,"shifts": [{"StartTime": "06:30","EndTime": "14:00"},{"StartTime": "14:00","EndTime": "19:00},{"StartTime": "19:00","EndTime":"01:00"}]}
null
Why is my JSON null?

The reason you are getting null for your JSON because your JSON string mockShifts is not contain's valid JSON, there is missing double quote(\") for the EndTime key after 19:00 in the second object of array shifts. Add that double quote and you all set to go.
let mockShifts = "{\"numOfShiftsInDay\": 3,\"shifts\": [{\"StartTime\": \"06:30\",\"EndTime\": \"14:00\"},{\"StartTime\": \"14:00\",\"EndTime\": \"19:00\"},{\"StartTime\": \"19:00\",\"EndTime\":\"01:00\"}]}"

Related

JSON to dict with class

I decide some JSON and try to typecast it to a dictionary of String: classy and it fails. I have found that often the reason I have trouble doing something is because of a misunderstanding of how Swift works, so here is what I want to happen. Feel free to tell me that I am doing it wrong and if I do it this way all will be wonderful.
I want my data to live between runs of the app so I have to save the data to storage between runs. I have an object, data and associated code, and I have places where changes I make to a copy should reflect back to the original so it is a class. I have a bunch of these objects and most of the time I pick the one I want based on an id that is an integer. An array is not good since it would be a sparse array cause come ids are not used. I came up with a dictionary with a key of the id and data of the structure. I turned the key from an Int to a String, by changing the Int id to a String, cause converting a dictionary to JSON is MUCH easier for a key that is a string. I save the JSON string. When the app starts again I read the string in and convert the JSON string to Any. Then I typecast the result to the desired dictionary. This is where it fails. The cast does not work. In my Googling the samples I found said this should work.
Here is my code:
class Y: Codable, Hashable {
var a: String = "c"
static func ==(lhs: Y, rhs: Y) -> Bool {
return lhs.a == rhs.a
}
func hash(into hasher: inout Hasher) {
hasher.combine(a)
}
}
struct ContentView: View {
var body: some View {
VStack {
Button ("Error") {
var y = Y()
var yDict = [String: Y]()
yDict["0"] = y
do {
let encodedData = try JSONEncoder().encode(yDict)
let jsonString = String(data: encodedData, encoding: .utf8)
let decoded = try JSONSerialization.jsonObject(with: encodedData, options: [])
if let yyDictDec = decoded as? [String:Y] {
print("yDict after decide")
print (yyDictDec)
}
} catch {
print(error.localizedDescription)
}
print("x")
}
}
}
}
In this code the if yyDictDec = is failing, I think, cause the prints after it never happen. I can cast it as [String, Any] but I really need it to be my class.
My problem is in the convert JSON back to the dictionary. I feel I am missing something fairly simple.
Don´t use JSONSerialization use JsonDecoder and decode it to the the type it was before encoding. e.g.:
let decoded = try JSONDecoder().decode([String: Y].self, from: encodedData)

Automatic parsing JSON with Swift 5 and Alomofire

I am calling an API via Alomofire in Swift 5 and get the following Result Set in JSON format :
Here is the call :
AF.request("https://shopping.yahooapis.jp/ShoppingWebService/V1/json/itemSearch", parameters: parameters).responseJSON { response in
print(response.result)
}
I have the following info in the result : Content-Encoding: gzip, the solution may come from here)
Here is the JSON Response body :
{"ResultSet":{"totalResultsAvailable":"3","totalResultsReturned":3,"firstResultPosition":"1","0":{"Result":{"Request":{"Query":""},"Modules":"","0":{"Name":"\u3010\u30ad\u30e3\u30c3\u30b7\u30e5\u30ec\u30b95\uff05\u9084\u5143\u3011\u30ab\u30eb\u30d3\u30fc\u3000\u304b\u3063\u3071\u3048\u3073\u305b\u3093\u7d00\u5dde\u306e\u6885\u547370g\u3000\u3010\u30a4\u30fc\u30b8\u30e3\u30d1\u30f3\u30e2\u30fc\u30eb\u3011","Description":"\u3010\u691c\u7d22\u30ad\u30fc\u30ef\u30fc\u30c9\uff08\u5546\u54c1\u5185\u5bb9\u3092\u4fdd\u969c\u3059\u308b\u3082\u306e\u3067\u306f\u3042\u308a\u307e\u305b\u3093\uff09\u3011\u304a\u83d3\u5b50\u3000\u304a\u3084\u3064\u3000\u30b9\u30ca\u30c3\u30af\u3000\u30b9\u30ca\u30c3\u30af\u83d3\u5b50\u3000\u30ab\u30c3\u30d1\u30a8\u30d3\u30bb\u30f3\u3000\u3046\u3081\u5473\u3000\u30a6\u30e1\u3000\u6d77\u8001\u3000\u30ab\u30eb\u30b7\u30a6\u30e0","Headline":"","Url":"https:\/\/store.shopping.yahoo.co.jp\/ejapan\/4901330197711f.html","ReleaseDate":"","Availability":"instock","Code":"ejapan_4901330197711f","Condition":"new","Image":{"Id":"ejapan_4901330197711f","Small":"https:\/\/item-shopping.c.yimg.jp\/i\/c\/ejapan_4901330197711f","Medium":"https:\/\/item-shopping.c.yimg.jp\/i\/g\/ejapan_4901330197711f"},"Review":{"Rate":"0.00","Count":"0","Url":"https:\/\/shopping.yahoo.co.jp\/review\/item\/list?store_id=ejapan&page_key=4901330197711f"},"Affiliate":{"Rate":"1.0"},"Price":{"_attributes":{"currency":"JPY"},"_value":"121"},"PremiumPrice":"","PriceLabel":{"_attributes":{"taxIncluded":"true"},"FixedPrice":"","DefaultPrice":"121","SalePrice":"","PremiumPriceStatus":"0","PremiumPrice":"121","PremiumDiscountType":"","PremiumDiscountRate":"","PeriodStart":"","PeriodEnd":""},"Point":{"Amount":"1","Times":"1","PremiumAmount":"1","PremiumTimes":"1"},"Shipping":{"Code":"1","Name":"\u8a2d\u5b9a\u7121\u3057"},"Category":{"Current":{"Id":"13451","Name":"\u305d\u306e\u4ed6\u30b9\u30ca\u30c3\u30af\u3001\u304a\u83d3\u5b50\u3001\u304a\u3064\u307e\u307f"}},"CategoryIdPath":{"0":{"Id":"1"},"1":{"Id":"2498"},"2":{"Id":"4745"},"3":{"Id":"13451"},"_container":"Category"},"Brands":{"Name":"\u30ab\u30eb\u30d3\u30fc","Path":{"0":{"Id":"1"},"1":{"Id":"16267"},"_container":"Brand"}},"JanCode":"4901330197711","Model":"","IsbnCode":"","Store":{"Id":"ejapan","Name":"e\u30b8\u30e3\u30d1\u30f3","Url":"https:\/\/store.shopping.yahoo.co.jp\/ejapan\/","Payment":{"0":{"Code":"1","Name":"\u30af\u30ec\u30b8\u30c3\u30c8\u30ab\u30fc\u30c9"},"1":{"Code":"16","Name":"Yahoo!\u30a6\u30a9\u30ec\u30c3\u30c8\u306b\u767b\u9332\u3057\u3066\u3044\u308b\u30af\u30ec\u30b8\u30c3\u30c8\u30ab\u30fc\u30c9"},"2":{"Code":"4","Name":"\u5546\u54c1\u4ee3\u5f15"},"3":{"Code":"2","Name":"\u9280\u884c\u632f\u8fbc"},"4":{"Code":"8","Name":"\u90f5\u4fbf\u632f\u66ff"},"5":{"Code":"1024","Name":"\u30bd\u30d5\u30c8\u30d0\u30f3\u30af\u307e\u3068\u3081\u3066\u652f\u6255\u3044"},"6":{"Code":"4096","Name":"PayPay"},"_container":"Method"},"IsBestStore":"false","Ratings":{"Rate":"4.5","Count":"11871","Total":"51092","DetailRate":"4.3"},"Image":{"Id":"ejapan_1","Medium":"https:\/\/item-shopping.c.yimg.jp\/s\/h\/ejapan_1"},"IsPMallStore":"false"},"IsAdult":"0","Deliveryinfo":{"Area":"","Deadline":"","Day":""},"_attributes":{"index":"1"}},"1":{"Name":"\u3010\u30ad\u30e3\u30c3\u30b7\u30e5\u30ec\u30b95\uff05\u9084\u5143\u3011\u2605\u307e\u3068\u3081\u8cb7\u3044\u2605\u3000\u30ab\u30eb\u30d3\u30fc\u3000\u304b\u3063\u3071\u3048\u3073\u305b\u3093\u7d00\u5dde\u306e\u6885\u547370g\u3000\u3000\u00d712\u500b\u3010\u30a4\u30fc\u30b8\u30e3\u30d1\u30f3\u30e2\u30fc\u30eb\u3011","Description":"\u3010\u691c\u7d22\u30ad\u30fc\u30ef\u30fc\u30c9\uff08\u5546\u54c1\u5185\u5bb9\u3092\u4fdd\u969c\u3059\u308b\u3082\u306e\u3067\u306f\u3042\u308a\u307e\u305b\u3093\uff09\u3011\u304a\u83d3\u5b50\u3000\u304a\u3084\u3064\u3000\u30b9\u30ca\u30c3\u30af\u3000\u30b9\u30ca\u30c3\u30af\u83d3\u5b50\u3000\u30ab\u30c3\u30d1\u30a8\u30d3\u30bb\u30f3\u3000\u3046\u3081\u5473\u3000\u30a6\u30e1\u3000\u6d77\u8001\u3000\u30ab\u30eb\u30b7\u30a6\u30e0","Headline":"","Url":"https:\/\/store.shopping.yahoo.co.jp\/ejapan\/012-4901330197711f.html","ReleaseDate":"","Availability":"instock","Code":"ejapan_012-4901330197711f","Condition":"new","Image":{"Id":"ejapan_012-4901330197711f","Small":"https:\/\/item-shopping.c.yimg.jp\/i\/c\/ejapan_012-4901330197711f","Medium":"https:\/\/item-shopping.c.yimg.jp\/i\/g\/ejapan_012-4901330197711f"},"Review":{"Rate":"0.00","Count":"0","Url":"https:\/\/shopping.yahoo.co.jp\/review\/item\/list?store_id=ejapan&page_key=012-4901330197711f"},"Affiliate":{"Rate":"1.0"},"Price":{"_attributes":{"currency":"JPY"},"_value":"1398"},"PremiumPrice":"","PriceLabel":{"_attributes":{"taxIncluded":"true"},"FixedPrice":"","DefaultPrice":"1398","SalePrice":"","PremiumPriceStatus":"0","PremiumPrice":"1398","PremiumDiscountType":"","PremiumDiscountRate":"","PeriodStart":"","PeriodEnd":""},"Point":{"Amount":"13","Times":"1","PremiumAmount":"13","PremiumTimes":"1"},"Shipping":{"Code":"1","Name":"\u8a2d\u5b9a\u7121\u3057"},"Category":{"Current":{"Id":"13451","Name":"\u305d\u306e\u4ed6\u30b9\u30ca\u30c3\u30af\u3001\u304a\u83d3\u5b50\u3001\u304a\u3064\u307e\u307f"}},"CategoryIdPath":{"0":{"Id":"1"},"1":{"Id":"2498"},"2":{"Id":"4745"},"3":{"Id":"13451"},"_container":"Category"},"Brands":{"Name":"\u30ab\u30eb\u30d3\u30fc","Path":{"0":{"Id":"1"},"1":{"Id":"16267"},"_container":"Brand"}},"JanCode":"4901330197711","Model":"","IsbnCode":"","Store":{"Id":"ejapan","Name":"e\u30b8\u30e3\u30d1\u30f3","Url":"https:\/\/store.shopping.yahoo.co.jp\/ejapan\/","Payment":{"0":{"Code":"1","Name":"\u30af\u30ec\u30b8\u30c3\u30c8\u30ab\u30fc\u30c9"},"1":{"Code":"16","Name":"Yahoo!\u30a6\u30a9\u30ec\u30c3\u30c8\u306b\u767b\u9332\u3057\u3066\u3044\u308b\u30af\u30ec\u30b8\u30c3\u30c8\u30ab\u30fc\u30c9"},"2":{"Code":"4","Name":"\u5546\u54c1\u4ee3\u5f15"},"3":{"Code":"2","Name":"\u9280\u884c\u632f\u8fbc"},"4":{"Code":"8","Name":"\u90f5\u4fbf\u632f\u66ff"},"5":{"Code":"1024","Name":"\u30bd\u30d5\u30c8\u30d0\u30f3\u30af\u307e\u3068\u3081\u3066\u652f\u6255\u3044"},"6":{"Code":"4096","Name":"PayPay"},"_container":"Method"},"IsBestStore":"false","Ratings":{"Rate":"4.5","Count":"11875","Total":"51100","DetailRate":"4.3"},"Image":{"Id":"ejapan_1","Medium":"https:\/\/item-shopping.c.yimg.jp\/s\/h\/ejapan_1"},"IsPMallStore":"false"},"IsAdult":"0","Deliveryinfo":{"Area":"","Deadline":"","Day":""},"_attributes":{"index":"2"}},"2":{"Name":"\u3010\u30ad\u30e3\u30c3\u30b7\u30e5\u30ec\u30b95\uff05\u9084\u5143\u3011\u3010\u9001\u6599\u7121\u6599\u3011\u2605\u307e\u3068\u3081\u8cb7\u3044\u2605\u3000\u30ab\u30eb\u30d3\u30fc\u3000\u304b\u3063\u3071\u3048\u3073\u305b\u3093\u7d00\u5dde\u306e\u6885\u547370g\u3000\u3000\u00d712\u500b\u3010\u30a4\u30fc\u30b8\u30e3\u30d1\u30f3\u30e2\u30fc\u30eb\u3011","Description":"\u3010\u691c\u7d22\u30ad\u30fc\u30ef\u30fc\u30c9\uff08\u5546\u54c1\u5185\u5bb9\u3092\u4fdd\u969c\u3059\u308b\u3082\u306e\u3067\u306f\u3042\u308a\u307e\u305b\u3093\uff09\u3011\u304a\u83d3\u5b50\u3000\u304a\u3084\u3064\u3000\u30b9\u30ca\u30c3\u30af\u3000\u30b9\u30ca\u30c3\u30af\u83d3\u5b50\u3000\u30ab\u30c3\u30d1\u30a8\u30d3\u30bb\u30f3\u3000\u3046\u3081\u5473\u3000\u30a6\u30e1\u3000\u6d77\u8001\u3000\u30ab\u30eb\u30b7\u30a6\u30e0","Headline":"","Url":"https:\/\/store.shopping.yahoo.co.jp\/ejapan\/012-4901330197711fm.html","ReleaseDate":"","Availability":"instock","Code":"ejapan_012-4901330197711fm","Condition":"new","Image":{"Id":"ejapan_012-4901330197711fm","Small":"https:\/\/item-shopping.c.yimg.jp\/i\/c\/ejapan_012-4901330197711fm","Medium":"https:\/\/item-shopping.c.yimg.jp\/i\/g\/ejapan_012-4901330197711fm"},"Review":{"Rate":"0.00","Count":"0","Url":"https:\/\/shopping.yahoo.co.jp\/review\/item\/list?store_id=ejapan&page_key=012-4901330197711fm"},"Affiliate":{"Rate":"1.0"},"Price":{"_attributes":{"currency":"JPY"},"_value":"2278"},"PremiumPrice":"","PriceLabel":{"_attributes":{"taxIncluded":"true"},"FixedPrice":"","DefaultPrice":"2278","SalePrice":"","PremiumPriceStatus":"0","PremiumPrice":"2278","PremiumDiscountType":"","PremiumDiscountRate":"","PeriodStart":"","PeriodEnd":""},"Point":{"Amount":"22","Times":"1","PremiumAmount":"22","PremiumTimes":"1"},"Shipping":{"Code":"1","Name":"\u8a2d\u5b9a\u7121\u3057"},"Category":{"Current":{"Id":"13451","Name":"\u305d\u306e\u4ed6\u30b9\u30ca\u30c3\u30af\u3001\u304a\u83d3\u5b50\u3001\u304a\u3064\u307e\u307f"}},"CategoryIdPath":{"0":{"Id":"1"},"1":{"Id":"2498"},"2":{"Id":"4745"},"3":{"Id":"13451"},"_container":"Category"},"Brands":{"Name":"\u30ab\u30eb\u30d3\u30fc","Path":{"0":{"Id":"1"},"1":{"Id":"16267"},"_container":"Brand"}},"JanCode":"4901330197711","Model":"","IsbnCode":"","Store":{"Id":"ejapan","Name":"e\u30b8\u30e3\u30d1\u30f3","Url":"https:\/\/store.shopping.yahoo.co.jp\/ejapan\/","Payment":{"0":{"Code":"1","Name":"\u30af\u30ec\u30b8\u30c3\u30c8\u30ab\u30fc\u30c9"},"1":{"Code":"16","Name":"Yahoo!\u30a6\u30a9\u30ec\u30c3\u30c8\u306b\u767b\u9332\u3057\u3066\u3044\u308b\u30af\u30ec\u30b8\u30c3\u30c8\u30ab\u30fc\u30c9"},"2":{"Code":"4","Name":"\u5546\u54c1\u4ee3\u5f15"},"3":{"Code":"2","Name":"\u9280\u884c\u632f\u8fbc"},"4":{"Code":"8","Name":"\u90f5\u4fbf\u632f\u66ff"},"5":{"Code":"1024","Name":"\u30bd\u30d5\u30c8\u30d0\u30f3\u30af\u307e\u3068\u3081\u3066\u652f\u6255\u3044"},"6":{"Code":"4096","Name":"PayPay"},"_container":"Method"},"IsBestStore":"false","Ratings":{"Rate":"4.5","Count":"11874","Total":"51099","DetailRate":"4.3"},"Image":{"Id":"ejapan_1","Medium":"https:\/\/item-shopping.c.yimg.jp\/s\/h\/ejapan_1"},"IsPMallStore":"false"},"IsAdult":"0","Deliveryinfo":{"Area":"","Deadline":"","Day":""},"_attributes":{"index":"3"}},"_container":"Hit"}}}}
So I would like to find the way to automatically parse this JSON body in order to exploit the data later,
Does the solution come from the encoding format ?
I have not been successful implementing decompressing using Gzip (link here)
Would it be possible to do it automatically via Decodable or the data is maybe directly accessible in Alomofire ?
Thank you in advance,
Charles
When it comes to decoding and holding data from JSON responses from REST APIs, I have used the following approach:
Include the bellow two PODS
1) Alamofire
2) TRON
Now, you'll have to create a class you'll use as a datasource interface between the API and the actual class model. In the following example, I'm pulling data from a movie database service and I have the bellow class for the data sourcing:
class MovieDataSource: JSONDecodable {
var movies: [Movie] = []
let cellid = "cellid"
required init(json: JSON) throws {
guard let moviesArray = json["results"].array else {
print("Error on the JSON Format")
return
}
self.movies = moviesArray.map({return Movie(json: $0)})
}
}
class JSONError: JSONDecodable {
required init(json: JSON) throws {
print("JSON error\n", json)
}
}
Then I have the actual data holding class/structure:
struct Movie {
let title: String
let movieId: Int
let overview: String
let releaseDate: String
let posterPathURL: String
let genres: [Int]
let vote_average: Float
let popularity: Float
let isForAdults: Bool
init(json: JSON) {
self.title = json["title"].stringValue
self.movieId = json["id"].intValue
self.overview = json["overview"].stringValue
self.releaseDate = json["release_date"].stringValue
self.posterPathURL = json["poster_path"].stringValue
self.genres = json["genre_ids"].arrayObject as! [Int]
self.vote_average = json["vote_average"].floatValue
self.popularity = json["popularity"].floatValue
self.isForAdults = json["adult"].boolValue
}
}
I think the above information should be enough to get you an idea on how to move forward, but If you need further guidance, I found this video series very educative on this subject: https://www.youtube.com/watch?v=tt67VikEovY&list=PL0dzCUj1L5JE1wErjzEyVqlvx92VN3DL5&index=13
Good luck!

Return JSON data from Parse Cloud Code to a Decodable Struct in Swift

I'm looking to run a Cloud-Code function from a Swift application and receive an object as a response. The response object from Parse is a standard JSON object as defined below and is not an object stored is Parse. Essentially, I'm looking to end up with an custom object defining the results of a cloud function's execution, not an object stored in the database.
I'm struggling with decoding the CloudCode response on the Swift side of things to a custom object following the Decodable protocol.
Sample Cloud Code
Parse.Cloud.define("MyCloudFunc", function(request, response) {
var results = {
"someBooleanProperty": true,
"someIntProperty": 1,
};
response.success(results);
}
Sample Swift Code
PFCloud.callFunction(inBackground: "MyCloudFunc", withParameters: []) { (result, error) in
// Printing `result` at this point shows what appears to be a JSON object.
guard let data = result as? Data else { return }
// Whatever type `result` actually is cannot be cast as Data, so we never make it past here.
guard let response = try? JSONDecoder().decode(MyDecodableStruct, from: data) else { return }
// DO SOMETHING WITH THE RESULT
}
Decodable Struct
struct MyDecodableStruct: Decodable {
var someBooleanProperty:Bool
var someIntProperty: Int
}
Question
How can I take that response from the Parse Cloud Code and end up with a decoded object of type MyDecodableStruct?
UPDATE
As suggested in the comments/answers, Parse is returning a Dictionary. I have been able to get everything working with the below; however, I feel there is a better way than double-conversion.
PFCloud.callFunction(inBackground: "MyCloudFunc", withParameters: []) { (result, error) in
guard let jsonString = result as? String else { return }
guard let data = jsonString.data(using: String.Encoding.utf8) else { return }
guard let response = try? JSONDecoder().decode(MyDecodableStruct.self, from: data) else { return }
// DO SOMETHING WITH RESULT.
}
Am I overlooking a way to convert from the Dictionary directly Data without doing the JSON conversion in-between?
Part of PFCloud's job is to create generic collection types from the cloud function response. Since the cloud function is answering a JS object, PFCloud should -- without the app noticing -- transmit JSON and parse it before invoking the callFunction callback.
So the posted cloud code result will the be a dictionary. Check to see that with...
if result is Dictionary<AnyHashable,Any> {
print("result is a Dictionary")
}
To convert that to the OP struct, add a from-dictionary initializer to it...
struct MyDecodableStruct: Decodable {
var someBooleanProperty:Bool
var someIntProperty: Int
init(dictionary: [AnyHashable,Any]) {
self.someBooleanProperty = dictionary["someBooleanProperty"] as? Bool ?? false
self.someIntProperty = dictionary["someIntProperty"] as? Int ?? 0
}
}

swift json how to fill an object

here is my issue, I would like to create a function with this prototype :
func doPostRequest(......)->JSON()
And I write it like that :
func downloadData(completed:#escaping()->()){
Alamofire.request(url).responseJSON(completionHandler: {
response in
let result = response.result
if let dict = ... {
self._temp = String(format: "%.0f °C", temp - 273.15)
...
}
completed()
})
}
I'd like to return an Any object or dictionary, something with my JSON in... but each time I try to implement return I have a nil object ! Maybe a scope problem how can I implement this function to have
var myJson:NSDictionary
myJson=downloadData(......) ???
Thanks for your help
Since the method in the body works asynchronously you have to declare your request method with an completion handler for example
func doPostRequest(completion: #escaping ([String:Any])->())
On return it passes a Swift dictionary.
The method can be used with this code:
var myJson = [String:Any]()
...
doPostRequest() { json in
self.myJson = json
// do something with the returned data
}
first you need to create a ObjectMapper to map your objects and use AlamofireObjectMapper to get
try this code
request(url, method: .post, parameters:params).validate().responseObject{(response:
DataResponse<objectMapperclass>)in
switch response.result{
case.success(let data):
let objects = data
case.faliure(_):
}
}

import JSON in Realm

I have a SQL Database on Azure and I would like to synchronize it with Realm, for my iOS App (in Swift)
For that, I have created a REST API which generates a JSON and now I would like to integrate this JSON in Realm.
To do that, I have tried to follow the explanation on Realm Documentation, so now I have :
Realm Table :
class tbl_test: Object {
dynamic var id:Int = 0
dynamic var name:String = ""
override class func primaryKey() -> String? {
return "id"
}
}
Swift Code :
let realm = try! Realm()
let stringTxt:String = "[{\"id\": 1, \"name\": \"My Name\"}]"
var myData = NSData()
if let dataFromString = stringTxt.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
let jsonData = JSON(data: dataFromString)
if let encryptedData:NSData = try! jsonData.rawData() {
myData = encryptedData
}
}
try! realm.write {
let json = try! NSJSONSerialization.JSONObjectWithData(myData, options: NSJSONReadingOptions())
realm.create(tbl_test.self, value: json, update: true)
}
I use SwiftyJSON to convert my string to JSON.
When I run the program, I have this error message :
[__NSCFDictionary longLongValue]: unrecognized selector sent to
instance 0x7fdcc8785820 2016-07-06 10:25:30.090
mydrawing[9436:2732447] *** Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '-[__NSCFDictionary
longLongValue]: unrecognized selector sent to instance 0x7fdcc8785820'
Is it a good way to import JSON in Realm ? There is no official way according to what I have found, but this method should work...
The problem you're facing is that the structure of the data you're passing to Realm.create(_:value:update:) doesn't match what the method expects. It expects either a dictionary with keys corresponding to the managed properties on your model type, or an array with one element for each managed property.
After deserializing the JSON data, json looks like so:
(
{
id = 1;
name = "My Name";
}
)
That is an array containing a single element that is an dictionary. When you pass this array to Realm.create(_:value:update:), Realm expects the first element of the array to be the value to use as the id property on your tbl_test type.
I suspect that what you mean to do is to call Realm.create on each of the elements of the array in turn, instead of calling it on the array itself.