HTTP Response String to 2D Swift Array - swift

I am wandering if anyone has done anything similar to this. I make a http request and the response is a two dimensional array, for example,
[["Column1","Column2","Column3","Column4"],["1","2","3","4"]]
I am trying to convert the "text/array" in the http response to a 2D array in Swift. Has anyone done anything like this?
I understand that I can have the http response come back in the JSON format and the use of JSONDecode, but that is not what I want to do in this particular case.

try this:
let responseString = "[[\"Column1\",\"Column2\",\"Column3\",\"Column4\"],[\"1\",\"2\",\"3\",\"4\"]]"
let data = responseString.data(using: .utf8)!
if let output : [[String]] = try! JSONSerialization.jsonObject(with: data, options: []) as? [[String]]{
print(output)
}
output:
[["Column1", "Column2", "Column3", "Column4"], ["1", "2", "3", "4"]]

Related

Conversion of JSON String to Object always returns nil

I'm fairly new to this. Anyway, here we go:
I have JSON data that comes from an API. For the sake of this question, I have simplified it greatly. You can run the following code in a Playground.
import UIKit
struct Book: Codable {
let image: String
}
// this comes from my API
let jsonString = "{ \"image\" = \"someURL\" }"
print(jsonString) // { "image" = "someURL" }
// convert String to Data
let jsonData = jsonString.data(using: .utf8)
// decode data (in my project, I catch the error, of course)
let decoder = JSONDecoder()
let decodingResult = try? decoder.decode(Book.self, from: jsonData!)
print(decodingResult) // nil
As you can see, I'm trying to decode my JSON-String into an Object (my Struct), but the Decoder always returns nil.
Can someone point me in the right direction?
Thank you.
Your current jsonString isn't a proper JSON. Change it to "{ \"image\": \"someURL\" }", and it should work. For more information on JSON syntax, check this manual.

How to convert bytes to swift array

I need to send an array through HTTP to my swift client but I'm not sure how to convert the bytes I've received to a swift array.
I've looked it up on google multiple times with multiple different ways of saying what I'm trying to do but all I'm getting is topics that say "convert byte array to swift string"
AF.request(exampleUrl).response { response in
if let data = response.data, let s = String(data: data, encoding: .utf8) {
debugPrint(s)
let myArray = decodeSomehow(data: data)
debugPrint(myArray[0]) // hooray
}
}
I need to be able to decode arrays sent from my server but my efforts to find the solution to this problem have yielded no results.
btw server is made with firebase functions and is run on Google frontend
and coded with typescript
also to clarify I do not want to take the bytes and put them into an array, I want to decode the bytes into what they originally were on the server aka an array (originally a typescript array but if it is possible to make it a swift array that would be 👌)
The Data class is an advance version of [UInt8]. Normally, working directly with Data class is recommended. If you really want to convert it to [UInt8], simply
let arr = [UInt8](data)
or
let arr = Array(data)
Hope it helps... (Thanks LEO for your best Comment)
let string = "Hello World"
print(Array(string.utf8))
I figured out how to do what I was trying to do...
In the end, I solved my own problem lol
all I needed to do was decode it with swiftyjson
thank you all for your answers
AF.request(exampleUrl).response { response in
if let data = response.data, let s = String(data: data, encoding: .utf8) {
let arr = JSON(data)
debugPrint(arr)
debugPrint(arr[0][0])
debugPrint(s)
}
}
output

Getting mySql data from url in swift 3 - again

I have asked this seemingly very simple and straight forward question a few times now, never got a solution.
I have a url to obtain mySql data
// 1. get url
let url = URL(string:"http://www.mobwebplanet.com/phpWebService/sample.php")
// 2. Fetch data from url
let data = try? Data(contentsOf: url!)
//playground Output is: 102 bytes. So obviously xcode gets the response data from the URL.
Then I move on to extracting the data:
//3. Create a dictionary from data:
let urlDict = try? JSONSerialization.jsonObject(with: data!, options: [])
// playground Output is: [["Latitude": "37.331741", "Address": "1 Infinite Loop Cupertino, CA", "Name": "Apple", "Longitude": "-122"]]
print(urlDict!)
// playground Output is: "(\n {\n Address = "1 Infinite Loop Cupertino, CA";\n Latitude = "37.331741";\n Longitude = "-122";\n Name = Apple;\n }\n)\n"
My understanding is urlDict is of a Any type. Am I correct?
My biggest question is how can I (cast or convet) urlDict so that I can access the value using key=>value? Like this:
urlDict!["Address"] Outputs "1 Infinite Loop Cupertino, CA"
urlDict!["Latitude"] Outputs "37.331741"...
I am a newbie to Swift so I am doing this as an exercise, any help will be greatly appreciated.
Your JSON response returns an Array of Dictionary objects. So you just need to cast correctly.
let urlString = "http://www.mobwebplanet.com/phpWebService/sample.php"
let url = URL(string: urlString)!
let data = try? Data(contentsOf: url)
if let json = try? JSONSerialization.jsonObject(with: data!, options: []) as? [[String:Any]] {
for location in json! {
print(location["Longitude"])
print(location["Latitude"])
print(location["Address"])
}
}
Output:
Optional(-122)
Optional(37.331741)
Optional(1 Infinite Loop Cupertino, CA)

Convert string representation of JSON to JSON

I have an odd question.
I have a string named string, {"reply": "", "emoji": ":)", "time": "3"}
Now obviously because this is a string, I cannot access it with string["time"].
I need to convert it to an array (or JSON), but I cannot figure out how.
I tried SwiftyJSON
let b = JSON(string)
print(b["comment"]) #"null\n"
I tried JSONSerialisation, but that seemingly failed as well.
Any help would be appreciated.
I am using Alamofire to retrieve the JSON, when I use .responseString, it contains everything, but .responseJSON is empty, and I don't know why.
Here's a quick-and-dirty solution with JSONSerialization that should get your started:
let string = "{\"reply\": \"\", \"emoji\": \":)\", \"time\": \"3\"}"
let json = try! JSONSerialization.jsonObject(with: string.data(using: .utf8)!, options: .allowFragments) as! [String: String]
print(json["time"])
Your actual code should have more error checking, of course.

How to make an HTTP GET Request with Parameters. SwiftyJSON Swift

Below mentioned snippet is working just fine. It queries JSON data. I just want to know how can I pass parameters with this.
let filePath = NSURL(string: "http://localhost:2403/postedjob")
let jsonData = NSData(contentsOfURL:filePath!)
let json = JSON(data: jsonData!, options: NSJSONReadingOptions.AllowFragments, error: nil)
I want to pass this parameters:
let params = ["$limit": 2, "$sort": ["id":"+1"]] as Dictionary<String, AnyObject>
Alamofire may be a good option for you to pass the parameters.
https://github.com/Alamofire/Alamofire
For a GET request pass parameters in the query string (the part after the "?" mark).
For a POST request parameters can be sent in the body in a number of ways. Raw data, form data and JSON among other methods.
Of course the server has to match the method used.