Creating a json object dynamically - ios

I have to make json request of following type.
{
"documents": [
{
"file_size": 48597,
"file_name": "pisa-en.pdf",
"file_content": "base64String"
}
]
}
Following is the way how im creating the json.
NSString *json = [NSString stringWithFormat:#"{\"documents\": [ { \"file_size\": %#, \"file_name\": %#\", \"file_content\": \"%#\" } ]}",_imageSizeArray[0],_imageNameArray[0],_baseArray[0]];
but the problem is that, the documents array may even contain more than one json object within it. If thats the case How can i create a jsonobject dynamically and embed it within documents array?

You have to take Array and add document object in that array
than at request time you have to convert your array to json string by following code
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:myArray options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

Related

Escaped double-quotes appear in string during debugging

I have a dictionary and I need to generate a JSON string by using NSMutableArray. Here is my code:
NSDictionary *dict = #{
#"From":From,
#"To":To,
#"DepartureDate":DepartureDate,
};
[FinalArray addObject:dict];
Then I generate the JSON String like this:
NSError *error;
NSData * JSONData = [NSJSONSerialization dataWithJSONObject:FinalArray
options:kNilOptions
error:&error];
NSString *jsonString = [[NSString alloc] initWithData:JSONData encoding:NSUTF8StringEncoding];
NSLog(#"jsonData=%#", jsonString);
Now output is on NSLog like this:
[
{
"From": "city",
"To": "city",
"DepartureDate": "20160301"
}
]
But while I'm debugging, at a breakpoint, the string appears with escaped double-quotes:
"[{\"From\":\"city\",\"To\":\"city\",\"DepartureDate\":\"20160301\"}]"
Why is that?
That's a stringified json object. My guess is that to allow the json to be shown in the console it's stringified, adding the escaped quotes. In your runtime the backslashes don't exist, they are only there to correctly display the json in the console.

How to parse JSON data from textual file in Objective-C

I know, JSON parsing questions are asked over and over again, but still I can't find any answer to this one.
I've been trying to read and parse a textual JSON file using NSJSONSerialization to no avail.
I've tried using the same JSON data from a NSString and it did work.
Here's the code:
NSError *error;
NSString *jsonString1 = [NSString stringWithContentsOfFile:jsonFilePath
encoding:NSUTF8StringEncoding
error:&error];
NSData *jsonData1 = [jsonString1 dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonObject1 = [NSJSONSerialization JSONObjectWithData:jsonData1
options:0
error:&error];
NSString *jsonString2 = #"{\"key\":\"value\"}";
NSData *jsonData2 = [jsonString2 dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonObject2 = [NSJSONSerialization JSONObjectWithData:jsonData2
options:0
error:&error];
- The text file contains one line: {"key":"value"}
- jsonString1 = #"{"key":"value"}"
- jsonString2 = #"{\"key\":\"value\"}"
- jsonData1 is 23 bytes in size
- jsonData2 is 15 bytes in size
- jsonObject1 is nil and I get error code 3840
- jsonObject2 is a valid dictionary
Seems like the problem is with reading the file, since the NSStrings and NSDatas differ, but what am I doing wrong here and how can I fix it?
Most likely you file contains some unprintable characters (e.g. \0) that trigger the failure. Printing the error message will tell you at what position the first invalid characters occurs.
For example, try printing "{\"key\":\u{0000}\"value\"}" and you'll seem to get a valid JSON, however decoding it fails.
I always do a check on the return value when doing anything with NSUTF8StringEncoding and if nil, then try NSASCIIStringEncoding:
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
if (jsonString == nil) {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSASCIIStringEncoding];
}
return jsonString;

Converting NSString to proper JSON format

Converting NSString to proper JSON format..
NSString *input_json = [NSString stringWithFormat:#"{\"id\":\"%#\",\"seconds\":\"%d\",\"buttons\": \"%#\"}", reco_id, interactionTime, json_Buttons];
Here json_Button is in json format converted from nsdictionary..
My input_json result is:
{"id":"119","seconds":"10","buttons": "{
"update" : "2",
"scan" : "4"
}"}
It is not in a proper JSON format. key buttons contain "{}" I want to remove these quotes.
Expected Result is:
{
"id": "119",
"seconds": "10",
"buttons": {
"update": "2",
"scan": "4"
}
}
You are going about this all wrong. First, create an NSDictionary that contains all of the data you want converted to JSON. Then use NSJSONSerialization to properly convert the dictionary to JSON.
Something like this will work:
NSDictionary *dictionary = #{ #"id" : reco_id, #"seconds" : #(interactionTime), #"buttons" : json_Buttons };
NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
if (data) {
NSString *jsonString = [[NSString alloc] intWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"JSON: %#", jsonString);
} else {
NSLog(#"Unable to convert dictionary to JSON: %#", error);
}
It's a bad idea to try to build JSON strings manually. Use the NSJSONSerialization class. That makes it easy. Create your dictionary, then call dataWithJSONObject:options:error:.
If you use options: NSJSONWritingPrettyPrinted it inserts line breaks and whitespace that makes the JSON more readable.
By using that function you get correctly formatted JSON every time, and it's flexible because if you send it a different dictionary you get different JSON.

reading a json object from a website in objective c

I need to separate sub person, name, age, home addr, office addr from below given json object retrieved from a website
{ "person" :
[{"subperson":{"home":{"id":"kljljk"},"name":"person3","age":"18","addr":{"home addr":"ksdjr","office addr":"kjshdg"}}}]}
tried nsjsonserialization,sbjson and touchJSON api's. returns a dictionary in which person is the key and everything else is the value(format of json string specified below the code)
my code:
NSURLRequest *urlreq = [NSURLRequest requestWithURL:url];
NSData *response = [NSURLConnection sendSynchronousRequest:urlreq returningResponse:nil error:nil];
[webviv loadRequest:urlreq];
SBJsonParser *jsonparser = [SBJsonParser new];
NSDictionary *json = [jsonparser objectWithData:response];
NSLog(#"%#\n", json);
for(id key in json)
{
NSLog(#"%#=%#",key,[json objectWithKey: key]);
}
//output is
person = (everythingelse starting with [, can't separate name and other required things)
//using NSJSONSerialization
if ([NSJSONSerialization JSONObjectWithData:response options:0 error:&error])
{
NSLog(#"json");
}
NSData *pTL = [NSJSONSerialization JSONObjectWithData:response options:0 error:&error];
NSLog(#"%#",pTL);
//Output is the same
//for(int i=0;i<[pTL count];i++)
//{
//NSLog(#"%d",i);
//}
//even with for loop the output is the same
Tell your backend guys(the person who wrote this web service) to change "[" as "(" and "]" as")". ( is array { is dictionary. [ is nothing for us we can differentiate it
There is a problem with your JSON structure.
For instance, the following is not a legal JSON string:
"subperson":"home":{"id":"kljljk"}
Try replacing it with the following:
{"person":[{"subperson":{"id":"kljljk","name":"person3","age":"18","addr":{"homeaddr":"ksdjr","office addr":"kjshdg"}}}]}
You can use any kind of online JSON parser tool to verify the JSON structure before continuing to debug your code.
Also you should read a little about JSON syntax here.

NSData to NSString with JSON response

NSData* jsonData is the http response contains JSON data.
NSString* jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"jsonString: %#", jsonString);
I got the result:
{ "result": "\u8aaa" }
What is the proper way to encoding the data to the correct string, not unicode string like "\uxxxx"?
If you convert the JSON data
{ "result" : "\u8aaa" }
to a NSDictionary (e.g. using NSJSONSerialization) and print the dictionary
NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"%#", jsonDict);
then you will get the output
{
result = "\U8aaa";
}
The reason is that the description method of NSDictionary uses "\Unnnn" escape sequences
for all non-ASCII characters. But that is only for display in the console, the dictionary is correct!
If you print the value of the key
NSLog(#"%#", [jsonDict objectForKey:#"result"]);
then you will get the expected output
說
I don't quite understand what the problem is. AFNetworking has given you a valid JSON packet. If you want the above code to output the character instead of the \u… escape sequence, you should coax the server feeding you the result to change its output. But this shouldn't be necessary. What you most likely want to do next is run it through a JSON deserializer…
NSDictionary * data = [NSJSONSerialization JSONObjectWithData:jsonData …];
…and you should get the following dictionary back: #{#"result":#"說"}. Note that the result key holds a string with a single character, which I'm guessing is what you want.
BTW: In future, I suggest you copy-paste output into your question rather than transcribing it by hand. It'll avoid several needless rounds of corrections and confusion.

Resources