Skip to content

Instantly share code, notes, and snippets.

@p13i
Created February 15, 2018 22:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save p13i/0eff910d62a28a12c1f3b3d1bbfc3496 to your computer and use it in GitHub Desktop.
Save p13i/0eff910d62a28a12c1f3b3d1bbfc3496 to your computer and use it in GitHub Desktop.
Simple JSON wrapper for Foundation's JSONEncoder and JSONDecoder
//
// JSON.swift
//
// Created by Pramod Kotipalli on 11/1/17.
// Copyright © 2017 Pramod Kotipalli. All rights reserved.
//
import Foundation
public class JSON {
/**
Encodes the given Codable document into a Data object.
- parameter object: The object to encode.
- returns: A JSON-encoded Data representation of the given object.
*/
public class func encode<T: Codable>(_ object: T) -> Data? {
do {
let jsonEncoder = JSONEncoder()
let jsonData = try jsonEncoder.encode(object)
let jsonString = String(data: jsonData, encoding: .utf8)!
return jsonString.data(using: .utf8)!
} catch {
return nil
}
}
/**
Decodes the given JSON Data into the specified
- parameter jsonData: The Data to decode.
- parameter into: The type into which the Data should be decoded.
*/
public class func decode<T: Codable>(_ jsonData: Data, into: T.Type) -> T? {
do {
let jsonDecoder = JSONDecoder()
let string = String(data: jsonData, encoding: .utf8)!
let object = try jsonDecoder.decode(T.self, from: string.data(using: .utf8)!)
return object
} catch {
return nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment