I am working on an application and i need to send some data to my server. The data is in json format and more specific the json file looks like this :
{
"eventData": {
"eventDate": "Jun 13, 2012 12:00:00 AM",
"eventLocation": {
"latitude": 43.93838383,
"longitude": -3.46
},
"text": "hjhj",
"imageData": "raw data",
"imageFormat": "JPEG",
"expirationTime": 1339538400000
},
"type": "ELDIARIOMONTANES",
"title": "accIDENTE"
}
So i have tried to hardcode the data in my json file and everything works ok. Now what i am trying to do is to fill my json file , using variables so everything can work automatcally when data changes. What would a good approach be for that?? Some sample code would be highly appreciated as i am very new to obj-c. Thanks for ur time! :D
EDIT
Ok so an NSDictionary seems a nice way to go.
But how can i create a dictionary to look like the json format?? I ve only used dictionaries like this :
NSArray *keys = [NSArray arrayWithObjects:#"eventDate", #"eventLocation", #"latitude" nil];
NSArray *objects = [NSArray arrayWithObjects:#"object1", #"object2", #"object3", nil];
dictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
For the langitude and longitude for example it is a pair of key and value but for the rest??
All you need is a NSDictionary containing your keys and values. Since iOS5, you can proceed with the following code
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:myDictionary
options:NSJSONWritingPrettyPrinted
error:&error];
if (!jsonData) {
NSLog(#"Got an error: %#", error);
} else {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
// ...
}
I have used this library . It is very simple and useful. And for tutorial check this site.
Related
I want to add a json data to HTTPBody request for an iOS app.
I am using objective c.
So I decided to use NSMutableDictionary to convert it to JSON
#property NSMutableDictionary* project;
Parameters:
project (required): a hash of the project attributes, including:
name (required): the project name
identifier (required): the project identifier
description
This is the JSON format when adding data as a raw:
If I want the JSON to look like this, do I have to create NSMutableDictionary object and have another NSMutableDictionary object inside it with the key name #"project"?
{
"project": {
"name": "",
"identifier": "example",
"description": "",
}
}
I tried to have only one NSMutableDictionary
Here is my code:
[self.project setObject:self.projectName.text forKey:#"name"];
[self.project setObject:self.projectDescription.text forKey:#"description"];
[self.project setObject:self.projectIdentifier.text forKey:#"identifier"];
Here is how to convert it to JSON:
NSData *data = [NSJSONSerialization dataWithJSONObject:project options:NSJSONWritingPrettyPrinted error:nil];
NSString* jsonString = [[NSString alloc]initWithData: data
encoding: NSUTF8StringEncoding ];
NSData* anotherdataobj = jsonString;
[request setHTTPBody:anotherdataobj];
I convert it to NSData again because HTTPBody accept NSData for the parameter.
To be clear:
1- do i have to create NSMutableDictionary for project and add NSMutableDictionary projectdetails as a value for for its key #"project"
2- Do I have to convert the string into NSData again to pass it for the HTTPBody?
Correct me if i'm wrong here?
You will definitely need another dictionary inside the first one. Whether you use a mutable version or a literal is up to you.
Note: you probably want to use the newer and much more readable Objective-C syntax.
Option 1:
NSMutableDictionary *object = [NSMutableDictionary dictionary];
NSMutableDictionary *project = [NSMutableDictionary dictionary];
project[#"name"] = whatever;
project[#"identifier"] = whateverElse;
project[#"description"] = stillSomethingElse;
object[#"project"] = project;
Option 2:
NSDictionary *object =
#{
#"project":
#{
#"name": whatever,
#"identifier": whateverElse,
#"description": stillSomethingElse,
}
};
NSJSONSerialization dataWithJSONObject:options:error: already returns an NSData object? Why would you need to convert it again? Also, you certainly don't want to cast an NSData object to an NSString, they're two completely different objects.
I have a json file that looks like this:
{
"data":
{
"level": [
{
//bunch of stuff
}
]
}
}
Now I want to convert that into a array of levels that I can access. If I take away the {"data: part, then I can use this:
NSData *allLevelsData = [[NSData alloc] initWithContentsOfFile:fileLoc];
NSError *error = nil;
NSMutableDictionary *allLevels = [NSJSONSerialization JSONObjectWithData:allLevelsData options:kNilOptions error:&error];
if(!error){
NSMutableArray *level = allLevels[#"level"];
for (NSMutableDictionary *aLevel in level){
//do stuff with the level...
But I have to have the {"data: as part of the file, and I can't figure out how to get a NSData object out of the existing NSData object. Any ideas?
Don't you need to pull the level NSArray out of the data NSDictionary first?
NSData *allLevelsData = [[NSData alloc] initWithContentsOfFile:fileLoc];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:allLevelsData options:kNilOptions error:&error];
if(!error){
NSArray *levels = dataDictionary[#"data"][#"level"];
for (NSDictionary *aLevel in levels){
//do stuff with the level...
You won't get mutable objects back by default and declaring the variables as mutable doesn't make them so. Take a mutableCopy of the result instead (assuming you really do need mutability).
Why are you trying to prune ahead of time? If you decode the original JSON, you'll be able to extract the level array from the data dict in the decoded dict.
It's not clear what else you're trying to accomplish or why you are going the path you ask about. Note, this doesn't necessarily mean your path is wrong, just that without a clearer indication of what goal you're really trying to accomplish or what you've actually tried (and errored/failed, along with how it failed), you're likely only to get vague/general answers like this.
This is my first native iOS app, so please bear with..
How would I construct this json data in a NSDictionary (I would guess thats how I would do it) so I cand make it part of my request body.
{
"Properties":{
"Description":"String content",
"Domain":"String content",
"GroupID":"String content",
...
},
"Foo":{....},
}
Yes, use a dictionary, created using literals or code.
NSDictionary* jsonDict = #{#"Properties":#{#"Description":#"String content",#"Domain":#"String content",#"GroupID":#"String content",},#"Foo":{....},}
Convert the dictionary into JSON data ready for posting.
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:&error];
I'm working on an application in iOS that gets some of its information from a server using JSON. The server's not online yet, so I'm trying to use what the developers working on the server have given me as sample code to build from. I thought the easiest way to do this would be storing the JSON response in a string and using NSJSONSerialization.
The code I'm trying looks as follows:
NSString * JSONString = #"{\"firstName\":\"John\", \"lastName\": \"Smith\", \"age\": 25, \"address\": {\"streetAddress\": \"21 2nd Street\",\"city\": \"New York\", \"state\": \"NY\",\"postalCode\": \"10021\"},}";
bool valid = [NSJSONSerialization isValidJSONObject:JSONString];
if (valid) {
NSLog(#"Valid JSON");
} else {
NSLog(#"Invalid JSON");
}
Which always logs, "Invalid JSON."
All of my research has given resources about how to get the data from a server, but nothing about testing before the server is available. Any ideas?
Two issues. First, your JSON string has an extra comma. It should be:
NSString *jsonString = #"{\"firstName\":\"John\", \"lastName\": \"Smith\", \"age\": 25, \"address\": {\"streetAddress\": \"21 2nd Street\",\"city\": \"New York\", \"state\": \"NY\",\"postalCode\": \"10021\"}}";
Second, though, your original code has a false negative. A string will always fail isValidJSONObject. That method is not for validating a JSON string. If you want to use isValidJSONObject, you should pass it a NSDictionary, e.g.:
NSDictionary* jsonDictionary = #{
#"firstName" : #"John",
#"lastName" : #"Smith",
#"age" : #(25),
#"address" : #{
#"streetAddress": #"21 2nd Street",
#"city" : #"New York",
#"state" : #"NY",
#"postalCode" : #"10021"
}
};
BOOL valid = [NSJSONSerialization isValidJSONObject:jsonDictionary];
if (valid) {
NSLog(#"Valid JSON");
} else {
NSLog(#"Invalid JSON");
}
So, the best way to create a JSON string is to create the dictionary like above, and then invoke dataWithJSONObject. I generally would advise against writing a JSON string manually, because you can always introduce typos like your extra comma. I always build a JSON string from a NSDictionary like this, because you never have to worry about whether the string is well formed or not. NSJSONSerialization takes care of the hard work of formatting the string properly:
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary
options:0
error:&error];
if (error)
NSLog(#"dataWithJSONObject error: %#", error);
NSString *jsonString = [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding]);
NSLog(#"JSON string is: %#", jsonString);
That yields:
{"age":25,"lastName":"Smith","firstName":"John","address":{"streetAddress":"21 2nd Street","state":"NY","city":"New York","postalCode":"10021"}}
Or, if you use the NSJSONWritingPrettyPrinted option to dataWithJSONObject:
{
"age" : 25,
"lastName" : "Smith",
"firstName" : "John",
"address" : {
"streetAddress" : "21 2nd Street",
"state" : "NY",
"city" : "New York",
"postalCode" : "10021"
}
}
I test by keeping a file in my resources say, test.json. You can open it with the following code:
NSString *path = [NSBundle.mainBundle pathForResource:#"test.json" ofType:#"json"];
NSError *error = nil;
NSString *fileContents = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:&error];
Then call the method to convert to a JSON object. The test file will be more readable than what you have above. Hope this helps!
I have recently started Application development on MAC OS 10.6, I am trying to modify a "key/value" pair in a local JSON file on my MAC machine using SBJSON. I have successfully read the value of a key, but I am not able to get that how to modify the value of a key and synchronize this to the JSON file. Lets suppose, I have a following JSON Data int o a local file:
{
"name": {
"fName":"John",
"lName":"Doe"
}
}
And i want to change the value of "fName" to something else, like Robert.
I have tried alot searching about it, but got no clue... Can anyone help me.
I am using SBJSON Framework!
Code:
NSString *filePath = #"/Users/dev/Desktop/SQLiteFile/myJSON2.json";
NSData *myData = [NSData dataWithContentsOfFile:filePath];
NSString *responseString = [[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding];
NSLog(#"FILE CONTENT : %#", responseString);
SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
NSDictionary * dictionary = (NSDictionary*)[jsonParser objectWithString:responseString error:NULL];
[dictionary setObject:#"Robert" forKey:#"fName"];
//
// Code for writing this change into the file, which i needed.
//
[jsonParser release];
You want a mutable deep copy of your dictionary. Then you'll be able to modify it.