class AppUsers: Object{
dynamic var email: String = ""
dynamic var type: String = ""
required convenience init?(map: Map) {
self.init()
mapping(map: map)
}
override class func primaryKey() -> String {
return "email"
}
}
extension AppUsers : Mappable {
func mapping(map: Map) {
email <- map["email"]
// active_platforms <- map["active_platforms"]
type <- map["type"]
// linked_to <- map["linked_to"]
}
}
JSON RESPONSE:
{
"email": "asd#gmail.com",
"type": "primary_email",
"linked_to": {
"_id": "DAS44564dasdDASd",
"image": null,
"company": null,
"designation": null,
"name": null
},
"active_platforms": [
"asd",
"qwe"
]
}
From above response how to get linked_to which is a Dictionary and active_platforms which is an Array. I tried creating separate class for linked_to create var of it in AppUsers but it didn't helped.
A one to one relationship is
dynmamic var linkedTo: LinkObject?
A one to many relationship is
let activePlatforms = List<ActivePlatform>()
If you want to use object mapper to fill them, LinkObject must be mappable and ActivePlatform must be mappable AND you must supply a custom transform to convert the JSON array into a Realm List.
Related
Here is my model
class ResponseDataType: Mappable {
var status: Int?
var message: String?
var info: [Info]?
required init?(map: Map) { }
func mapping(map: Map) {
status <- map["status"]
message <- map["message"]
info <- map["member_info"]
}
}
Here is my JSON
"status": 200,
"data": {
"member_info": [
{
"fullname": "werwerwer",
"type": "werwer",
"profile_image": "sdfsdfsd.jpg",
"email": "wfwe#werwegt",
"contact": ""
}
]
},
"message": "Login Success"
}
Im having a hard time mapping the array inside the data. Please tell me what is wrong with my code.
You forgot the data. It should be like this:
class ResponseDataType: Mappable {
var status: Int?
var message: String?
var data: Data?
required init?(map: Map) { }
func mapping(map: Map) {
status <- map["status"]
message <- map["message"]
data <- map["data"]
}
and your data class:
class Data: Mappable {
var info: [Info]?
required init?(map: Map) { }
func mapping(map: Map) {
info <- map["member_info"]
}
If your Info object conforms to Mappable, everything should work properly in your code. But try to read about Codable protocol, it’s much easier to map objects with it!
I am trying to parse a nested iterative loop in swift
I am getting the response from web service in the following format
{
"categories": [{
"name": "Default Category",
"id": "default_category",
"children": [{
"uuid": "783f491fef5041438fb7a2c3bf6a3650",
"name": "Accessories",
"children": [{
"uuid": "d21b4491ff784a9bae88de279b99fac3",
"name": "All Accessories",
"children": [{
"uuid": "2b1a23c4107844ad8a7afc1b324d0ffd",
"name": "Belts",
"children": [{
"uuid": "2b1a23c4107844ad8a7afc1b324d0ffd",
"name": "Belts",
"children": []
},
{
"uuid": "2b1a23c4107844ad8a7afc1b324d0ffd",
"name": "Belts",
"children": []
}
]
},
{
"uuid": "a1c2a64c36c2461cad3d5f850e4fd0f5",
"name": "Hats",
"children": []
},
{
"uuid": "8f26bc764b8342feaa0cb7f3b96adcae",
"name": "Scarves",
"children": []
},
{
"uuid": "aa1116d1a0254ecea836cc6b32eeb9e0",
"name": "Sunglasses",
"children": []
},
{
"uuid": "9d7033233e8f47eaa69eb1aaf2e98cdd",
"name": "Watches",
"children": []
}
]
}]
}],
"uuid": "6a23415771064e7aaad59f84f8113561"
}]
}
Inside, the categories, there is 'children' key which in turn can contain another children and so on.
I want to continuously loop inside the children key until the children key is empty and insert the last child into database.
Following is the code which i have done
for currentCategory in mainCategories {
// guard against if there are child categories
guard var children = currentCategory.children, children.count > 0 else {
// Save the context
self.coreData.saveStore()
continue
}
for thisChildCategory in children {
if thisChildCategory.children?.count > 0 {
for innerChildCategory in thisChildCategory.children! {
print("innerChildCategory name \(String(describing: innerChildCategory.name))")
}
}
if let child = thisChildCategory.children {
children = child
}
// Create new object
if let currentChildCategory = self.coreData.insertNewObject(CoreDataEntities.BijouCategories.rawValue,
keyValues: ["id" : thisChildCategory.id! as Optional<AnyObject>,
"uuid" : thisChildCategory.uuid as Optional<AnyObject>,
"name" : thisChildCategory.name! as Optional<AnyObject>,
"gender" : thisChildCategory.gender as Optional<AnyObject>!,
"active" : NSNumber(value: false)]) as? BijouCategories {
// Set as parent category
currentChildCategory.parentCategory = parentCategory
// Save the context
self.coreData.saveStore()
}
}
}
But this is not saving all the last child category in database.
Swift 4
You should let Swift 4's codable do the work for you.
You can use the following class as a struct but I find using a class is better if you plan on editing the data.
class Categories: Codable {
var categories: [CategoryItems]
}
class CategoryItems: Codable {
var name: String?
var id: String?
var uuid: String?
var children: [CategoryItems]?
required init(from decoder: Decoder) throws {
var container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decodeIfPresent(String.self, forKey: CodingKeys.name)
id = try container.decodeIfPresent(String.self, forKey: CodingKeys.id)
uuid = try container.decodeIfPresent(String.self, forKey: CodingKeys.uuid)
children = try container.decodeIfPresent([CategoryItems].self, forKey: CodingKeys.children)
if children != nil, children!.count == 0 {
children = nil
}
}
You can see here we add create the root level class "Categories" that has an array of CategoryItems. CategoryItems has all the possible values within it, but each item in the array may or may not have all of the possible values, hence they are optional. The important one is the children which is optional. Then in the required init we only se the optional values if the key value pair is available when decoding. I also set the children to nil if there are zero items, this is optional but helps when doing if statements later.
Then to decode your json using these codable classes you use the following code.
func decode(jsonData data: Data) {
let decoder = JSONDecoder()
do {
let decoded = try decoder.decode(Categories.self, from: data)
}
catch let error as NSError {
print("JSON Decode error = ", error)
}
}
If you want to do a quick test to see if you got the deeping children level which I did you can simply run the following on the decoded variable.
for i in decoded.categories.first!.children!.first!.children!.first!.children!.first!.children! {
print(i.name)
print(i.uuid)
}
With more than 2 nested levels a recursive function is recommended. recursive means the function calls itself.
Here is an simple example assuming jsonString is the given JSON in the question.
The function parseCategory passes the children array and the UUID string as parent identifier. The print line is the place to save the object in Core Data and of course you can pass the created Core Data object as parent as well to set the relationship.
func parseCategory(children: [[String:Any]], parent: String) {
for child in children {
print("Save in Core Data", child["name"] as! String, parent)
let descendants = child["children"] as! [[String:Any]]
parseCategory(children:descendants, parent: child["uuid"] as! String)
}
}
let data = Data(jsonString.utf8)
do {
let json = try JSONSerialization.jsonObject(with: data) as! [String:Any]
parseCategory(children: json["categories"] as! [[String:Any]], parent: "")
} catch { print(error)}
The output is
"Save in Core Data Default Category
Save in Core Data Accessories 6a23415771064e7aaad59f84f8113561
Save in Core Data All Accessories 783f491fef5041438fb7a2c3bf6a3650
Save in Core Data Belts d21b4491ff784a9bae88de279b99fac3
Save in Core Data Belts 2b1a23c4107844ad8a7afc1b324d0ffd
Save in Core Data Belts 2b1a23c4107844ad8a7afc1b324d0ffd
Save in Core Data Hats d21b4491ff784a9bae88de279b99fac3
Save in Core Data Scarves d21b4491ff784a9bae88de279b99fac3
Save in Core Data Sunglasses d21b4491ff784a9bae88de279b99fac3
Save in Core Data Watches d21b4491ff784a9bae88de279b99fac3"
Created an model class to hold your nested children in the form of a tree.
class Children {
var uuid: String?
var name: String?
var children: [Children] = [Children(array: [])]
init(array: NSArray) {
let childrenDic = array[0] as! NSDictionary
uuid = childrenDic["uuid"] as? String
name = childrenDic["name"] as? String
children[0] = Children.init(array: childrenDic["children"] as! NSArray)
}
}
Use like
var childrenModel = Children.init(array: yourArray)
I would suggest you to use ObjectMapper instead of unwrapping the json manually.
https://github.com/Hearst-DD/ObjectMapper
then everything should be much cleaner
class Child: Mappable {
var uuid: String?
var name: String?
var childern: [Child]?
required init?(map: Map) {
}
// Mappable
func mapping(map: Map) {
uuid <- map["uuid"]
name <- map["name"]
childern <- map["childern"]
}
}
class Category: Mappable {
var _id: String? //id is the reserved word
var name: String?
var childern: [Child]?
required init?(map: Map) {
}
// Mappable
func mapping(map: Map) {
_id <- map["id"]
name <- map["name"]
childern <- map["childern"]
}
}
I need to store alamofire JSON response to realm storage directly. Here is the response tat I get from alamofire JSON.
{
"all": [
{
"date": "2017-03-30T00:00:00.000Z",
"subject": "loe",
"desc": "",
"id": 13,
"number": "19/312/2012",
"title": "loe",
"name": "Supreme",
"type": "Event",
"practice": 20,
"contact": "",
"object": "{\"id\":20,\"id\":13,\"name\":\"loe\",\"time\":\"2017-03-30T00:00:00.000Z\",\"end\":\"2017-03-31T00:00:00.000Z\",\"creator\":\"user\",\"created_by\":132,\"des\":\"\",\"created_at\":\"2017-03-30T08:22:31.150Z\",\"updated_at\":\"2017-03-30T08:23:04.944Z\",\"judge\":null,\"purpose\":null,\"google_event_id\":null,\"is_completed\":false,\"business\":null,\"last_notified\":\"2017-03-30T08:23:04.926Z\",\"next\":null,\"business_date\":null,\"business\":false}"
},
{
"date": "2017-03-30T00:30:00.000Z",
"subject": "user",
"desc": "Loe",
"id": 138,
"number": "19/312/2012",
"title": "loe user",
"name": "Supreme India",
"type": "Appointment",
"practice": 6,
"contact": 91,
"object": "{\"id\":20,\"id\":13,\"name\":\"loe\",\"time\":\"2017-03-30T00:00:00.000Z\",\"end\":\"2017-03-31T00:00:00.000Z\",\"creator\":\"user\",\"created_by\":132,\"des\":\"\",\"created_at\":\"2017-03-30T08:22:31.150Z\",\"updated_at\":\"2017-03-30T08:23:04.944Z\",\"judge\":null,\"purpose\":null,\"google_event_id\":null,\"is_completed\":false,\"business\":null,\"last_notified\":\"2017-03-30T08:23:04.926Z\",\"next\":null,\"business_date\":null,\"business\":false}"
}
And Here is the code that I have used for realm storage
class PracticeArea:Object,Mappable
{
dynamic var contact = 0
dynamic var id = ""
dynamic var number = ""
dynamic var title = ""
dynamic var name = ""
dynamic var date = ""
dynamic var description2 = ""
dynamic var object = ""
dynamic var practice = 0
dynamic var subject = ""
dynamic var type = ""
override static func primaryKey() -> String?
{
return "contact"
}
//Impl. of Mappable protocol
required convenience init?(map: Map)
{
self.init()
}
func mapping(map: Map)
{
contact <- map["contact"]
id <- map["id"]
number <- map["number"]
title <- map["title"]
name <- map["name"]
date <- map["date"]
description2 <- map["description"]
object <- map["object"]
practice <- map["practice"]
subject <- map["subject"]
type <- map["type"]
}
}
Code Used for Storing Values:
let PracticeTestValues = response.result.value!
let realm:Realm = try! Realm()
try! realm.write
{
for all in PracticeTestValues as! [Any]
{
realm.add(all as! Object, update: true)
}
}
I would sugget to use this:
for all in PracticeTestValues as? NSArray
{
realm.add(all as! Object, update: true)
}
I'm currently using AlamofireObjectMapper to create JSON objects. I'm having a tough time accessing JSON arrays:
This is the JSON Array:
[
{
"city": "string",
"country": "string",
"county": "string",
}
]
This is the function:
func getMemberDetails ( id: String) {
Alamofire.request(.GET, "\(baseURL)/api/Members/\(id)/memberDetails").responseArray { (response: Response<[MemberDetailInfo], NSError>) in
let memberDetailArray = response.result.value
if let memberDetailArray = memberDetailArray {
for memberDetail in memberDetailArray {
print(memberDetail.createDate)
print(memberDetail.id)
}
}
}
}
This Is the class:
class MemberDetailInfo: Mappable{
var city: String?
var country: String?
var county: String?
required init?(_ map: Map) {
mapping(map)
}
unc mapping(map: Map) {
city <- map["city"]
country <- map["country"]
county <- map["county"]
}
}
Whenever I step through it it just jumps right to the end, I’m not sure why it isn’t working. If anyone knows how to extract the JSON data from the array it would be greatly appreciated.
I'm receiving the following json from the API:
[ { "first_id": 1,
"second_objs": [ { "second_id": 2,
"third_objs": [ { "third_id": 3,
"param": "abcd" }] } ] } ]
And serialising it using ObjectMapper:
class First: NSObject, Mappable {
var first_id: Int?
var second_objs: [Second]?
required init?(_ map: Map){}
func mapping(map: Map) {
first_id <- map["first_id"]
second_objs <- map["second_objs"]
}
}
class Second: NSObject, Mappable {
var second_id: Int?
var third_objs: [Third]?
required init?(_ map: Map){}
func mapping(map: Map) {
second_id <- map["second_id"]
third_objs <- map["third_objs"]
}
}
class Third: NSObject, Mappable {
var third_id: Int?
var param: String?
required init?(_ map: Map){}
func mapping(map: Map) {
third_id <- map["third_id"]
param <- map["param"]
}
}
Now after recieving and modifying that JSON I need to send it back to the API.
However before sending back I need to rename keys "second_objs" and "third_objs" to "something_else_2" and "something_else_3".
[ { "first_id": 1,
"something_else_2": [ { "second_id": 2,
"something_else_3": [ { "third_id": 3,
"param": "abcd" }] } ] } ]
How do I do the renaming in a clean way?