-1

I've read close to a 100 questions on SO but I still haven't been able to figure out how to create a simple JSON object from a set of simple strings. Every attempt ends with unresolved reference.

Eg:

Key1 : value1

Key2 : value2

Key3 : value3

And I want to create a JSON object from the above using Objective C. Thank you.

Edit: This is how I've created the dictionary.

NSDictionary *jsonDict = [NSDictionary dictionaryWithObjectsAndKeys:
                        @"key1", @"val1",
                        @"key2", @"val2",
                        @"key3", @"val3",
                        nil];
  • Create an NSDictionary containing the data and run it through NSJSONSerializaion. – Hot Licks Feb 12 '15 at 12:54
  • `NSString` -> data -> `NSJSONSerialization`. How does your string set exactly look like? – Maciej Oczko Feb 12 '15 at 12:55
  • Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. – Hot Licks Feb 12 '15 at 12:55
  • You should look at [this][1] SO question. [1]: http://stackoverflow.com/questions/6368867/generate-json-string-from-nsdictionary – David Hoelzer Feb 12 '15 at 12:55
  • I don't have a string as of now. I'm looking for any example that just lets me enter key-value pairs and end up with a json object. Also, I've managed to create a NSDictionary but converting it to a JSON object seems impossible. I'm trying this `NSString *json_str = [NSString stringFromDictionary:jsonDict];` but stringFromDictionary cannot be found. –  Feb 12 '15 at 12:58
  • Sigh!! `stringFromDictionary` is an *old* 3rd party JSON conversion tool, and it's only available if you've installed the corresponding category. Look at the documentation for NSJSONSerialization. Please. – Hot Licks Feb 12 '15 at 13:00
  • I thought it was a default library. There was no mention of it being a 3rd party tool on the question page. –  Feb 12 '15 at 13:01
  • @DavidHoelzer doesn't show how to make it out of new strings. –  Feb 12 '15 at 13:07
  • What he's put in the question is a dictionary even though strings are mentioned in the title. @john – David Hoelzer Feb 12 '15 at 13:08

1 Answers1

2
NSDictionary *jsonDict = [NSDictionary dictionaryWithObjectsAndKeys:
                    @"key1", @"val1",
                    @"key2", @"val2",
                    @"key3", @"val3",
                    nil];
NSError *error;
NSData *jsonData =[NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:&error];

This data will json format

Mrugesh Tank
  • 3,495
  • 2
  • 29
  • 59