Conversion between Array and JSON string using ObjectMapper
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