Swift HTTP POST 2D array - arrays

The question is: in which format to send this array to remote URL? JSON or as array?
Is it possible to send it as simple array?
What I want to do is, to send 2d array to url. The array looks like following:
[
"deviceID" => "123456789"
"answers" => array(
1=>"a",
2=>"b"
...
)
]
Now a bit of code:
I have the following Dictionary:
var postJSON = [ids[0]:answersArray[0], ids[1]:answersArray[1], ids[2]:answersArray[2]] as Dictionary => [2: B, 1: B, 3: B]
Now, I want to create another Dictionary, like: ["deviceID", "123456789"], later concatenate these two Dictionaries onto one and JSON encode the result array.
How can I realize it?
For the POST I use:
var URL: NSURL = NSURL(string: "http://example.com/en/check-answers")!
var request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
request.HTTPMethod = "POST"
var bodyData = // a JSON encode here
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
{
(response, data, error) in
println(NSString(data: data, encoding: NSUTF8StringEncoding))
}

You can just build a new dictionary using your answers object and the deviceID key/value pair:
let answers = ["a", "b", "c"] // build this any way you want
let device = "123456789"
let payload = ["answers" : answers, "deviceID" : device]
let body = try! NSJSONSerialization.dataWithJSONObject(payload, options: [])
let request = NSMutableURLRequest(URL: URL)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPBody = body
// now issue request
That creates JSON that looks like:
{"answers":["a","b","c"],"deviceID":"123456789"}
If you want to see it as the server gets it, you could have PHP code that takes that and prints it:
<?
$handle = fopen("php://input", "rb");
$raw_post_data = '';
while (!feof($handle)) {
$raw_post_data .= fread($handle, 8192);
}
fclose($handle);
$body = json_decode($raw_post_data, true);
header("Content-Type: text/plain");
print_r($body);
?>
It looks like:
Array
(
[answers] => Array
(
[0] => a
[1] => b
[2] => c
)
[deviceID] => 123456789
)
Obviously, I wouldn't generally do print_r or var_dump, but rather would build a JSON response (set application/json for the Content-Type header, use json_encode to build response, etc.), but I wanted to show the associative array in more of a native PHP syntax. But hopefully this illustrates the idea, nonetheless.
By the way, if you wanted to really represent answers, itself, as a dictionary, you can do that, too, e.g.:
let answers = ["1" : "a", "2" : "b", "3" : "c"]
Just notice that the keys, 1, 2, and 3 must be strings, not numbers (it's a constraint of JSON, not of dictionaries in Swift).
Anyway, the resulting JSON would look like
{"answers":{"2":"b","1":"a","3":"c"},"deviceID":"123456789"}
And in PHP, that would look like:
Array
(
[answers] => Array
(
[2] => b
[1] => a
[3] => c
)
[device] => 123456789
)

Related

How to post Array of Dictionaries, which is stored in NSArray var in swift?

I have JSON response of type (Array of dictionaries) coming of POST request using Alamofire
"emergency_contacts":[ (
{
"first_name" = bxbx;
"last_name" = yahd;
},
{
"first_name" = Bills;
"last_name" = yah;
}
)]
I'm saving response like this and Im getting it successfully
let tempArray = userData["emergency_contacts"] as! NSArray
LoginSingleton.shared.usersList= tempArray
Now I want to POST this Array of Dictionaries in another request How do I do that?Im post other parameters too so please suggest me some method using multipart.Thanks
This is how I'm trying
multipartFormData.append("\(LoginSingleton.shared.usersList)".data(using: .utf8, allowLossyConversion: false)!, withName: "emergency_contacts")
You probably need to convert your array of dictionaries to data using data(withJSONObject:options:) function of JSONSerialization like this:
do {
let data = try JSONSerialization.data(withJSONObject: LoginSingleton.shared.usersList)
multipartFormData.append(data, withName: "emergency_contacts")
} catch {
// Something whent srong with serialization proccess
print(error)
}

Ruby: integrate a ruby key/value-hash in an existing JSON string

The JSON-String:
jsonString = {"string1" => {"test1" => "test2"}}
results (with JSON.pretty_generate) in a pretty printed:
{
"string1":
{
"test1": "test2"
}
}
But when I try to add all elements of two arrays into this JSON-String
keys = [:key0, :key1]
values = [:value0, :value1]
my_hash = Hash[keys.zip values]
jsonString = {"string1" => {"test1" => "test2", my_hash}}
I'm always getting a:
syntax error, unexpected '}', expecting =>
jsonString = {"string1" => {"test1" => "test2", my_hash}}
I would have expected a behavior like this:
jsonString = {"string1" => {"test1" => "test2", keys[0] => values[0], keys[1] => values[1]}}
Output:
{
"string1":
{
"test1": "test2",
"key0": "value0",
"key1": "value1"
}
}
Is there a way to this using the hash-mechanism?
Thanks a lot.
Try jsonString.merge(my_hash) ?
My understanding is that the variable called jsonString is actually a hash, not a json string. If you wanted to convert that hash to a real JSON string, you could import the json module (using require 'json') than call jsonStrong.to_json, but once you've converted the hash to a string it's more difficult to had other hashes to it. It's best to add all the hashes together, then convert the result to json.

POST request with string parameters and array

I want to make a POST request and pass some parameters.
The parameters I want to pass is:
- Item : String
- Length : String
- Names : String Array
- Age : String
Today I´m doing this
var URL: NSURL = NSURL(string: "URL")!
var request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
request.HTTPMethod = "POST"
request.HTTPBody = // parameters here?
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {
(response, data, error) in
println(NSString(data: data, encoding: NSUTF8StringEncoding))
}
Can anyone provide help of how to pass the above parameters in my request? I´m not quite sure how to do that.
The thing is that the HTTPBody expect a NSData object, so you can create Dictionary with the data you need as #dsk explain in this answer and then convert it to JSON to pass as parameters using the dataWithJSONObject function, like in the following way:
var request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
var values: [String: AnyObject] = [:]
values["item"] = "value"
values["length"] = "value"
values["names"] = ["value1", "value2"]
values["age"] = "value"
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(values, options: [])
Nevertheless I strongly recommend you use Alamofire to handle all the networking process more easily.
I hope this help you.
Add a variable for your parameters:
var params: [String: AnyObject] = [:]
params["item"] = "YOUR_STRING"
params["length"] = "YOUR_STRING"
params["names"] = ["YOUR_STRING1", "YOUR_STRING2"]
params["age"] = "YOUR_STRING"
Assuming the POST is a JSON request, add them to the HTTPBody as such:
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: [])

Compiling Swift source files hangs on large array reduce-combine + expressions

In my tests I'm used to write Strings in arrays in different lines like
let jsonString = ["{"
,"\"url\": \"http://localhost:8090/rest/api/3\","
, "\"id\": \"3\","
, "\"description\": \"A test that needs to be done.\","
, "\"name\": \"Test\","
, "\"subtest\": false,"
, "\"avatar\": 1"
,"}"].reduce("", combine: +)
That works fine, still my array get 145 lines for a large test json string.
With 145 lines (or maybe less, didn't tried it line by line) the build task hangs while "Compiling Swift source files".
First, that is a bit crazy. 30 lines are ok, 145 not? What?
Second, what is a better solution to write a String in multiple lines in Swift? - I don't want to load a json and parse it from an external file.
This is probably because of type inference.
Try giving an explicit [String] type to an array variable to help the compiler figure it out, then apply reduce to the variable.
let arrayOfStrings: [String] = ["{"
,"\"url\": \"http://localhost:8090/rest/api/3\","
, "\"id\": \"3\","
, "\"description\": \"A test that needs to be done.\","
, "\"name\": \"Test\","
, "\"subtest\": false,"
, "\"avatar\": 1"
,"}"] // etc
let jsonString = arrayOfStrings.reduce("", combine: +)
Anyway, to create JSON you should make a dictionary then serialize it with NSJSONSerialization, this is less error prone:
Swift 2
do {
// Create a dictionary.
let dict = ["url": "http://localhost:8090/rest/api/3", "id": "3"] // etc
// Encode it to JSON data.
let jsonData = try NSJSONSerialization.dataWithJSONObject(dict, options: [])
// Get the object back.
if let jsonObject = try NSJSONSerialization.JSONObjectWithData(jsonData, options: []) as? [String:String] {
print(jsonObject)
}
// Get it as a String.
if let jsonString = String(data: jsonData, encoding: NSUTF8StringEncoding) {
print(jsonString)
}
} catch let error as NSError {
print(error)
}
Swift 3
do {
// Create a dictionary.
let dict = ["url": "http://localhost:8090/rest/api/3", "id": "3"] // etc
// Encode it to JSON data.
let jsonData = try JSONSerialization.data(withJSONObject: dict, options: [])
// Get the object back.
if let jsonObject = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String:String] {
print(jsonObject)
}
// Get it as a String.
if let jsonString = String(data: jsonData, encoding: String.Encoding.utf8) {
print(jsonString)
}
} catch let error as NSError {
print(error)
}

How to parse through FB Graph API friends list array for specific value, ID?

I successfully loaded the friends array containing more arrays into a variable. But how do I iterate through it to take only the id's out?
I used:
$friends = $facebook->api('/me/friends/');
It returns a multidimensional array like so:
array(1) { ["name"] => "Username" ["id"] => "User ID #"}
array(2) { ["name"] => "Username" ["id"] => "User ID #"}
...and so on...
Any help would be appreciated! Thanks.
Results of Graph API almost always contain data property which is contain all the response data, to get only the friends ids you can look over it in such way:
// If all you need is users ids, specify it in fields url argument
$friends = $facebook->api('/me/friends/?fields=id');
$data = $friends['response'];
$friendsIds = array();
for ($data as $user){
$friendsIds[] = $user['id'];
}
Try:
$yourIdArr = array();
foreach($yourFriendArray as $key => $val) {
if("id" == $key) {
array_push($yourIdArr, $val);
}
}

Resources