Swift and Objectmapper: Nsdate with Min Value

Swift and ObjectMapper: NSDate with min value

ObjectMapper not convert from String to NSDate properly you have to make a workaround like this to specify the type of NSDate format it need to convert from the String :

func mapping(map: Map) {
id <- map["Id"]
color <- map["Cor"]
text <- map["Texto"]
kilometer <- map["Kilometro"]

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"

if let dateString = map["Data"].currentValue as? String, let _date = dateFormatter.dateFromString(dateString) {
date = _date
}
}

I hope this help you.

Swift Object Mapper passing a different date

Try using a DateFormatterTransform instead:

import Foundation
import ObjectMapper

class example :Mappable
{
var ExampleDate: Date?

required init?(map: Map){
}

//Mappable
func mapping(map: Map){
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'hh:mm:ss.SSSZ"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.locale = Locale(identifier: "en_US_POSIX")

ExampleDate <- (map["ReviewDate"], DateFormatterTransform(dateFormatter: dateFormatter))
}
}

And as a general observation try do avoid using a capital first letter for your variable names. It's the recommended way so you can easily distinguish them from types. So use exampleDate instead of ExampleDate

ObjectMapper - nested dynamic keys

Solution

I solved my problem by mapping the JSON manually.

class GroupResponse: Mappable {

var stats: [String: StatsYear]?

func mapping(map: Map) {
stats <- map["stats"]
}
}

class StatsYear: Mappable {

var months: [String: StatsMonth] = [:]

override func mapping(map: Map) {

for (monthKey, monthValue) in map.JSON as! [String: [String: Any]] {

let month = StatsMonth()

for (monthKeyType, valueKeyType) in monthValue {

if monthKeyType == "results" {
let tipResultDict = valueKeyType as! [String: Int]

for (result, tipsForResult) in tipResultDict {
month.tips[result] = tipsForResult
}
}
else if monthKeyType == "roi" {
month.roi = valueKeyType as? Double
}
else if monthKeyType == "win" {
month.win = valueKeyType as? Double
}
}
months[monthKey] = month
}
}
}

class StatsMonth {

var tips: [String: Int] = [:]
var roi: Double?
var win: Double?
}

There's probably a better solution to this problem but this is what I'm sticking with for now.

Hopefully this helps!

Swift ObjectMapper mapping an array with multiple types of values - numbers and complex objects mixed

I am afraid that the only way to map this array, using ObjectMapper, is in [Any]:

class Result: Mappable {
var id: Int?
var jsonrpc: String?
var result: [Any]?

required init?(map: Map) {}

func mapping(map: Map) {
id <- map["id"]
jsonrpc <- map["jsonrpc"]
result <- map["result"]
}
}

That way, for this particular json response, the first element of the array will be of type Int and the second will be of type [String: Any].

Of course, this includes the type casting procedure whenever you are trying to access an element of this array. (which is just bad)

Using cryptography with ObjectMapper

There are several ways to accomplish the data decryption. ObjectMapper provides the protocol TransformType to deal with data transformations while mapping (reference).

Transformer:

import ObjectMapper

class PointsTransform: TransformType {
typealias Object = Double
typealias JSON = String

func transformFromJSON(_ value: Any?) -> Object? {
guard let encoded = value as? String
else { return nil }

// TODO: Replace with decoding logic
return 239_584.938
}

func transformToJSON(_ value: Object?) -> JSON? {
guard let decoded = value
else { return nil }

return "\(decoded)"
}
}


Model:

class PosicaoConsolidada: Mappable {
var portifolioBalance: Double!
var families: [Family]!

required init?(map: Map) {}

public func mapping(map: Map) {
portifolioBalance <- (map["pointsBalance"], PointsTransform())
families <- map["fam"]
}

}

Get value from array objects with AlamofireObjectMapper/ObjectMapper (swift - iOS)

You have to map each property with correct data type of that property. One of the objects in your response contains a Boolean value ( For ex. "Response"), but you are declaring it as a String. We have to match the data type of the property exactly, else the object will be nil and will not be mapped.

Also search by id response does not match your mapper class.

let Result = response.result.value is wrong. response.result.value would yield you SearchResponse object.

Bottom line

You have to get the mapping part right first. Any mismatching types will be not be mapped. Using response object will give you the whole object with all the mappings instead of the JSON obviously. So it should be: let movie = response.result.value. Then you access movie's properties like for ex. movie.actors

Swift - ObjectMapper: Mapping jsonString

Please drop ObjectMapper.

It's a library of merit but since Swift 4 (introduced 2017) it has become obsolete in favor of the built-in and swiftier Codable protocol.

The main benefit is that the model files can be structs (value types) and it's much more reliable because the developer doesn't have to take care of literal string keys

This is sufficient

struct Model: Codable {
let cells : [Cell]
}

struct Cell: Codable {
let id: Int
let title: String
let description: String
}

The given JSON string

let jsonString = """
{"cells":[{"id":0,"title":"Header","description":"Description"},{"description":"Description","id":0,"title":"Header"},{"description":"Description","id":1,"title":"Header"},{"id":0,"title":"Header","description":"Description"},{"description":"Description","title":"Header","id":0}]}
"""

can be decoded and encoded with this code

do {
// Decode the JSON
let decoded = try JSONDecoder().decode(Model.self, from: Data(jsonString.utf8))
print(decoded)

// Encode it back
let encoded = try JSONEncoder().encode(decoded)
print(String(data: encoded, encoding: .utf8)!)
} catch {
print(error)
}


Related Topics



Leave a reply



Submit