//
//  JSON.swift
//  Astro
//
//  Created by Jeremy Wiebe on 2015-04-20.
//  Copyright (c) 2015 Mobify Research & Development Inc. All rights reserved.
//

import Foundation

class JSON {
    static func serialize(_ jsonObject: JSONObject) -> String? {
        if !JSONSerialization.isValidJSONObject(jsonObject) {
            AstroLog.logger(AstroLog.Json).error("Cannot serialize object to JSON: \(jsonObject)")
            return nil
        }

        if let data = try? JSONSerialization.data(withJSONObject: jsonObject) {
            return String(data: data, encoding: .utf8)
        }

        AstroLog.logger(AstroLog.Json).error("Cannot serialize object to JSON: \(jsonObject)")
        return nil
    }

    static func deserialize(_ json: String) -> JSONObject? {
        if let data = json.data(using: .utf8, allowLossyConversion: false) {
            if let object = (try? JSONSerialization.jsonObject(with: data)) as? NSDictionary {
                return object as? JSONObject
            }
        }

        AstroLog.logger(AstroLog.Json).error("Could not deserialize JSON!  \(json)")
        return nil
    }
}
