SwiftyJSON iterates over an array of JSON objects

[ { "cont": 9714494770, "id": "1", "name": "Kakkad" }, { "cont": 9714494770, "id": "2", "name": "Ashish" } ] 

One of them is a json array filled with JSON objects. I don't know how to parse this with SwiftyJSON

+6
source share
3 answers

An example on the SwiftyJSON page adapted to your data:

 let json = JSON(data: dataFromNetworking) for (index, object) in json { let name = object["name"].stringValue println(name) } 
+11
source

Assuming [{"id":"1", "name":"Kakkad", "cont":"9714494770"},{"id":"2", "name":"Ashish", "cont":"9714494770"}] assigned to a property named jsonData.

let sampleJSON = JSON(data: jsonData)

let sampleArray = sampleJSON.array sampleArray is an optional array of JSON objects.

let firstDict = sampleArray[0] firstDict - optional JSON dict.

let name = firstDict["name"] is an optional JSON object

let virtName = name.string is an optional string (in this case, "Kakkad").

let realName = name.stringValue realName is a string or an empty string.

You can also use: let longName = sampleJSON[0]["name"].stringValue

After initializing a JSON object with data, all elements are JSON types until you convert them to a fast type.

  • .string optional (string or zero)
  • .stringValue string or "" empty string
  • .dict optional ([String: AnyObject] or null)
  • .dictValue ([String: AnyObject] or String: AnyObject)
+2
source

For Swift4, I updated the code from Moritz's answer

  if let path : String = Bundle.main.path(forResource: "tiles", ofType: "json") { if let data = NSData(contentsOfFile: path) { let optData = try? JSON(data: data as Data) guard let json = optData else { return } //If it is a JSON array of objects for (_, object) in json { let name = object["name"].stringValue print(name) } } } 
0
source

Source: https://habr.com/ru/post/985550/


All Articles