How to pass to Array JSON information on Swift

Asked

Viewed 456 times

1

When the result comes from the server I use the following code snippet to receive the result:

if let JSON = response.result.value {
      print("JSON: \(JSON)")
}

And the result of the print is:

[{
  Nome = Tiago;
  Idade = 22;
  Cidade = Minas;
}, {
  Nome = Luisa;
  Idade = 12;
  Cidade = Califórnia;
}]

How can I take this result and place it in an array?

1 answer

2


You can create a String array and receive the json result with it and then use it in another method.

Declare in global scope, this is at the beginning of class: var texto: [String] = []

Then when you go through Json to get the value of each item of an append in it:

Alamofire.request(mutableURLRequest).responseJSON {
  response in
if
  let value: AnyObject = response.result.value {
let json = JSON(value) print(json) for (_, subJson) in json {
  self.texto.addObject(subJson.object)
}
  }
}

  • Where do you get this JSON? since you have not declared it?

  • @Hidecode How you put the tag Alamofire put an example of the request, if you want to test it just add one let url = 'caminhoDaRequisicao' the content that solves your doubt is the array statement and how the json result is inserted into the array within the for

  • I tried to do a for to access the information that is inside the text but does not show me anything. I did it like this for pessoas in self.texto{
 print(pessoas)
 }

  • the problem here I think is that I am receiving an array with arrays inside. I tried to do this let json = JSON(value)
 for (_, subJson) in json {
 self.texto.append(subJson.stringValue) // Inserindo valores no array
 print(self.texto)
 } and the result I got was "", "" "", "" "" "", "" "" "" ""

  • you are using ? https://github.com/SwiftyJSON/SwiftyJSON

  • I am, but for example if I want to do this let listresultados: Array<JSON> = json["list"].arrayValue&#xA; &#xA; for number in listresultados {&#xA; print(number)&#xA; } I can’t because in the result that comes from the server where is actually "list" I have "", hence I am not able to fetch the data you see

  • I got the solution and it was the following Alamofire.request(mutableURLRequest)&#xA; .responseJSON{&#xA; response in&#xA; if let value: AnyObject = response.result.value {&#xA;&#xA; let json = JSON(value)&#xA; print(json)&#xA; for (_, subJson) in json {&#xA; self.texto.addObject(subJson.object)&#xA; }&#xA; }&#xA; }&#xA;

  • @Hidecode Oce only switched to addObject ? the append should work. I edited answer to help someone who may have the same doubt.

Show 3 more comments

Browser other questions tagged

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