如何将JSON数据从Alamofire转换为Swift对象

编程入门 行业动态 更新时间:2024-10-24 07:34:50
本文介绍了如何将JSON数据从Alamofire转换为Swift对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在 xcode 6.2中使用swift 1.1快速制作照片查看器应用程序

hi there im making a photo viewer app in swift using swift 1.1 in xcode 6.2

我遇到了麻烦尝试将json响应从 alamofire转换为swift对象。我使用了swiftyjson库,但似乎存在兼容性问题。这是我的模型类

i am a having trouble trying to convert json response from alamofire to swift objects.i have used swiftyjson library but it seems there is a compatibility issues.here is my model class

import Foundation struct Photo { var name: String var filename :String var notes: String }

这是我的viewController

here is my viewController

import UIKit class ImageViewerTableViewController: UITableViewController { var photos = [Photo]() override func viewDidLoad() { super.viewDidLoad() Alamofire.request(.GET, "httpbin/get") .responseJSON { (_, _, JSON, _) in } }

在这种情况下,我如何将json映射为快速对象

how can i map json to swift objects in this situation

谢谢。

推荐答案

最好的解决方案是使用 AlamofireObjectMapper 。

The best solution is to use AlamofireObjectMapper.

您的代码应该看起来像这样:

Your code should look like this:

import Foundation import ObjectMapper struct Photo: Mappable { var name: String var filename :String var notes: String required init?(map: Map) {} func mapping(map: Map) { self.name <- map["name"] self.filename <- map["filename"] self. notes <- map["notes"] } }

在viewController:

In viewController:

import UIKit class ImageViewerTableViewController: UITableViewController { var photos = [Photo]() override func viewDidLoad() { super.viewDidLoad() Alamofire .request(.GET, "httpbin/get") .responseArray { (response: Response<[Photo], NSError>) in if let myPhotos = response.result.value { print(myPhotos) } } } }

AlamofireObjectMapper 和 ObjectMapper 的文档以获取更多信息。

Look the documentation of AlamofireObjectMapper and ObjectMapper for more informations.

更多推荐

如何将JSON数据从Alamofire转换为Swift对象

本文发布于:2023-11-26 18:31:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634700.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   如何将   对象   数据   Alamofire

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!