SPB Git

Repository Public

JSONValue.swift 6.6 KB 173 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Vrai-Prix iOS9// File             : VraiPrix/Core/V3/JSONValue.swift10// Description      : valeur JSON tolérante. Les modèles de l'API v3 se lisent11//                    par accès nommés : une clé absente, nulle ou d'un autre12//                    type rend nil, jamais une erreur de décodage (l'API v313//                    peut gagner des champs).14// Module           : VraiPrix15// Repository       : https://git.spboucher.ai/vrai-prix-ios-v316// Project Website  : https://www.vrai-prix.com17// Created          : 2026-11-2818// Last Modified    : 2026-11-2819//20// =============================================================================21// AUTHOR & PROFESSIONAL AFFILIATION22// =============================================================================23//24// Author           : Simon-Pierre Boucher25// Position         : Professor of Finance26// Institution      : Université du Québec en Outaouais (UQO)27// Department       : Département des sciences administratives28// Organization     : SP Boucher29//30// Website          : https://spboucher.ai31// Git              : https://git.spboucher.ai32//33// =============================================================================34// OFFICIAL CONTACT DIRECTORY35// =============================================================================36//37// General          : info@spboucher.ai38// Professional     : contact@spboucher.ai39// Direct           : simon@spboucher.ai40// Research         : research@spboucher.ai41// Development      : dev@spboucher.ai42// Support          : support@spboucher.ai43// Security/Admin   : admin@spboucher.ai44// Notifications    : notifications@spboucher.ai45//46// Preferred Contact: support@spboucher.ai47//48// =============================================================================49// COPYRIGHT & INTELLECTUAL PROPERTY50// =============================================================================51//52// Copyright (c) 202653// Simon-Pierre Boucher54//55// All rights reserved where applicable.56//57// This file is governed by the applicable project license,58// copyright notices, institutional agreements and relevant law.59//60// Unless expressly authorized by the applicable license or61// rights holder, copying, redistribution, sublicensing,62// publication and commercial exploitation are not permitted.63//64// Existing third-party rights and notices remain unaffected.65//66// =============================================================================67// CONFIDENTIALITY & SECURITY68// =============================================================================69//70// Classification   : Public71// Distribution     : Public repository; use is governed by the project license72// Security Contact : admin@spboucher.ai73//74// Access to this source does not independently grant permission75// to redistribute or disclose confidential materials.76//77// Do not embed credentials, private keys, access tokens,78// certificates or confidential personal information.79//80// =============================================================================81// LICENSE & MAINTENANCE82// =============================================================================83//84// License          : None specified (no license file in this repository)85// Maintainer       : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import Foundation9394enum JSONValue: Decodable, Sendable, Hashable {95    case null96    case bool(Bool)97    case number(Double)98    case string(String)99    case array([JSONValue])100    case object([String: JSONValue])101102    init(from decoder: Decoder) throws {103        let c = try decoder.singleValueContainer()104        if c.decodeNil() { self = .null }105        else if let b = try? c.decode(Bool.self) { self = .bool(b) }106        else if let d = try? c.decode(Double.self) { self = .number(d) }107        else if let s = try? c.decode(String.self) { self = .string(s) }108        else if let a = try? c.decode([JSONValue].self) { self = .array(a) }109        else if let o = try? c.decode([String: JSONValue].self) { self = .object(o) }110        else { self = .null }111    }112113    static func parse(_ data: Data) -> JSONValue? { try? JSONDecoder().decode(JSONValue.self, from: data) }114115    subscript(_ key: String) -> JSONValue {116        if case .object(let o) = self { return o[key] ?? .null }117        return .null118    }119120    var isNull: Bool { self == .null }121    /// l'objet lui-même s'il en est un (sinon nil) : pour les blocs facultatifs122    var object: JSONValue? { if case .object = self { return self } else { return nil } }123    var keys: [String] { if case .object(let o) = self { return o.keys.sorted() } else { return [] } }124    var items: [JSONValue] { if case .array(let a) = self { return a } else { return [] } }125126    var string: String? {127        switch self {128        case .string(let s): s129        case .number(let d): d == d.rounded() && abs(d) < 1e15 ? String(Int(d)) : String(d)130        default: nil131        }132    }133    /// texte non vide, espaces retirés134    var text: String? {135        guard let s = string?.trimmingCharacters(in: .whitespacesAndNewlines), !s.isEmpty else { return nil }136        return s137    }138    var double: Double? {139        switch self {140        case .number(let d): d.isFinite ? d : nil141        case .string(let s): Double(s)142        default: nil143        }144    }145    var int: Int? { double.map { Int($0.rounded()) } }146    var bool: Bool? {147        switch self {148        case .bool(let b): b149        case .number(let d): d != 0150        default: nil151        }152    }153    /// dictionnaire clé → entier (compteurs par motif, par statut)154    var counts: [String: Int] {155        guard case .object(let o) = self else { return [:] }156        return o.compactMapValues(\.int)157    }158}159160/// Modèle lu d'une valeur JSON ; `Decodable` par construction.161protocol JSONModel: Decodable, Sendable {162    init(json j: JSONValue)163}164165extension JSONModel {166    init(from decoder: Decoder) throws { self.init(json: try JSONValue(from: decoder)) }167}168169extension JSONValue {170    func model<T: JSONModel>(_ type: T.Type = T.self) -> T? { object.map(T.init(json:)) }171    func list<T: JSONModel>(_ type: T.Type = T.self) -> [T] { items.compactMap { $0.model(T.self) } }172}173
Files main
Menu

Theme