基于Key检索JSON内容的Decodable实现方案问询
实现App启动时下载JSON并根据Key查询节点内容
针对你的需求,我来分享两种常见移动端平台(iOS/Swift、Android/Kotlin)的实现方案,包含启动时下载解码JSON,以及根据Key查询对应节点内容的函数。
iOS/Swift 实现
1. 定义JSON对应的模型(类型安全解码)
首先我们根据你的JSON结构定义Codable结构体,这样解码后能直接通过属性访问数据,避免字典取值的类型转换麻烦:
// 匹配JSON结构的Codable模型 struct TestData: Codable { let testName: TestNode // 映射JSON中的"Test Name"到属性testName enum CodingKeys: String, CodingKey { case testName = "Test Name" } } struct TestNode: Codable { let schede: [String: String] let info: String // 映射JSON中的"Info"到属性info enum CodingKeys: String, CodingKey { case schede case info = "Info" } }
2. App启动时下载并解码JSON
在AppDelegate(或者SwiftUI的App结构体)中,启动时发起网络请求下载JSON,异步解码后保存数据:
import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? // 保存解码后的全局数据 private var appData: TestData? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // 替换成你的指定JSON链接 guard let jsonUrl = URL(string: "https://your-api-url.com/data.json") else { print("无效的JSON链接") return true } // 后台线程发起网络请求,避免阻塞启动流程 URLSession.shared.dataTask(with: jsonUrl) { [weak self] data, _, error in guard let data = data, error == nil else { print("JSON下载失败: \(error?.localizedDescription ?? "未知错误")") return } do { // 解码JSON到模型 self?.appData = try JSONDecoder().decode(TestData.self, from: data) print("JSON解码完成!") // 测试查询函数 self?.appData.flatMap { self?.printNodeContent(forKey: "Test Name", data: $0) } } catch { print("JSON解码失败: \(error.localizedDescription)") } }.resume() return true } // 核心查询函数:传入Key,输出对应节点的所有内容 private func printNodeContent(forKey key: String, data: TestData) { // 匹配目标Key(可扩展支持多个Key) guard key == "Test Name" else { print("未找到匹配的Key: \(key)") return } let targetNode = data.testName print("\n=== \(key) 对应的节点内容 ===") // 输出schede下的所有键值对 print("schede 字段内容:") targetNode.schede.forEach { infoKey, value in print("- \(infoKey): \(value)") } // 输出Info字段值 print("Info 字段值: \(targetNode.info)") } }
Android/Kotlin 实现
1. 定义JSON数据类
使用Gson库(需在build.gradle添加依赖)来解码JSON,定义对应的数据类:
import com.google.gson.annotations.SerializedName // 匹配JSON结构的数据类 data class TestData( @SerializedName("Test Name") val testName: TestNode ) data class TestNode( val schede: Map<String, String>, @SerializedName("Info") val info: String )
2. App启动时下载解码JSON
在自定义的Application类中,启动时异步下载并解码JSON:
import android.app.Application import com.google.gson.Gson import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.net.URL class MyApplication : Application() { // 保存全局解码数据 private var appData: TestData? = null override fun onCreate() { super.onCreate() startDownloadingJson() } private fun startDownloadingJson() { val jsonUrl = "https://your-api-url.com/data.json" // 替换为你的链接 // 后台线程执行网络操作 GlobalScope.launch(Dispatchers.IO) { try { val jsonString = URL(jsonUrl).readText() // 解码JSON到数据类 appData = Gson().fromJson(jsonString, TestData::class.java) // 切换到主线程处理结果(可选) withContext(Dispatchers.Main) { appData?.let { printNodeContent("Test Name", it) } } } catch (e: Exception) { e.printStackTrace() println("下载/解码失败: ${e.message}") } } } // 查询函数:传入Key输出节点内容 private fun printNodeContent(key: String, data: TestData) { when(key) { "Test Name" -> { val node = data.testName println("\n=== $key 对应的节点内容 ===") println("schede 字段内容:") node.schede.forEach { (infoKey, value) -> println("- $infoKey: $value") } println("Info 字段值: ${node.info}") } else -> println("未找到匹配的Key: $key") } } }
注意事项
- Android需在
AndroidManifest.xml中添加网络权限:<uses-permission android:name="android.permission.INTERNET"/> - Swift中如果使用HTTP链接,需要在
Info.plist添加NSAppTransportSecurity例外(允许非HTTPS请求) - 网络操作必须在后台线程执行,避免阻塞App启动或UI线程
- 可以根据需求扩展查询函数,支持多个Key的匹配,或者返回数据而非直接打印
内容的提问来源于stack exchange,提问作者user9779811
相关产品推荐
相关产品推荐

