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

iOS开发:从Web API返回的JSON中获取指定学生姓名返回Null

iOS JSON解析取不到字段?先看看你的JSON格式!

嘿,我看你遇到的问题很常见——能拿到JSON数据,但取学生姓名这类字段时返回null,大概率是你的JSON格式有问题,咱们一步步来排查解决:

首先,你的原始JSON有这些错误

你贴的JSON格式完全不符合标准,这是解析失败的核心原因:

  • 最外层的Sudent( { ... })是无效写法,JSON只能用{}(对象)或[](数组)包裹
  • 第三个学生对象前缺少了{,语法不完整
  • 所有学生数据没有放在一个统一的数组里,结构混乱

修正后的标准JSON格式

我帮你调整成了两种常见的正确格式,你可以对应API的实际返回情况选择:

格式1:外层对象包裹学生数组(推荐,结构更清晰)

{
  "students": [
    { 
      "id":"20", 
      "name":"Alan", 
      "email":"simpl@gmail.com", 
      "phone":"1234567890", 
      "location":"London"
    }, 
    { 
      "id":"40", 
      "name":"John", 
      "email":"simpl@gmail.com", 
      "phone":"1234567890", 
      "location":"usa"
    },
    { 
      "id":"50", 
      "name":"Nora", 
      "email":"simpl@gmail.com", 
      "phone":"1234567890", 
      "location":"kenya"
    }
  ]
}

格式2:直接返回学生数组

[
    { 
      "id":"20", 
      "name":"Alan", 
      "email":"simpl@gmail.com", 
      "phone":"1234567890", 
      "location":"London"
    }, 
    { 
      "id":"40", 
      "name":"John", 
      "email":"simpl@gmail.com", 
      "phone":"1234567890", 
      "location":"usa"
    },
    { 
      "id":"50", 
      "name":"Nora", 
      "email":"simpl@gmail.com", 
      "phone":"1234567890", 
      "location":"kenya"
    }
]

iOS里正确解析的代码示例(用Codable,苹果推荐方案)

首先定义对应的数据模型,属性名要和JSON里的键完全匹配(大小写也不能错):

// 学生模型
struct Student: Codable {
    let id: String
    let name: String
    let email: String
    let phone: String
    let location: String
}

// 如果用格式1(外层有students字段),需要额外定义一个根模型
struct StudentResponse: Codable {
    let students: [Student]
}

然后在请求API后解析数据:

// 假设你已经通过网络请求拿到了data对象
do {
    // 解析格式1的JSON
    let response = try JSONDecoder().decode(StudentResponse.self, from: data)
    // 遍历学生列表,就能正常拿到name了
    for student in response.students {
        print("学生姓名:\(student.name)")
    }
    
    // 如果是格式2的JSON,直接解析数组即可
    // let students = try JSONDecoder().decode([Student].self, from: data)
    // for student in students {
    //     print("学生姓名:\(student.name)")
    // }
} catch {
    // 打印解析错误,方便排查
    print("JSON解析出错:\(error.localizedDescription)")
}

额外提醒几个容易踩的坑

  • 属性名要完全匹配:JSON里是name,模型里就不能写成Name或者studentName,如果想自定义属性名,可以用CodingKeys映射(比如把JSON的id映射成模型的studentId)
  • 先验证API返回的真实JSON:可以用Postman或者直接在浏览器里调用API,确认返回的JSON格式和你预期一致,有时候你打印的JSON可能是代码处理后变形的
  • 处理可选字段:如果API返回的某些字段可能为null,记得把模型里对应的属性设为可选类型(比如let name: String?)

内容的提问来源于stack exchange,提问作者Mr david alan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:01:36