如何显示来自 Api 和 Json.file 的数据

Posted

技术标签:

【中文标题】如何显示来自 Api 和 Json.file 的数据【英文标题】:How to Display Data From Api and Json.file 【发布时间】:2018-09-28 06:42:30 【问题描述】:

我有两个数据 1.来自json 2.来自json.file

数据格式如下:-


  "data": [
    
      "question": "Gender",
      "options": [
        "Male",
        "Female"
      ],
      "button_type": "2"
    ,
    
      "question": "How old are you",
      "options": [
        "Under 18",
        "Age 18 to 24",
        "Age 25 to 40",
        "Age 41 to 60",
        "Above 60"
      ],
      "button_type": "2"
    ,
    
      "button_type": "2",
      "question": "I am filling the Questionnaire for?",
      "options": [
        "Myself",
        "Mychild",
        "Partner",
        "Others"
      ]
    
  ]

这是我的模型:-

enum NHAnswerType:Int

     case NHAnswerCheckboxButton = 1
     case NHAnswerRadioButton

     case NHAnswerSmileyButton
     case NHAnswerStarRatingButton

     case NHAnswerTextButton


class NH_QuestionListModel: NSObject 

    var dataListArray33:[NH_OptionsModel] = []

    var id:Int!
    var question:String!
    var buttontype:String!
    var options:[String]?
    var v:String?
    var answerType:NHAnswerType?

    var optionsModelArray:[NH_OptionsModel] = []
    init(dictionary :JSONDictionary) 

        guard   let question = dictionary["question"] as? String,
            let typebutton = dictionary["button_type"] as? String,

                let id = dictionary["id"] as? Int
             else 
                return

        
       // (myString as NSString).integerValue

        self.answerType = NHAnswerType(rawValue: Int(typebutton)!)

        if let options = dictionary["options"] as? [String]
           print(options)

            for values in options
                print(values)
                let optionmodel = NH_OptionsModel(values: values)
                self.optionsModelArray.append(optionmodel)
             
        

        self.buttontype = typebutton
        self.question = question
        self.id = id
    
  

选项模型:-

class NH_OptionsModel: NSObject 

    var isSelected:Bool? = false
    var textIndexPath :IndexPath?

    var dummyisSelected:Bool? = false

    var v:String?
        var values:String?

     init(values:String) 
           self.values = values
           print( self.values)
        
  

questionviewmodel:-中的视图模型-

 func loadData(completion :@escaping (_ isSucess:Bool) -> ())

        loadFromWebserviceData  (newDataSourceModel) in

            if(newDataSourceModel != nil)
            
                self.datasourceModel = newDataSourceModel!
                completion(true)
            
            else
                completion(false)
            
        
     
  func loadFromWebserviceData(completion :@escaping (NH_QuestionDataSourceModel?) -> ())

        //with using Alamofire  ..............
        //  http://localhost/json_data/vendorlist.php
        Alamofire.request("http://www.example.com").validate(statusCode: 200..<300).validate(contentType: ["application/json"]).responseJSON response in
            let status = response.response?.statusCode
            print("STATUS \(status)")

            print(response)

            switch response.result

            case .success(let data):
                print("success",data)

                let result = response.result

                print(result)

                if  let wholedata = result.value as? [String:Any]

                    print(wholedata)

                   // let data2 = wholedata["data"] as? [String:Any]
                        self.datasection1 = wholedata

                    if  let data1 = wholedata["data"] as? Array<[String:Any]>
                        print(data)
                        print(response)

                        for question in data1 
                            let typebutton = question["button_type"] as? String
                            print(typebutton)
                            self.type = typebutton

                            let options = question["options"] as! [String]
                         //   self.dataListArray1 = [options]
                            self.tableArray.append(options)
                           // self.savedataforoptions(completion: <#T##(NH_OptionslistDataSourceModel?) -> ()#>)

                            self.no = options.count
                        

                        print(self.tableArray)

                        let newDataSource:NH_QuestionDataSourceModel = NH_QuestionDataSourceModel(array: data1)

                        completion(newDataSource)
                    
                

            case .failure(let encodingError ):
                print(encodingError)

                //  if response.response?.statusCode == 404
                print(encodingError.localizedDescription)

                completion(nil)
            
        

虚拟数据视图模型:-

  func loadFromDummyData(completion :@escaping (NH_DummyDataSourceModel?) -> ())

if let path = Bundle.main.path(forResource: "jsonData", ofType: "json") 
    do 
        let jsonData = try NSData(contentsOfFile: path, options: NSData.ReadingOptions.mappedIfSafe)

        do 
            let jsonResult: NSDictionary = try JSONSerialization.jsonObject(with: jsonData as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary

           // self.datasection2 = jsonResult as! [String : Any]

            let people1  = jsonResult["data"] as? [String:Any]
            self.datasection2 = jsonResult as! [String : Any]
            if let people  = jsonResult["data"] as? Array<[String:Any]> 
                //  self.dict = people

                for person in people 
                    let options = person["options"] as! [String]
                    self.tableArray.append(options)
                    let name = person ["question"] as! String
                   self.tableArray.append(options)
                
                let newDataSource:NH_DummyDataSourceModel = NH_DummyDataSourceModel(array: people)

                completion(newDataSource)
            
         catch 
     catch 
   


 func loadData1(completion :@escaping (_ isSucess:Bool) -> ())

 loadFromDummyData (newDataSourceModel) in

    if(newDataSourceModel != nil)
    
        self.datasourceModel = newDataSourceModel!
        completion(true)
    
    else
        completion(false)
     
  

终于在viewcontroller:-

viewDidLoad:-

 questionViewModel.loadData  (isSuccess) in

            if(isSuccess == true)
            
                let sec = self.questionViewModel.numberOfSections()
                for _ in 0..<sec
                
                    self.questionViewModel.answers1.add("")
                    self.questionViewModel.questions1.add("")
                    self.questionViewModel.questionlist1.add("")
                

               self.item1 = [self.questionViewModel.datasection1]

               self.activityindicator.stopAnimating()
               self.activityindicator.isHidden = true
               self.tableview.refreshControl = refreshControl
               self.tableview .allowsMultipleSelection = false
               self.tableview.reloadData()

                self.dummyDataViewModel.loadData1 (isSuccess) in

                    if(isSuccess == true)
                    

                    
                    else
                     self.viewDidLoad() 
                    
                
            
            else
                self.activityindicator.stopAnimating()

                self.activityindicator.isHidden = true

                let controller = UIAlertController(title: "No Internet Detected", message: "This app requires an Internet connection", preferredStyle: .alert)
                // Create the actions
                let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) 
                    UIAlertAction in
                    NSLog("OK Pressed")
                    self.viewDidLoad()
                
                controller.addAction(okAction)
                self.present(controller, animated: true, completion: nil)
            
            self.sections = [Category(name:"A",items:self.item1),
                        Category(name:"B",items:self.item2),
            ]

            print(self.sections)
             self.tableview.reloadData()
        

这是来自 json.file 和 api 的格式。 我用过tableview。

所以我需要从关键“问题”中列出标题标题

并且应该从选项键显示行的单元格。

那么如何将JsonJson.file这两个数据相加呢?

【问题讨论】:

您是否尝试过任何方法来实现这一目标?显示你的代码? 请转到 app.quicktype.io 并粘贴您的 JSON。它为您创建数据模型以使用 Decodable 解码 JSON ...不要repost questions 【参考方案1】:

您可以创建代表您的模型的模型。最好喜欢

struct ResponseModel: Codable 
 var data: [Question]?


struct QuestionModel
 var question: String?
 var options: [String]?

然后在你的 Ajax post 使用之后

let responseData = try JSONDecoder().decode(AjaxResponse<ResponseModel>.self, from: data!)

现在你有你的数据了。

然后你可以在你的 UITableViewDeleates 中做

//节数

resposnseData.data.count

//节的行数

responseData.data[section].options.count

//用于索引的单元格修改您的单元格使用

response.data[indexPath.section].options[indexPath.row]

希望对你有帮助。

【讨论】:

如果 JSON 显然总是包含所有键,请不要建议可选类型。 @vadian 是的。这只是一个快速的答案。可能我会添加评论 @vinbhai4u 我已经更新了我的代码。请检查一下。如何组合这两个数据以及如何在 tableview 中列出数据?

以上是关于如何显示来自 Api 和 Json.file 的数据的主要内容,如果未能解决你的问题,请参考以下文章

如何在反应中显示来自api的数据

如何在 SwiftUI 中显示来自 API 的 JSON 数据?

如何在颤动中显示来自api响应的png图像?

在 ReactJS 中使用搜索框时如何显示来自 API 的信息?

如何比较来自同一API请求的JSON数据?

Dart/flutter:如何在模拟器的本地主机上显示来自 API 的图像