Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Convert JSON String to Array of Custom Object with ObjectMapper

Tags:

json

swift

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"]
    }
}
like image 421
bashoogzaad Avatar asked Mar 24 '15 16:03

bashoogzaad


2 Answers

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.

like image 192
bashoogzaad Avatar answered Oct 31 '22 12:10

bashoogzaad


Another option is

let products = Mapper<ProductVariant>().mapArray(JSONString: json)
like image 3
Bogdan Ustyak Avatar answered Oct 31 '22 11:10

Bogdan Ustyak