【问题标题】:how can I parse alamofire return json to the array of strings in Swift?如何将 alamofire 返回 json 解析为 Swift 中的字符串数组?
【发布时间】:2017-04-16 23:28:10
【问题描述】:

在我的swift 应用程序中,我使用的是SwiftyJSONAlamofire

我有一个从后端返回到应用程序的 json:

{
  "responses" : [
    {
      "labelAnnotations" : [
        {
          "mid" : "\/m\/01yrx",
          "score" : 0.8735667499999999,
          "description" : "cat"
        },
        {
          "mid" : "\/m\/0l7_8",
          "score" : 0.7697883,
          "description" : "floor"
        },
        {
          "mid" : "\/m\/01c34b",
          "score" : 0.7577944,
          "description" : "flooring"
        },
        {
          "mid" : "\/m\/03f6tq",
          "score" : 0.52875614,
          "description" : "living room"
        },
        {
          "mid" : "\/m\/01vq3",
          "score" : 0.52516687,
          "description" : "christmas"
        }
      ]
    }
  ]
}

我想构造一个包含上述每个描述的Strings 数组。 我试图用代码解析它:

{
    case .success:
      print("sukces")


      if let jsonData = response.result.value {

        let data = JSON(jsonData)
            print(data)

        if let responseData = data["responses"] as? JSON{

            if let responseData2 = responseData["labelAnnotations"] as? JSON{
                for userObject in responseData2 {
                    print(userObject["description"])
                }
            }

        }

    }

     case .failure(let error):
        print("fail")
        print(error)
    }
}

但是print(userObject) 行返回空字符串。如何显示每个描述?一旦我可以在控制台中打印它,我就会将它添加到我的数组中。

【问题讨论】:

    标签: swift swift3 alamofire swifty-json


    【解决方案1】:

    检查字典值是否为JSON 类型似乎是这里的问题,因为SwiftyJSON 所做的只是让您免于使用as? ... 进行类型检查的麻烦。

    我对图书馆不熟悉,但我认为你所要做的就是:

    (假设 response.result.value 返回一个字典,因为您使用了 .responseJSON 方法,例如 Alamofire.request(...).responseJSON(...),否则如果您调用了 .response(...),则必须使用 JSON(data: $0.data)。) em>

    Alamofire.request(...).responseJSON { response in
      if let dictionary = response.result.value {
        let JSONData = JSON(dictionary)
        let userObjects =  JSONData["responses"][0]["labelAnnotations"].arrayValue.map( 
          { $0["description"].stringValue }
        )
      }
    }
    

    【讨论】:

    • swiftyJson 不是一个解决方案,如果您想生成一个适当的数组列表以便缓存或使用 UserDefaults 存储在 plist 中。
    • @OnderOZCAN 与 SwiftyJSON 不适合缓存内容或任何其他内容有什么关系?我认为该库主要用于处理可转换为 JSON 对象的数据。
    猜你喜欢
    • 1970-01-01
    • 2019-04-08
    • 1970-01-01
    • 2019-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多