Creating nested dictionary for JSON - ios

I am trying to replicate the json format for a POST request, but I am having trouble working with the following 2D dictionary in Swift.
payload = {"cardholder": {
"address": {
"city": "city",
"state": "MA",
"street": "street",
"zip_code": "11111"
},
"shipping_address": {
"city": "city",
"state": "MA",
"street": "street",
"zip_code": "11111"
}
}}
Is there a way I can set up addressDetails and shippingDetails?
var addressDetails = ["city": self.newCity!, "state": self.newState!,"street": self.newStreet!,"zip_code": self.newZipcode!]
var shippingDetails = ["city": self.newCity!, "state": self.newState!,"street": self.newStreet!,"zip_code": self.newZipcode!]
if self.newUnit != ""{
addressDetails["unit"] = self.newUnit!
shippingDetails["unit"] = self.newUnit!
}
var test: [String:[String:[String:String]]] = ["cardholder": ["address": addressDetails]]

To answer your question: yes. Everything you need to do is add shippingDetails to the test["cardholder"] dict:
var test: [String:[String:[String:String]]] = ["cardholder": ["address": addressDetails, "shipping_address": shippingDetails]]
However, I totally agree with #Paulw11, you should not fiddle around with dictionaries that way. Use structs that conform to Codable instead:
struct Address: Codable {
var city: String
var state: String
var street: String
var zipCode: String
var unit: String?
enum CodingKeys: String, CodingKey {
case city, state, street, zipCode = "zip_code", unit
}
}
struct Cardholder: Codable {
var address: Address
var shippingAddress: Address
enum CodingKeys: String, CodingKey {
case address, shippingAddress = "shipping_address"
}
}
struct Payload: Codable {
var cardholder: Cardholder
}
...
let addressDetails = Address(city: self.newCity!, state: self.newState!, street: self.newStreet!, zipCode: self.newZipcode!, unit: self.newUnit == "" ? nil : self.newUnit)
let shippingDetails = Address(city: self.newCity!, state: self.newState!, street: self.newStreet!, zipCode: self.newZipcode!, unit: self.newUnit == "" ? nil : self.newUnit)
var test = Payload(cardholder: Cardholder(address: addressDetails, shippingAddress: shippingDetails))

Related

Elegant solutions to decoding a JSON nested array in swift using decodable

Currently working with an API, and while I have successfully gotten it to decode the full result, I am only interested in the Entities/identifier portion. While I have gotten it working and get what I want/need I feel like this could be done better and more elegant and maybe in a single step. Any insight/suggestions appreciated.
JSON returned from API:
{
"count": 4596,
"entities": [
{
"facet_ids": [
"contact",
"siftery",
"investor",
"ipqwery",
"aberdeen",
"apptopia",
"semrush",
"company",
"rank",
"builtwith",
"bombora",
"key_event"
],
"identifier": {
"uuid": "468bef9f-2f50-590e-6e78-62e3adb05aa1",
"value": "Citi",
"image_id": "v1417152861/pdgwqt8ddecult5ktvdf.jpg",
"permalink": "citigroup",
"entity_def_id": "organization"
},
"short_description": "Citigroup is a diversified financial services holding company that provides various financial products and services."
},
{
"facet_ids": [
"contact",
"siftery",
"investor",
"apptopia",
"semrush",
"company",
"rank",
"builtwith",
"key_event"
],
"identifier": {
"uuid": "031a344b-c2b9-e60b-d950-1ae062026fde",
"value": "Citi",
"image_id": "yzlzhjqpparamrswaqa1",
"permalink": "citi-2",
"entity_def_id": "organization"
},
"short_description": "CITi is an NPO supporting the ICT sector in Western Cape."
},
{
"facet_ids": [
"contact",
"siftery",
"semrush",
"company",
"rank",
"builtwith",
"bombora"
],
"identifier": {
"uuid": "7ce45379-957c-49c5-bca2-c9ffd521f7da",
"value": "CITI",
"image_id": "qbkqndm7d0wgbogxjcrs",
"permalink": "citi-f7da",
"entity_def_id": "organization"
},
"short_description": "CITI trusted gateway to project-based change expertise that major organisations need to thrive, change and innovate."
}
]
}
Structs:
struct Entity: Decodable, Identifiable
{
var id: String
var companyName: String
var permalink: String
var imageID: String
init(from entity: Entities.Entity) throws
{
self.id = entity.identifier?.uuid ?? ""
self.companyName = entity.identifier?.value ?? ""
self.permalink = entity.identifier?.permalink ?? ""
self.imageID = entity.identifier?.image_id ?? ""
}
}
struct Entities: Decodable
{
var count:Int?
var entities: [Entity]?
struct Entity: Decodable
{
var facet_ids:[String]?
var identifier:Identifier?
var short_description:String?
}
struct Identifier:Decodable
{
var permalink:String?
var value:String?
var image_id:String?
var entity_def_id:String?
var uuid:String?
}
}
Call to decode:
if let data = data{
do {
let businessEntities = try decoder.decode(Entities.self, from: data)
let entities:[Entity] = try businessEntities.entities!.compactMap{
entity in
do
{
return try Entity(from: entity)
}
}
Thinking you are just interested in the Entities/identifier, you can simplify your model. Here's an example:
typealias Entities = [Entitie]
struct Entitie: Codable {
let facetIDS: [String]
let identifier: Identifier
let shortDescription: String
enum CodingKeys: String, CodingKey {
case facetIDS = "facet_ids"
case identifier
case shortDescription = "short_description"
}
}
struct Identifier: Codable {
let uuid, value, imageID, permalink: String
let entityDefID: String
enum CodingKeys: String, CodingKey {
case uuid, value
case imageID = "image_id"
case permalink
case entityDefID = "entity_def_id"
}
}
You can access entities object and decode it like this:
guard let data = data,
let jsonDict = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let entitiesObj = jsonDict["entities"] else { return }
do {
let entitiesData = try JSONSerialization.data(withJSONObject: entitiesObj)
let result = try JSONDecoder().decode(Entities.self, from: entitiesData)
} catch {
print(error.localizedDescription)
}
Obs: I created the CodingKeys because I use camelCase in my projects, you can left it in snake_case just remember to replace variables.

How to configure model class for nested JSON response with Alamofire and Decodable in iOS

I'm using Alamofire and Decodable for a Google Books API request for performing a search.
I've created a Decodable model which I will add below and it worked up until I try to get any other field below "title" in "volumeInfo" (I've been commenting out properties one by one to check where it fails). The error I get after uncommenting "authors", "publisher" or anything other than "title" inside "volumeInfo" is:
responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.decodingFailed(error: Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "publisher", intValue: nil)
An example response is:
{
"kind": "books#volume",
"id": "Ett09eLWE5oC",
"etag": "WIwTdsmpnhs",
"selfLink": "https://www.googleapis.com/books/v1/volumes/Ett09eLWE5oC",
"volumeInfo": {
"title": "The Picture of Dorian Gray",
"authors": [
"Oscar Wilde"
],
"publisher": "Wordsworth Editions",
"publishedDate": "1992",
"description": "The handsome appearance of dissolute young Dorian Gray remains unchanged while the features in his portrait become distorted as his degeneration progresses",
"industryIdentifiers": [
{
"type": "ISBN_10",
"identifier": "1853260150"
},
{
"type": "ISBN_13",
"identifier": "9781853260155"
}
],
"readingModes": {
"text": false,
"image": true
},
"pageCount": 312,
"printType": "BOOK",
"categories": [
"Fiction"
],
"averageRating": 4.0,
"ratingsCount": 6,
"maturityRating": "NOT_MATURE",
"allowAnonLogging": false,
"contentVersion": "1.1.2.0.preview.1",
"panelizationSummary": {
"containsEpubBubbles": false,
"containsImageBubbles": false
},
"imageLinks": {
"smallThumbnail": "http://books.google.com/books/content?id=Ett09eLWE5oC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api",
"thumbnail": "http://books.google.com/books/content?id=Ett09eLWE5oC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"
},
"language": "en",
"previewLink": "http://books.google.ro/books?id=Ett09eLWE5oC&pg=PA130&dq=9781853260155&hl=&cd=1&source=gbs_api",
"infoLink": "http://books.google.ro/books?id=Ett09eLWE5oC&dq=9781853260155&hl=&source=gbs_api",
"canonicalVolumeLink": "https://books.google.com/books/about/The_Picture_of_Dorian_Gray.html?hl=&id=Ett09eLWE5oC"
}
}
My model:
struct Response: Decodable {
struct VolumeInfo: Decodable {
var title: String
//var authors: [String]
var publisher: String
//var identifiers: [Identifier]
//var image: ImageLink
enum CodingKeys: String, CodingKey {
case title
//case authors
case publisher
//case identifiers = "industryIdentifiers"
//case image = "imageLinks"
}
}
struct Identifier: Decodable {
var type: String
var identifier: String
enum CodingKeys: String, CodingKey {
case type
case identifier
}
}
struct ImageLink: Decodable {
var url: URL
enum CodingKeys: String, CodingKey {
case url = "thumbnail"
}
}
var id: String
var volumeInfo: VolumeInfo
}

How to construct struct based on json

I have list Json result based on that I created struct but while parsing getting an error typeMismatch. I am not able to find what's wrong going while create structs in code
I have created struct based on json which is not working for me
["status": "1",
"error": false,
"data": [
{
"order_id": "11",
"order_unique_id": "ORDR-1001",
"store_name": "24X7",
"otp_store": "781103",
"product": [
"Product One",
"Product Two"
],
"qty": [
"1",
"3"
],
"user_details": {
"name": "test",
"number": "98145314586",
"landmark": "test",
"area": "Bow East",
"pincode": "E3 9EG",
"place": "Home"
},
"status": "2",
"date": "2018-12-13",
"time": "14:37:57"
}]
struct RunnerStatus: Decodable {
var status: String
var error: Bool
var data: [Runner]
}
struct Runner: Decodable {
var order_id: String
var order_unique_id: String
var store_name: String
var otp_store: String
var product: [Product]
var qty: [Quantity]
var user_details: [UserDetails]
var status: String
var date: String
var time: String
}
struct Product: Decodable {
var ProductName: String
}
struct Quantity: Decodable {
var qty: String
}
struct UserDetails: Decodable {
var name: String
var number: String
var landmark: String
var area: String
var pincode: String
var place: String
}
all struct should bind with there associated value/Data
I think you structure should be as follows:
// 1
struct RootClass : Codable {
let data : [RunnerData]?
let error : Bool?
let status : String?
}
// 2
struct RunnerData : Codable {
let date : String?
let orderId : String?
let orderUniqueId : String?
let otpStore : String?
let product : [String]?
let qty : [String]?
let status : String?
let storeName : String?
let time : String?
let userDetails : UserDetail?
enum CodingKeys: String, CodingKey {
case date
case orderId = "order_id"
case orderUniqueId = "order_unique_id"
case otpStore = "otp_store"
case product
case qty
case status
case storeName = "store_name"
case time
case userDetails = "user_details"
}
}
// 3
struct UserDetail : Codable {
let area : String?
let landmark : String?
let name : String?
let number : String?
let pincode : String?
let place : String?
}
I hope this will help you. Let me know still you have any query.
If you create JSON structure manually than before you should have proper knowledge of making structure. Otherwise it's effect on JSONDecoding. There are lots of website available to make your json codable classes online, one of them is: http://www.jsoncafe.com/
Use this website to create your swift codable classes.

Parse Using Swifty JSON

My JSON is like:
{
"status": 1,
"msg": "Category Product List",
"product_data": [{
"product_id": "49",
"image": "http://192.168.1.78/Linkon/site/pub/static/frontend/Linkon/default/en_US/Magento_Catalog/images/product/placeholder/image.jpg",
"shopName": "putin",
"review": "",
"rating": "2",
"productName": "ccd",
"customrFirstName": "devi",
"customrLastName": "ss",
"address": "6th Ln, S.T.Colony, Mahalaxminagar, Rajarampuri, Kolhapur, Maharashtra 416008, India",
"contactNumber": null,
"description": "<p>ccd</p>"
},
{
"product_id": "50",
"image": "http://192.168.1.78/Linkon/site/pub/static/frontend/Linkon/default/en_US/Magento_Catalog/images/product/placeholder/image.jpg",
"shopName": "putin",
"review": "",
"rating": "2",
"productName": "car garage",
"customrFirstName": "devi",
"customrLastName": "ss",
"address": "6th Ln, S.T.Colony, Mahalaxminagar, Rajarampuri, Kolhapur, Maharashtra 416008, India",
"contactNumber": null,
"description": "<p>car garage</p>"
}
]
}
So my question is: How to create JSON model class and parse using swifty JSON?
I would recommend ditching SwiftyJSON in favor of the built-in Codable and JSONDecoder support in Swift 4.
For this, you simply define a struct that matches your JSON format, and decode it:
struct Data: Codable {
let status: Int
let msg: String
let products: [Product]
enum CodingKeys: String, CodingKey {
case status, msg
case products = "product_data"
}
}
struct Product: Codable {
let product_id, image, shopName, review: String
let rating, productName, customrFirstName, customrLastName: String
let address: String
let contactNumber: String?
let description: String
}
do {
let data = try JSONDecoder().decode(Data.self, from: json)
print("\(data.msg)") // e.g.
} catch {
print("\(error)")
}
You can create your data model class like below:
import UIKit
import SwiftyJSON
class ProductModels: NSObject {
var productModel:[ProductModel]?
}
public init(json:JSON) {
self.productModel = json["product_data"].dictionary
}
class ProductModel: NSObject {
var productID:String?
var image:String?
var shopName:String?
var review:String?
var rating:String?
var productName:String?
var customrFirstName:String?
var customrLastName:String?
var address:String?
var contactNumber:String?
var description:String?
public init(json:JSON) {
self.productID = json["product_id"].string
self. image = json["image"].string
self. shopName = json["shopName"].string
self. review = json["review"].string
self. rating = json["rating"].string
self. productName = json["productName"].string
self. customrFirstName = json["customrFirstName"].string
self. customrLastName = json["customrLastName"].string
self. address = json["address"].string
self. contactNumber = json["contactNumber"].string
self. description = json["description"].string
}
}
and can use this class by passing response from model who is calling api and getting this response example below: (the class where you are using this below code, you have to import SwiftyJSON)
Alamofire.request(//(your method or api call).responseJSON(completionHandler: { (response) in
switch response.result {
case .success(let value):
let productJson = JSON(value)
let productsData = ProductModels(json: productJson)
break;
}
})
You can create class using SwiftyJSONAccelerator
Get SwiftyJSONAccelerator from Here: https://github.com/insanoid/SwiftyJSONAccelerator
or you can create it online using https://app.quicktype.io/

iOS swift JSON to class object

How can I parse JSON to a class when JSON has multiples arrays?
I'm trying to convert data from REST API to my classes in Swift 2.0, but I can't figure out how to do it properly, anyone can help?
/* JSON from REST API
{
"Name": "New name",
"Email": "test#test.com",
"FacebookId": "new facebook Id",
"Address": "New Address",
"Photo": "https://graph.facebook.com/novo facebook Id/picture?width=500&height=500",
"CreditCards": [
{
"Id": 5,
"LastNumber": "3123",
"Brand": "visa"
},
{
"Id": 6,
"LastNumber": "3124",
"Brand": "visa"
}
]
}
Class representation in swift?
class Client {
var fullName: String?
var email: String?
var facebookId: String?
var photo: String?
var creditCards: [CreditCard]?
required init(json: JSON) {
self.fullName = json["FullName"].string
self.email = json["Email"].string
self.facebookId = json["FacebookId"].string
self.photo = json["Photo"].string
self.creditCards = json["CreditCards"]["Id"]
}
required init() {}
}
class CreditCard {
var Id: Int?
var lastNumber: String?
var brand: String?
}
You should take a look at the NSJSONSerialization class and its methods. They do exactly what you need: converting JSON data into arrays, dictionaries, strings and numbers.

Resources