11

I want to set up static dummy data, in JSON, for my app to process. This is purely client-side; I don't want to retrieve anything from the network.

All the questions and answers I've seen so far have NSData* variables storing what's retrieved from network calls and [JSONSerialization JSONObjectWithData: ...] usually acting on data that was not created manually.

Here's an example of what I've tried within xcode.

NSString* jsonData = @" \"things\": [{ \
\"id\": \"someIdentifier12345\", \
\"name\": \"Danny\" \
\"questions\": [ \
    { \
        \"id\": \"questionId1\", \
        \"name\": \"Creating dummy JSON data by hand.\" \
    }, \
    { \
        \"id\": \"questionId2\", \
        \"name\": \"Why no workie?\"
    } \
    ], \
\"websiteWithCoolPeople\": \"http://stackoverflow.com\", \
}]}";

NSError *error;
NSDictionary *parsedJsonData = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];

Attempts like that (and trying to change things, like switching the NSString* to NSData* from that JSON string) have yielded a null parsedJsonData data or exceptions when trying to create that JSON data variable or when trying to parse it.

How do I create dummy JSON data within my own code such that it can be parsed through the normal Foundation classes that parse JSON data?

Danny
  • 3,670
  • 12
  • 36
  • 45
  • 1
    I don't believe JSON can start with a string. Try adding a `{` to the beginning before `"things"`. Afterwards, take your string and use the `[jsonData dataUsingEncoding:NSUTF8StringEncoding]` method, as `NSJSONSerialization` only takes data, not a string :) – anon_dev1234 Mar 27 '13 at 19:02
  • Thanks. I've tried that route before, but you have brought to light that I may have malformed JSON, which is why I can't seem to create the data manually. Care to post a small example of how the JSON should look while I try out the new JSON? If it works, then I'll mark your answer as the answer since people trying to do this might very well have malformed JSON as the problem. – Danny Mar 27 '13 at 19:08
  • 1
    When I need to do this I have a text file containing the json in the app bundle rather than an NSString in code. I think it makes it easier to swap out for your production URLs and should be easier to format too. – James P Mar 27 '13 at 20:15
  • 1
    When you get the string coded, add an NSLog to print it out, and copy/paste into a site like http://json.parser.online.fr/ to syntax-check it. – Hot Licks Mar 27 '13 at 20:31
  • 1
    And the [JSON syntax](http://www.json.org/) is quite simple. You can absorb the basics in 5 minutes, with time left to get coffee. – Hot Licks Mar 27 '13 at 20:32
  • (There are 3rd party JSON packages, like SBJSON, that will accept NSStrings.) – Hot Licks Mar 27 '13 at 20:33

6 Answers6

23

I would save my test json as separate files in the app. The advantage of this is that you can just copy & paste responses from a web service and read them easily without having to convert them to NSDictionaries or escaped strings.

I've correctly formatted your JSON (using jsonlint) and saved it to a file named testData.json in the app bundle.

{"things":
    [{
     "id": "someIdentifier12345",
     "name": "Danny",
     "questions": [
                   {
                   "id": "questionId1",
                   "name": "Creating dummy JSON data by hand."
                   },
                   {
                   "id": "questionId2",
                   "name": "Why no workie?"
                   } 
                   ], 
     "websiteWithCoolPeople": "http://stackoverflow.com" 
     }]
}

Then in order to parse this file in your app you can simply load the file from the bundle directory.

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"testdata" ofType:@"json"];
NSData *jsonData = [[NSData alloc] initWithContentsOfFile:filePath];

NSError *error = nil;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];

NSLog(@"%@", jsonDict);

It would now be pretty easy to extend this to load any number of responses and essentially have a local web service. It then wouldn't be much more work to adapt this to load responses from a remote server.

James P
  • 4,786
  • 2
  • 35
  • 52
4

Try something like this!!

NSDictionary *jsonObject = @{@"id": @"someIdentifier",
                             @"name":@"Danny",
                             @"questions":@[
                                            @{@"id":@"questionId1",
                                              @"name":@"Creating dummy JSON"},
                                            @{@"id":@"questionId2",
                                              @"name":@"Creating dummy JSON"},
                                            @{@"id":@"questionId3",
                                              @"name":@"Creating dummy JSON"}],
                             @"websiteCoolPeople":@"http://stackoverflow.com"};


NSLog(@" JSON = %@",jsonObject); // let's see if is correct

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonObject options:NSJSONWritingPrettyPrinted error:nil];

NSLog(@" JSON DATA \n  %@",[NSString stringWithCString:[jsonData bytes] encoding:NSUTF8StringEncoding]);


//lets make a check

if ([NSJSONSerialization isValidJSONObject:jsonObject] == YES) {

    NSLog(@" ;) \n");
}
else{

    NSLog(@"Epic Fail! \n");

}


//Going back

NSDictionary *parsedJSONObject = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:nil];


NSLog(@"Cool! :  %@",parsedJSONObject);
  • I like that your answer clearly created the JSON with a dictionary and that it used the data related to my original question. In this way, future searchers will find it easy to follow along. – Danny Mar 27 '13 at 20:29
2

first of all

-(void)createJsonData
{
    //your objects for json
    NSArray * objects=@[@"object1",@"object2",@"object3",@"object4"];
    //your keys for json
    NSArray * keys=@[@"key1",@"key2",@"key3",@"key4"];

    //create dictionary to convert json object
    NSDictionary * jsonData=[[NSMutableDictionary alloc] initWithObjects:objects forKeys:keys];


    //convert dictionary to json data
    NSData * json =[NSJSONSerialization dataWithJSONObject:jsonData options:NSJSONWritingPrettyPrinted error:nil];


    //convert json data to string for showing if you create it truely
    NSString * jsonString=[[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];

    NSLog(@"%@",jsonString);
}

this creates a jsonData. another fact is that to create data you should use dataWithJSONObject. and this method accepts NSDictionary or NSArray. NSString is not valid class for this method.

meth
  • 1,887
  • 2
  • 18
  • 33
1

The answer is in creating correctly formed JSON. If your JSON is malformed when you create it manually, then you will just get the blanket "null" value from the serialization. Here are things that drove me crazy because they were small factors until @bgoers mentioned one of them.

  • Ensure that you're including the correct braces ([{}]) and closing them off appropriately. This actually isn't a small factor, but if you're basing your data on documentation (as I was) then you might miss out on copying/pasting one of the curly braces.
  • When copying/pasting what JSON data should look like, ensure that all the characters used -- especially "quotation" marks -- are uniform. It turned out that I was using the fancy opening and closing quotation marks, which were encoded into the documentation, instead of just the " you'd type into xcode.

Once you have your valid JSON, the Foundation classes should work just fine.

Danny
  • 3,670
  • 12
  • 36
  • 45
1
#import "SBJSON.h"

NSDictionary *dictionary = [[NSDictionary alloc] initWithObjects:[NSArray arrayWithObjects:
                                                                      @"2013-03-27",
                                                                      @"2013-04-04",
                                                                      @"2013-03-27",
                                                                      @"0",
                                                                      @"1",
                                                                      @"1",nil]
                                                             forKeys:[NSArray arrayWithObjects:
                                                                      @"startDate",
                                                                      @"endDate",
                                                                      @"selectedDate",
                                                                      @"shadowsOfID",
                                                                      @"appointmentsOfID",
                                                                      @"shadowType",nil]];


   SBJsonWriter *p = [[SBJsonWriter alloc] init];
        NSString *jsonStr = [NSString stringWithFormat:@"%@",[p stringWithObject:dictionary]];

jsonStr now contains the following:

"{\"shadowType\":\"1\",\"startDate\":\"2013-03-27\",\"selectedDate\":\"2013-03-27\",\"endDate\":\"2013-04-04\",\"shadowsOfID\":\"0\",\"appointmentsOfID\":\"1\"}";

Note that: Dictionary can be a plist file in the project.

yunas
  • 4,143
  • 1
  • 32
  • 38
0

go to this link for an online JSON to NSDictionary/NSArray Converter:

https://erkanyildiz.me/lab/jsonhardcode/

use a well formatted json as input, then copy and past the result in your code as a literal NSDictionary *myDict = @{...};

Enrico Cupellini
  • 447
  • 7
  • 14