Swift - how to find out the size of JSON?

0

I'm getting a Json from a link. How do I find its size and thus how do I assign the "image" key to a String vector - var img = [String]() ?

JSON example:

[{"imagem":"textoX","link":"link da webX"},
 {"imagem":"textoY","link":"link da webY"},
 {"imagem":"textoZ","link":"link da webZ"}]

Picking up JSON and consulting:

func search(query: String) {
    guard
        let _ = query.stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet()),
        url = NSURL(string:  "http://meusite.com.br/app/teste.php?a=1000")
        else { return }
    NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, response, error) -> Void in
        guard
            let httpURLResponse = response as? NSHTTPURLResponse where httpURLResponse.statusCode == 200,
            let data = data where error == nil
            else { return }
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            var error: NSError?
            let json = JSON(data: data, options: .AllowFragments, error: &error)
            if let error = error {
                print(error.localizedDescription)
            }
    //IMPRIMINDO JSON. . .       
            print("===json start")
            print(json)
            print("===json end")

    //CONSULTANDO JSON. . .

            print(json[0]["imagem"])  // CHAVE IMAGEM DA POSIÇÃO 0
            print(json[1]["imagem"])  // CHAVE IMAGEM DA POSIÇÃO 1
        }
    }).resume()
}

I am using SwiftJSON.swift and in plist I am with App Transport Security Settings

In this way it prints in the response I want to assign to a [String]:

var int = 0
            for (key, subJson) : (String, JSON) in json {
                print("=======Passei aqui!!!=======")
                print(json[int]["imagem"])
                int = int+1

            }
    
asked by anonymous 02.05.2016 / 18:57

2 answers

1

To iterate through JSON:

  let json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as! [[String: AnyObject]]
  for objeto in json {
    // preenche os arrays com os dados do JSON
    imagens.append(String(objeto["imagem"]))
    links.append(String(objeto["link"]))
  }

Then just use the arrays:

Thesamplecodeis in this gist playground;)

    
04.05.2016 / 19:20
2

If I understand correctly, you want to iterate over the object json and add it to the img vector, right?

Considering this, you do so:

var img: [String] = []

for (index, subJson) : (String, JSON) in json {
    if let imagem: String = json[index]["imagem"] {
        img.append(imagem)
    }
}

// Resultado
print(img)
    
03.05.2016 / 13:45