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

Swift解析特定字符串:提取姓名学号及转字典数组方法咨询

Swift解析自定义字符串获取姓名的方法

首先明确:你提供的字符串不是标准JSON格式,还存在语法错误(第三个条目里的"place"="bbc,缺少闭合引号),所以无法直接解析为字典数组,必须先处理格式并修复错误。

步骤1:修复原字符串的语法错误

修正后的字符串如下:

"Student"={"Info"={}},
"Student"={"SchoolName"="abc","place"="abc","Info"={"Name"="student1","class"="class1"}},
"Student"={"SchoolName"="abc","place"="bbc","Info"={"Name"="student2","class"="class1"}}

步骤2:转换为标准JSON格式

原字符串是类似Objective-C的字典语法,需要转换成JSON格式才能被Swift原生解析:

  • 将所有"Key"="Value"格式替换为JSON的"Key":"Value"格式
  • 将每个"Student"={...}条目转换为{"Student":{...}}
  • 把所有条目包裹在数组[]中,同时去除末尾多余的逗号

转换后的标准JSON如下:

[
    {"Student":{"Info":{}}},
    {"Student":{"SchoolName":"abc","place":"abc","Info":{"Name":"student1","class":"class1"}}},
    {"Student":{"SchoolName":"abc","place":"bbc","Info":{"Name":"student2","class":"class1"}}}
]

步骤3:Swift解析实现

使用JSONSerialization解析转换后的JSON字符串,提取姓名:

import Foundation

// 修正并转换后的JSON字符串
let jsonString = """
[
    {"Student":{"Info":{}}},
    {"Student":{"SchoolName":"abc","place":"abc","Info":{"Name":"student1","class":"class1"}}},
    {"Student":{"SchoolName":"abc","place":"bbc","Info":{"Name":"student2","class":"class1"}}}
]
"""

// 解析逻辑
if let data = jsonString.data(using: .utf8),
   let studentsArray = try? JSONSerialization.jsonObject(with: data) as? [[String: Any]] {
    for studentDict in studentsArray {
        if let studentInfo = studentDict["Student"] as? [String: Any],
           let info = studentInfo["Info"] as? [String: Any],
           let name = info["Name"] as? String {
            print("姓名:\(name)")
        } else {
            print("该学生无姓名信息")
        }
    }
}

补充说明

你提到的**学号(roll number)**在提供的字符串中没有对应字段,无法提取,需要确认原数据是否包含该字段。

内容的提问来源于stack exchange,提问作者Navaneeth A S

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 16:03:10