Skip to content

Instantly share code, notes, and snippets.

@d108
d108 / DataDecoder.swift
Last active June 3, 2023 06:26
Useful for decoding JSON data from a file by passing in a type.
/*
* SPDX-FileCopyrightText: © 2023 Daniel Zhang <https://github.com/d108/>
* SPDX-License-Identifier: MIT License
*/
import Foundation
struct DataDecoder
{
/// Generic decoder with a switch statement to handle specific types.
@Test fun testParseDaily2()
{
val expected = 13
val klx = Klaxon()
val dataKey = "Time Series (Daily)"
val days = klx.parseJsonObject(StringReader(File(pathname).readText()))
.filter { it.key == dataKey }
.map { it.value as JsonObject }.first().values
.map { klx.parseFromJsonObject<Daily>(it as JsonObject)?.close }
assertEquals(days.size, expected, "Bad count of " + days.size + ", expected " + expected + ".")
fun waitForCount() = runBlocking {
val count = async {
parseDaily()
}
count.await()
}
suspend fun parseDaily(): Int
{
val dataKey = "Time Series (Daily)"
@Test fun testParseDaily1()
{
val cnt = 0
val dataKey = "Time Series (Daily)"
val klx = Klaxon()
val f = File(pathname).readText()
val parsed = klx.parseJsonObject(StringReader(f))
val timeSeries = parsed.filter {
it.key == dataKey
}.map {
data class Daily
(
@Json(name = "1. open")
val open: String,
@Json(name = "2. high")
val high: String,
@Json(name = "3. low")
val low: String,
@Json(name = "4. close")
val close: String,
timeSeries.first().values.forEach {
val day = klx.parseFromJsonObject<Daily>(it as JsonObject)
}
val parsed = klx.parseJsonObject(StringReader(f))
val timeSeries = parsed.filter {
it.key == dataKey
}.map {
it.value as JsonObject
}
val data1 = Klaxon().parse<String>(File(pathname).toString())
// This just tried to parse the filename.
val data2 = Klaxon().parse<File>(StringReader(File(pathname).toString())
// What's a Reader? I think that's what I need.
val data3 = Klaxon().parse<String>(File(pathname).readText())
// Oh, there's a readText(). Why didn't this work? It seems it's the wrong parse call evenough the types match.
val data4 = Klaxon().parseJsonObject(StringReader(File(pathname).readText()))
@d108
d108 / ResourceTypeDetector.swift
Created January 30, 2018 01:51
ResourceTypeDetector.swift code
}
// MARK: Synchronous detectors
open class ResourceTypeDetector: NSObject {
/// There is not very much of them nor big variety in them, so replacing with
/// regexes or adding leading dot in initialization would make the code
/// unnecessarily complicated.
fileprivate struct TypeMatcherDefinition {
@d108
d108 / AppDelegate.swift
Last active February 22, 2017 23:51
Xcode 8.2.1 app delegate formatted for ikiApps code style.
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder,
UIApplicationDelegate
{
var window: UIWindow?
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool