Swift alamofire响应JSON转换为一个内置的JSON

时间:2018-05-08 12:13:06

标签: swift xcode alamofire

我是第一次开发ios应用程序,我使用Alamofire和Swiftyjson来处理网络,但我不知道Alamofire有什么问题,每次我用空间解析JSON的输出就像那样 例如:

{
   "ref_number":"EPFNKS",
   "datetime_of_booking":"2018-05-08 13:13",
   "datetime_pay_by":"2018-05-08 23:13",
   "nta":1250100,
   "fare_details":[
      {
         "basic":1070000,
         "tax":107000,
         "iwjr":5000,
         "insurance":0,
         "fuel":0,
         "adm":100000,
         "total":1282000,
         "generation":"adult",
         "surcharge":"0",
         "discount":"0"
      }
   ],
   "flights":{
      "go":[
         {
            "flight_num":"JT 912",
            "depart_port":"BPN",
            "depart_city":"Balikpapan",
            "depart_time":"18:05",
            "depart_date":"2018-05-10",
            "depart_datetime":"2018-05-10 18:05",
            "arrive_port":"BDO",
            "arrive_city":"Bandung",
            "arrive_time":"19:05",
            "arrive_date":"2018-05-10",
            "arrive_datetime":"2018-05-10 19:05",
            "class":"eco",
            "seat_class":"b"
         }
      ],
      "back":null
   },
   "inv_number":null
}

因为我想再将json发送到服务器,我必须将它转换为onelined utf8编码的json,如下所示:

{"ref_number":"EPFNKS","datetime_of_booking":"2018-05-08 13:13","datetime_pay_by":"2018-05-08 23:13","nta":1250100,"fare_details":[{"basic":1070000,"tax":107000,"iwjr":5000,"insurance":0,"fuel":0,"adm":100000,"total":1282000,"generation":"adult","surcharge":"0","discount":"0"}],"flights":{"go":[{"flight_num":"JT 912","depart_port":"BPN","depart_city":"Balikpapan","depart_time":"18:05","depart_date":"2018-05-10","depart_datetime":"2018-05-10 18:05","arrive_port":"BDO","arrive_city":"Bandung","arrive_time":"19:05","arrive_date":"2018-05-10","arrive_datetime":"2018-05-10 19:05","class":"eco","seat_class":"b"}],"back":null},"inv_number":null}

如何将具有空格的JSON转换为在线?

感谢

1 个答案:

答案 0 :(得分:0)

Alamofire有一些非常有趣的方法来处理代码。老实说,我要说,放弃SwiftyJSON依赖,因为你正在以艰难的方式去做。只需使用Alamofire的.responseData链方法直接处理数据。

我想提一下,就像Swift 4," Codable"类使得解码和编码对象变得更好,以更加面向对象的方式完成您尝试执行的操作。你只需要处理" try-do-catch"语句以及极端情况下可能的编码器和解码器。这将使您的代码更加健壮。

You can find a great tutorial on how to go about that here