Swift - how to find out the size of JSON?

Asked

Viewed 340 times

0

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

example JSON:

[{"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’m using the SwiftJSON.swift and in the plist I’m with the App Transport Security Settings

This way it prints in the answer I wish 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

            }

2 answers

2

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

Considering that, 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)
  • Exactly this however, when you include your code in the scope, it gave me an error in the line of goes saying 'Element' (aka '(String, JSON)') is not convertible to '[String:String]'

  • 1

    Oh yes, now I checked in the library what the result of this method is. I edited the answer, see if it now returns correctly.

  • Thanks for your attention, he identified the for now however, this giving the following error in the if Cannot subscript a value of type 'JSON' with an índex of type 'String'

  • So no error however, it does not enter the if if let imagem: String = subJson["imagem"] as? String

  • 1

    What I’m not getting is to know which object this library is represented because I can’t test here, by the documentation it’s also hard to know. But I made another attempt, considering json is a array, as you reported.

  • I am testing with a JSON that has 3 contents in its scope, it is identifying the 3, because it goes 3 times through the for, but what I do not know at the moment and assign the value of json in the vector [String]. I am very lay at SWIFT, I updated the question. At the end of the question based on your answer. It print on the desired values, only I wonder how to assign even.

Show 1 more comment

1


To iterate the 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:

inserir a descrição da imagem aqui

The example code is in this gist playground ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.