Adding a JSON blob to a JSON request in iOS - ios

I need to be able to create a JSON object (I'm using the built in classes in iOS 5).
The JSON that should be sent is this:
{"request_type":"<the request type (a string)>" "security_level":<the security level (an int)> "device_type":"<android or ios (a string)" "version":<the app version (android, ios on different version schemes) (a float)> "email":<the email address of the user sending the request (a string)> "blob":{<the contents of the actual request, encrypted/encoded according to the security level (a map)>}
My problem is with the last portion, a "blob"
Which is basically just another JSON object, i.e.
{"display_name":"Jack Bower", "email":"jackb#gmail.com", "password":"roflcopter"}
(Let's forget the password is in plaintext)
I can create everything using NSDictionary,
I just don't know how to add the last part.
My guess is create the first request using NSDictionary.
Then create the second blob request using another NSDictionary.
And then just add that second blob NSDictionary as a object back to the initial NSDictionary.
Will NSJSONSerialization understand what I'm trying to do?

Ok I think it's 5am and I'm just being really stupid:
here's the answer:
NSDictionary *blobData = [NSDictionary dictionaryWithObjectsAndKeys:
#"email",userEmail,
#"password",userPassword,
nil];
NSString *blobString = [[NSString alloc]
initWithData:[NSJSONSerialization dataWithJSONObject:blobData options:kNilOptions error:&error]
encoding:NSUTF8StringEncoding];
NSDictionary *requestData = [NSDictionary dictionaryWithObjectsAndKeys:
#"login",#"request_type",
0,#"security_level",
#"ios",#"device_type",
#"blob",blobString,
nil];
NSData *JSONRequestData = NULL;
if ([NSJSONSerialization isValidJSONObject:requestData]) {
NSData *JSONRequestData = [NSJSONSerialization dataWithJSONObject:requestData options:kNilOptions error:&error];
}
else NSLog(#"requestData was not a proper JSON object");

Related

Html tag in json object

I have started on a new project. It is the first time that I see the following webservice output. This following json object text contains html tags.
I wonder how do you parse it to string or how do you know where the paragraph starts? or do you think that I should contact web service developer guy to fix this?
You can use
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData: responseData options: NSJSONReadingMutableContainers error: &e];
To turn the data into dictionary. Then you can access the value of "icerik" by traversing the dictionary tree with NSArray/NSDictionary. For your case example,
first nest is a dictionary of key "news" with array objects. So you get the the array out of it:
NSArray *newsArray = [JSON objectForKey:#"news"];
Then you get the first news item by getting another dictionary:
NSDictionary *firstNews = [newsArray objectAtIndex:0];
Then you can get icerik:
NSString *icerik = [firstNews objectForKey:#"icerik"];
Once you get the value as string, you need to do some string manipulation on it (many ways to do this)
You can get your html string as
NSDictionary *json = [NSJSONSerialization JSONObjectWithData: responseData options: NSJSONReadingMutableContainers error: &e];
NSString *icerik = json[#"news"][0][#"icerik"];
You can use UIWebView or UITextView to load html string.
NSString *myHTML = [NSString stringWithFormat:#"<html><body>%#</body></html>" ,icerik ];
[yourWebView loadHTMLString:myHTML baseURL:nil];

Send and receive key/value pair using gcdasyncsocket over wifi

I've made an iOS app that receives RSSI values from a BLE Beacon and sends (using GCDAsynSocket) it to a connected MacBook over wifi. My next app on the MacBook receives the RSSI values and saves (using NSOutpuStream class) it in .txt format.
Now, I need to send RSSI values from eight different BLE beacons and their respective MAC address in key/value pairs.
I tried to solve it using NSKeyedArchiver to encode NSDictionary into NSData.
NSData *data = [NSKeyedArchiver archivedDataWithRootObject: NSDictionaryContaningKeyValuePair];
And on the receiver's end (MacBook), I used NSUnarchiver to decode. I am unable to extract the NSDictionary containing key/value (MAC address/RSSI values) pair and store it to the .txt file. Moreover, since NSoutputStrteam write method takes nonnull const uint8_t value, how can I write the Key/value pair in the .txt file?
I use Objective-C and Xcode (7.0).
Thank you.
Got the solution. NSDictionary can be sent using NSJSONSerialization class. At transmitter's end (iOS):
NSDictionary* dictInfo = [NSDictionary dictionaryWithObjectsAndKeys:self.txtInfo.text,#"data", nil];
NSData* dataDict = [NSJSONSerialization dataWithJSONObject:dictInfo options:NSJSONWritingPrettyPrinted error:nil];
[self.socket writeData:dataDict withTimeout:-1.0f tag:0];
At receiver's end (MacBook):
if ([self getSelectedSocket]== sock) {
[_dataBuffer appendData:data];
if ([sock socketAvailableBytes] == 0) {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:_dataBuffer options:NSJSONReadingMutableLeaves error:nil];
DLog("Dictionary Info: %#", dict);
NSString* strInfo = (NSString*)[dict objectForKey:#"data"];
[_dataBuffer setLength:0];
self.txtLogs.stringValue= strInfo;
For further information please visit https://github.com/boobalaninfo/Bonjour-iOS-MAC-Apps.

Pass an array to .net webservice in ios sdk

I like to call the json web service through my iphone app.
I try to pass the array like as follow:
NSArray *keys = [NSArray arrayWithObjects:#"key",nil];
NSArray *objects = [NSArray arrayWithObjects:venueId,nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSString* jsonString = [jsonDictionary JSONRepresentation];
NSLog(#"%#",jsonString);
Call to webservice
SBJSON *json = [SBJSON new];
json.humanReadable = YES;
responseData = [[NSMutableData data] retain];
NSString *service = #"/DerializeDataTable";
NSString *requestString = [NSString stringWithFormat:#"{\"n\":\"%#\"}",jsonString];
NSLog(#"request string:%#",requestString);
Requsted String
{"n":"{"key":["4e78b7f7483bc8fe83ed2bf9","4de248a21520b8ceaabd9197","4f0d502be4b0dd89303e6bde","4f2a79a1e4b0b052a3f37633","500ebf52e4b0edbb8dbc7e9c","4d63a047a45b5481c872032d"]}"}
But can't able to get the response.
I don't know what is the reason.
I don't know the any problem on my side or server side.
You haven't posted the code where you actually send the request off to your web service, so it is going to be hard to help you.
The first thing you should do is isolate whether the problem is with your client (the app) or your server. You can do this by logging the response you get when you send the message - it sounds as if you're getting no response, in which case you might be better off examining your server logs to see if the request ever reaches your server. You might find it useful to use a proxy to actually see the network traffic as it leaves your app.
Looks like you have extra quotes in there. I think you mean:
{"n":{"key": ["4e78b7f7483bc8fe83ed2bf9","4de248a21520b8ceaabd9197","4f0d502be4b0dd89303e6bde","4f2a79a1e4b0b052a3f37633","500ebf52e4b0edbb8dbc7e9c","4d63a047a45b5481c872032d"]}}

Fill NSDictionary with JSON [duplicate]

This question already has answers here:
Decode JSON to NSArray or NSDictionary
(5 answers)
Closed 9 years ago.
Iam new in iOS development .
I want to fill this json
"{
"form_name":"login_form_mobile",
"user_login":"mark wallet",
"password":"123456",
"dispatch":{"auth.login":"Sign in"}
}
"
into a NSDictionary to use it in post for a URL using AFNetworking.
I fill the dictionary like this
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:#"login_form_mobile",#"form_name",#"markwallet",#"user_login",#"123456",#"password",#"{ \" auth.login \" : \" Sign in \" }",#"dispatch", nil];
Now i have two problems
1-The \" in before and after auth.login is shown as it i want to show the Double quotes only.
BTW i tried to make a nested Dictionary this solved the first problem but for the second one problem not.
2-When i run the app. and see how the dictionary is filled it is shown like this
{
dispatch = "{ \" auth.login \" : \" Sign in \" }";
"form_name" = "login_form_mobile";
password = 123456;
"user_login" = markwallet;
}
a-There is equal between the key and its value and i need it : not =
b-some words doesnt have "" like password , 123456 and markwallet . i dont know why
c-Also i dont know why dispatch and it value go in the first.
EDIT:
I used this new code.
NSDictionary *dic = [[NSDictionary alloc]initWithObjectsAndKeys:#"Sign in",#"auth.login", nil];
NSArray *keys = [NSArray arrayWithObjects:#"form_name",#"user_login",#"password",#"dispatch",nil];
NSArray *objects = [NSArray arrayWithObjects:#"login_form_mobile",#"markwalletz",#"123456",dic,nil];
NSMutableDictionary * params1 = [[NSMutableDictionary alloc]init];
params1 = [NSMutableDictionary dictionaryWithObjects:objects forKeys:keys];
But when i see params1 value in the debug
{
dispatch = {
"auth.login" = "Sign in";
};
"form_name" = "login_form_mobile";
password = 123456;
"user_login" = markwalletz; }
And this is differs from the one i need as stated at the top of the question
And when i send a request with this dictionary it replies BAD Request.
Several things you need to understand:
When you NSLog an NSDictionary, it does not display JSON syntax. Yes, it superficially looks like JSON, but, as you noted, not all character strings are quoted (only those with blanks or odd characters get quotes) and an = is used instead of :. This is because it's a description of the NSDictionary object, not a JSON translation.
And, on the other hand, just because stuff looks the same between JSON and an NSDictionary does not make it the same. Your "dispatch":{"auth.login":"Sign in"} entry represents a second NSDictonary as the value of the key "dispatch". You cannot create that second dictionary simply by making the characters look like the JSON/description representation. Rather, you have to (as a separate conceptual step) create that one-element dictionary and then insert it as an object in the outer dictionary.
One place where NSDictionary and JSON are the same is that neither an NSDictionary nor a JSON "object" maintains the order of the key/value pairs it contains. So don't expect to see the values in the same order in one version vs the other.
Look at the NSJSONSerialization class. Methods in this class will convert JSON into the appropriate objects (e.g NSDictionary, NSArray), and vice versa. See the Apple Documentation for details.
Added:
For example:
NSString *jsonString = ... // Whatever your JSON is
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *d = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
What you get is a dictionary, d, that contains all the keys and their values as described in the JSON (assuming the JSON represented a dictionary). JSON data can represent an array of objects too. It's all quite flexible. I suggest reading the references documentation and search here for other examples using NSJSONSerialization. There are surely some good ones.
The "jsonString" variable should be formed like:
NSString *jsonString = #"{\"form_name\":\"login_form_mobile\",\"user_login\":\"mark wallet\",\"password\":\"123456\",\"dispatch\":\{\"auth.login\":\"Sign in\"}}";
Then, using the code above:
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:nil];
NSLog(#"DIC %#",dic);
will output:
DIC {
dispatch = {
"auth.login" = "Sign in";
};
"form_name" = "login_form_mobile";
password = 123456;
"user_login" = "mark wallet";
}
If your json string is in a NSString variable called "jsonString":
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:nil];
So your "dic" variable will have the parsed json.

Issue in parsing NSDictionay into JSON NSData

How do we convert a NSDictionary into JSON data object? I want to send a JSON data to my server. I am using the below code but facing an issue when it comes to NSDictionary containing Array or further NSDictionary in it. This works well with simple key-value pair.
Issue: It fails on the below line and sets the error object. This works fine if I remove arrays and dictionaries from the source myData dictionary.
NSData *aPostBodyData = [NSJSONSerialization dataWithJSONObject:myData options:0 error:&error];
Where myData looks like:
{
URI = "www.google.com";
addOnTestString = "4,3,";
status = (
"In Progress",
Submitted,
Delivered
);
data =
{
URI = "www.test.com";
testString = "43";
status = (
"In Progress",
Submitted,
Delivered
);
}
}
Error trace:
ok i just write a sample code that includes your situation and it works well.
NSArray * myarray=#[#"a",#"b"];
NSMutableDictionary * dict=[[NSMutableDictionary alloc] initWithObjects:#[#"a",myarray] forKeys:#[#"str",#"arr" ]];
NSData * js=[NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
NSString * jsString=[[NSString alloc] initWithData:js encoding:NSUTF8StringEncoding];
NSLog(#"%#",jsString);
probable reasons for you get errors may be;
your myData is not in type NSDictionary or NSArray.
or while adding arrays to dictionary you are missing a point.

Resources