posted in Swift 

ObjectMapper is a swift library like Gson in Java. Using ObjectMapper, I can easily convert basic classes into JSON format string or convert it inversely.

The code below shows how to convert swift array into JSON and also recover it from JSON.

class Book: Mappable{
    var id:Int?
    var title:String?
    var category:[String]?
    
    init(id:Int, title:String, category:[String]){
        self.id = id
        self.title = title
        self.category = category
    }
    
    required init?(_ map: Map) {
        
    }
    
    func mapping(map: Map) {
        id          <- map["id"]
        title       <- map["title"]
        category    <- map["category"]
    }
}


// Do the conversion
let JSON = "{\"id\":3, \"title\":\"The Third Book\", \"category\":[\"TOP\", \"TECH\"]}"

// Convert JSON to class instance
let book3 = Mapper<Book>().map(JSON)!

let book1 = Book(id: 1, title: "The First Book", category: ["TECH"])
let book2 = Book(id: 2, title: "The Second Book", category: ["ART","MUSIC"])
let books = [book1, book2, book3]
   
// Convert array to JSON array string
let arrayJSON = Mapper().toJSONString(books, prettyPrint: true)

// Convert JSON array back to the array
let bookArray = Mapper<Book>().mapArray(arrayJSON)

TAG: ObjectMapper, JSON, Swift, Array, Convert, Conversion

posted in Swift  iOS 

The class NSDateFormatter is an easy-to-use tool. Just like SimpleDateFormat in Java.

Convert String to NSDate

let str = "2016-06-01T00:00:00Z"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.dateFromString(str)

Convert NSDate to String

let description = "Time is \(dateFormatter.stringFromDate(date))"

TAG: Convert, String, NSDate, NSDateFormatter