ios开发:alamofire解析接口内容

一,代码:

1,json返回:

{
  "status": "success",
  "code": 200,
  "time": "2026-03-29 14:29:06",
  "msg": "",
  "data": {
    "list": [
      {
        "id": 1,
        "author": "李白",
        "title": "静夜思"
      },
      {
        "id": 2,
        "author": "孟浩然",
        "title": "宿建德江"
      },
      {
        "id": 3,
        "author": "author3",
        "title": "title3"
      },
      {
        "id": 4,
        "author": "author4",
        "title": "title4"
      },
      {
        "id": 5,
        "author": "author5",
        "title": "title5"
      },
      {
        "id": 6,
        "author": "author6",
        "title": "title6"
      },
      {
        "id": 7,
        "author": "author7",
        "title": "title7"
      },
      {
        "id": 8,
        "author": "author8",
        "title": "title8"
      },
      {
        "id": 9,
        "author": "author9",
        "title": "title9"
      },
      {
        "id": 10,
        "author": "author10",
        "title": "title10"
      },
      {
        "id": 11,
        "author": "author11",
        "title": "title11"
      },
      {
        "id": 12,
        "author": "author12",
        "title": "title12"
      }
    ]
  }
}

2, model类


import Foundation

// 最外层响应体
struct ApiResponse: Decodable {
    let status: String
    let code: Int
    let time: String
    let msg: String
    let data: ListData
}

// Data 层
struct ListData: Decodable {
    let list: [Poem]
}

// 具体的列表项(诗词)
struct Poem: Decodable {
    let id: Int
    let author: String
    let title: String
}

3, 返回数据

 

//
//  ContentView.swift
//  helloworld2
//
//  Created by liuhongdi on 2026/3/28.
//

import SwiftUI
import Alamofire

struct Item: Codable {
    let id: Int
    let author: String
    let title: String
}

struct ContentView: View {
    @State private var message = "加载中..."
    var urlString = "http://www.nihonnoma.net/list.php";
         var body: some View {
             Text(message)
                 .onAppear {
                     fetchData()
                 }
         }
         
         /// 获取数据
         func fetchData() {

             AF.request(urlString).responseDecodable(of: ApiResponse.self) { response in
                 switch response.result {
                 case .success(let apiResponse):
                     // 此时 apiResponse 已经是解析好的结构体对象
                     print("状态: \(apiResponse.status)")
                     
                     for poem in apiResponse.data.list {
                         print("ID: \(poem.id), 作者: \(poem.author), 标题:\(poem.title)")
                     }
                     
                 case .failure(let error):
                     // 常见的错误包括网络问题或 JSON 格式与模型不匹配
                     print("解析或网络错误: \(error)")
                 }
             }

             
         }
}

#Preview {
    ContentView()
}

 

二,运行结果:

image

 

posted @ 2026-03-29 15:25  刘宏缔的架构森林  阅读(1)  评论(0)    收藏  举报