You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何JSON自动转为NSDictionary?如何转为MKGeoJSONFeature?

问题解答

1. 为何消息体自动转为NSDictionary?

WKWebKit的webkit.messageHandlers.postMessage在传递JS对象时,会自动将符合JSON结构的对象映射为OC/Swift的原生集合类型(NSDictionary/NSArray等),这是框架内置的序列化逻辑——目的是让原生端能直接使用结构化数据,省去手动解析JSON的步骤。

2. 如何阻止自动转换?

无法直接禁用框架的自动映射,但可以换一种传递方式:前端先把GeoJSON对象序列化为JSON字符串,再传递给Swift:

function sendPath(path){
    const jsonStr = JSON.stringify(path);
    window.webkit.messageHandlers.fieldDataPass.postMessage(jsonStr);
}

Swift端接收时直接转换为String,再转成Data后解析:

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    if message.name == "fieldDataPass" {
        if let jsonStr = message.body as? String, let jsonData = jsonStr.data(using: .utf8) {
            let parser = MKGeoJSONParser(data: jsonData)
            parser.parse()
            if let features = parser.parsedFeatures as? [MKGeoJSONFeature], let feature = features.first {
                showNamePrompt(pathData: feature)
                // 后续处理GeoJSONFeature
            }
        }
    }
}

3. 直接将NSDictionary转为MKGeoJSONFeature的方法

如果不想修改前端代码,也可以把已有的NSDictionary转回JSON Data,再用MKGeoJSONParser解析:

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    if message.name == "fieldDataPass" {
        if let dict = message.body as? NSDictionary {
            do {
                let jsonData = try JSONSerialization.data(withJSONObject: dict, options: [])
                let parser = MKGeoJSONParser(data: jsonData)
                parser.parse()
                if let features = parser.parsedFeatures as? [MKGeoJSONFeature], let feature = features.first {
                    showNamePrompt(pathData: feature)
                    // 处理解析后的Feature
                }
            } catch {
                print("转JSON Data失败: \(error)")
            }
        }
    }
}

只要原始JS对象是标准GeoJSON结构,这种转换方式就能正常工作。

内容的提问来源于stack exchange,提问作者ReezaCoriza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 13:38:17