如何通过Food API编码此JSON回复

问题描述 投票:-5回答:4

我从API调用中获得以下响应

Optional(<__NSSingleObjectArrayI 0x6000024638d0>(
{
    name = "";
    steps =     (
                {
            equipment =             (
                                {
                    id = 404667;
                    image = "dutch-oven.jpg";
                    name = "dutch oven";
                }
            );
            ingredients =             (
                                {
                    id = 2009;
                    image = "chili-powder.jpg";
                    name = "chili powder";
                },
                                {
                    id = 19334;
                    image = "dark-brown-sugar.png";
                    name = "brown sugar";
                },
                                {
                    id = 1065062;
                    image = "whole-chicken.jpg";
                    name = meat;
                }
            );
            length =             {
                number = 15;
                unit = minutes;
            };
            number = 1;
            step = "Heat 1 package (4 cups) Savory Meat base, thawed, in a Dutch oven over medium heat. Stir in 2 teaspoons chili powder and 1 teaspoon brown sugar. Cover and simmer, stirring occasionally, 15 to 20 minutes.";
             },
                     {
                 equipment =             (
                 );

我需要提取详细步骤并保存,但是我无法通过此响应进行解析。有人可以帮忙吗?这是我用来保存此步骤的代码:

let recipeSumaryJson : JSON = JSON(response.result.value!)
let step = recipeSumaryJson["steps"]["step"]
json swift
4个回答
0
投票

您有一些响应,并且此响应的值很可能是Data类型,因此您需要decode它为某种Swift类型。


自Swift 4起,您可以轻松地使用Decodable协议将Data解码为符合该协议的自定义模型。

所以让我们为简单的json创建简单的结构

JSON:

let data = Data("""
{
    "property": "someName"
}
""".utf8)

型号:

struct Model: Decodable {
    let property: String
}

每个属性也必须为Decodable,因此,如果您具有不同的可解码结构,则可以将其用作属性的类型,甚至可以将其用于此类型的数组,例如某些字典

JSON:

let data = Data("""
{
    "items": [
        { "title": "name1" },
        { "title": "name2" },
        { "title": "name3" }
    ]
}
""".utf8)

型号:

struct Model: Decodable {
    let items: [Item]
}

struct Item: Decodable {
    let title: String
}

你看到那个图案吗?因此,请尝试根据您的情况自行实施。


现在最后一部分:解码。要解码Data,您可以简单地使用JSONDecoder及其JSONDecoder方法。只需指定输出类型并传递decode对象

请注意,解码可能会引发错误,因此应将其放入do-try-catch块中

Data

0
投票

首先,确保所获取的JSON数据有效,然后可以将其强制转换为[String:Any]。之后,您只需访问键的值即可。这是处理JSON的最简单方法。还有另一种更合适的方法,就是使用Model处理JSON。


0
投票

//这是一个JSON Food API程序,带有更多标签和更多标签。

guard let data = response.result.value else { ... }

do {
    response.result.value!
    let models = try JSONDecoder().decode([Model].self, from: data)
} catch { print(error) }

0
投票

import UIKit
import AFNetworking
import SDWebImage

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource
{

    @IBOutlet var tbl_reload: UITableView!
    var getAllData = NSMutableArray()
    override func viewDidLoad()
    {
        super.viewDidLoad()
        CallApi()
        // Do any additional setup after loading the view, typically from a nib.
    }

    func CallApi()
    {
        let manage = AFHTTPSessionManager()
        manage.get("https://smartfoodery.oneapp.ro/smart_food/public/api/get_restaurant/11", parameters: nil, progress: nil, success: { (Operation, response) in

            print(response!)
            if let data = response as? NSDictionary
            {
                let datas = data.value(forKey: "data") as! NSDictionary
                let restaurant_name = datas.value(forKey: "restaurant_name")
                self.title = "\(restaurant_name!)"

                let food_detail = datas.value(forKey: "food_detail") as! NSArray
                self.getAllData = NSMutableArray(array: food_detail)
                self.tbl_reload.reloadData()

            }

        }) { (Operation, Error) in
            print(Error.localizedDescription)
        }
    }

    //MARK:- Tableview Methods

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return getAllData.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


        let getData = getAllData.object(at: indexPath.row) as! NSDictionary
        let cell = tableView.dequeueReusableCell(withIdentifier: "displycell", for: indexPath) as! Customcell
        cell.lbl_name.text = (getData.value(forKey: "food_name") as! String)
        let food_image = getData.value(forKey: "food_image")
        cell.img_display.sd_setImage(with: URL(string: "\(food_image!)"), placeholderImage: UIImage(named: "placeholder.png"))
        cell.lbl_totalstock.text = "Total Stock : \(getData.value(forKey: "total_stock")!)"
        cell.lbl_foodprice.text = "Food Price :\(getData.value(forKey: "food_price")!)"
        cell.lbl_availabelstock.text = "Availabel Stock :\(getData.value(forKey: "available_stock")! )"
        cell.lbl_filtertype.text = "Filter Type : \(getData.value(forKey: "food_filter_type")!)"
        cell.lbl_availabelstock.font = UIFont(name: "Futura", size: 12)!
        cell.lbl_filtertype.font = UIFont(name: "Futura", size: 12)!
        cell.lbl_foodprice.font = UIFont(name: "Futura", size: 12)!
        cell.lbl_totalstock.font = UIFont(name: "Futura", size: 12)!
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 160.5
    }

}


© www.soinside.com 2019 - 2024. All rights reserved.