swift 蒸气 json 对数组的响应

swift vapor json response to array

使用 swift vapor 和 elasticsearch,得到如下响应:

{ "_shards": { "failed": 0, "successful": 5, "total": 5 }, "hits": { "hits": [ { "_id": "3", "_index": "items_v1", "_score": 1.2029922, "_source": { "property1": "test", "property2": "another test", ... }, "_type": "item" }, ...

在 "hits" -> "hits" -> “_source” 我得到了模型 "Item" 的所有属性。我如何从这个 json 响应中创建项目数组“[Item]”?

这样试试!我假设您得到了响应,并且该响应已保存在响应变量

    var myarray = [String]()
    let hitDict = response["hits"] as! [String:AnyObject]

    let hitArray = hitDict["hits"] as! Array

    let someDict = hitArray[0] as! [String:AnyObject]
    let sourcDict = someDict["_source"] as! [String:AnyObject]

    let property1 = sourcDict["property1"] as! String
    let property2 = sourcDict["property2"] as! String
    myarray.append(property1)
    myarray.append(property2)

以这种方式解析您的响应,因此如果某些值未发送,则不会发生崩溃。

if let dict = response as? [String : Any] {
    if let hits = dict["hits"] as? [String : Any] {
        if let hitArray = hits["hits"] as? [[String : Any]] {
            for hit in hitArray {
                if let source = hit["_source"] {
                    arrayOfItems.append(Item(with: source))
                }
            }
        }
    }
}

Int 你的 Item class 创建 init 方法,你将在其中初始化项目的属性。

init(with dict: [String : Any]) {

    if let property1 = dict["property1"] as? Int {
        self.property1 = property1
    }

    super.init()
}

小改进,使用保护语句避免嵌套 ifs...

guard
  let dict = response as? [String : Any],
  let hits = dict["hits"] as? [String : Any],
  let hitArray = hits["hits"] as? [[String : Any]]
else
{ throw Abort}

for hit in hitArray {
   if let source = hit["_source"] {
        arrayOfItems.append(Item(with: source))
   }
}
var myArray = [String:String]()

//response from try drop.client.get(…)
let bodyReceived = responseFirebaseAssigned?.body.bytes

//JSON object made of bodyReceived
let JsonFirebase:JSON? 

     for val in JsonFirebase?.object ?? [:]{

        let valKey = val.key.string
        let valValue = val.value.string
        arrayFB[valKey!] = valValue
        print("arrayFB is \(arrayFB)")
    }