Skip to content
Next Next commit
Add message parsing utility to parse generic message objects
  • Loading branch information
chickdan committed Oct 27, 2022
commit a9d5feed4e9b4f1f3ee35293729b03f872ae333a
46 changes: 46 additions & 0 deletions Sources/ForemWebView/Utils/MessageParser.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
//
// MessageParser.swift
//
//
// Created by Daniel Chick on 10/26/22.
//

import Foundation

public typealias Json = [String: Any]

public class MessageParser {
public init () {}

public func parse<T: Decodable>(jsonArray: [Json]) -> T? {
guard let serializedInnerJSON = try? JSONSerialization.data(withJSONObject: jsonArray) else {
return nil
}

return parseObject(serializedJson: serializedInnerJSON)
}

public func parse<T: Decodable>(json: Json) -> T? {
guard let serializedInnerJSON = try? JSONSerialization.data(withJSONObject: json) else {
return nil
}

return parseObject(serializedJson: serializedInnerJSON)
}

public func parse<T: Decodable>(json: Any) -> T? {
guard let serializedInnerJSON = try? JSONSerialization.data(withJSONObject: json) else {
return nil
}

return parseObject(serializedJson: serializedInnerJSON)
}

private func parseObject<T: Decodable> (serializedJson: Data) -> T? {
do {
return try JSONDecoder().decode(T.self, from: serializedJson)
} catch {
return nil
}
}
}