如何完全按照我的方式存储json响应的一部分?

时间:2019-05-16 07:33:06

标签: ios json swift alamofire

我有一个很大的JSON响应,我可以将响应映射到CODABLE类并在这些字段中使用数据。

但是如何存储部分JSON响应到数组或字符串变量?


"availabilityResultList":[  
   {  
      "availabilityRouteList":[  
         {  
            "availabilityByDateList":[  
               {  
                  "originDestinationOptionList":[  
                     {  
                        "fareComponentGroupList":[  
                           ...
                        ]
                     },
                     {  
                        "fareComponentGroupList":[  
                           ...
                        ]
                     }
                  ]
               }
            ]
         }
      ]
   }
]


我想存储“ fareComponentGroupList”中的所有内容 (两者分开,我可以通过

root?.availabilityResultList.first?.availabilityRouteList.first?.availabilityByDateList.first?.originDestinationOptionList[i]

当我尝试将上述代码转换为字符串时,出现错误

Cannot convert value of type 'String' to expected argument type 'OriginDestinationOptionList'

那我该如何从响应中获取并存储呢?(因为我必须在POST期间将整个响应发送回服务器)

当我尝试

po 
 root?.availabilityResultList.first?.availabilityRouteList.first?.availabilityByDateList.first?.originDestinationOptionList[i]

给出

的输出
▿ Optional<OriginDestinationOptionList>
  ▿ some : OriginDestinationOptionList
    ▿ fareComponentGroupList : 1 element
      ▿ 0 : FareComponentGroupList
        ▿ boundList : 1 element
          ▿ 0 : BoundList
......

当我尝试

print root?..availabilityResultList.first?.availabilityRouteList.first?.availabilityByDateList.first?.originDestinationOptionList[i]

我得到的输出

some {
  fareComponentGroupList = 1 value {
    [0] = {
      boundList = 1 value {
        [0] = {
          availFlightSegmentList = 1 value {
            [0] = {
              addOnSegment = false
              flightSegment = {
                journeyDuration = "PT1H15M"
                distance = 643
                departureAirport = {

如何将其转换为字符串?

回答,如果有人遇到此帖子。

编辑:

let objx = root!.availabilityResultList.first?.availabilityRouteList.first?.availabilityByDateList.first?.originDestinationOptionList[i]
 // i being the number of *fareComponentGroupList* inside originDestinationOptionList. (i = 1 to get first fareComponentGroupList , i = 2 to get next and so on. Used a for loop to automatically increment i)


                    do
                    {
                    let jsonxzx = try JSONEncoder().encode(objx)
                    let jsonStringb = String(data: jsonxzx, encoding:                     
                    .utf8)
                    }
                    catch
                    {
                    print("error")
                    }

还要防止有人想将字典转换为Json String

let dictionary = ["nacho": ["1","2","3"]]
let jsonData = try? JSONSerialization.data(withJSONObject: dictionary, options: [])
let jsonString = String(data: jsonData!, encoding: .utf8)
print(jsonString)

0 个答案:

没有答案