I am currently using the ObjectMapper for Swift (see: https://github.com/Hearst-DD/ObjectMapper/) to convert a String
from a HTTP Request to an object of a custom class. The JSON I get from the request is a JSON Array, and I would like to convert this to an Array
from type CustomObject
.
I have tried it like this:
var object = Mapper<Array<CustomObject>>().map(string: json)
But then I get an error: Can not find member 'map'
.
How should this be done?
Edit: this is my CustomObject
Class, from now called ProductVariant
:
public class ProductVariant: Mappable {
/* Attributes */
public var id = 0
// var size : Size = nil
public var SKU = ""
public var stock = 0
public var numberOfDefects = 0
/* Constructors */
public init?() {
// Empty Constructor
}
required public init?(_ map: Map) {
mapping(map)
}
/* Methods */
public func mapping(map: Map) {
id <- map["id"]
SKU <- map["SKU"]
stock <- map["stock"]
numberOfDefects <- map["numberOfDefects"]
}
}
I have found a solution, which seems to be working:
var list: Array<ProductVariant> = Mapper<ProductVariant>().mapArray(string: json)
When I loop through the array, it gives me the correct attributes for the CustomObject
.
My mistake was that I tried to put the Array
in the type of the Mapper
, as shown in my question.
Another option is
let products = Mapper<ProductVariant>().mapArray(JSONString: json)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With