2

When I NSLog a dictionary output is this:

{
    accounts =     (
                {
            "account_number" = 9000012;
            "account_type" = "Saver Account";
            ato = 0;
            balance = "0.0";
        },
                {
            "account_number" = 9000010;
            "account_type" = "Primary Account";
            ato = 0;
            balance = "100000.0";
        }
    );
}

Now I need same dictionary inside another program (Mocking in my tests). How can I assign this value from copy pasting from console to a NSDictionary?

I tried to make it as NSString as this answer explain

NSString *jsonStr = @" { ({\"account_number\" = 9000012; \"account_type\" = \"Saver Account\"; ato = 0; balance = \"0.0\";});}";
NSData *data = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
return dict;

Converting NSString to NSDictionary / JSON

but this is returning null.

Again I replace = with : and tried

NSString *jsonStr = @" { ({\"account_number\" : 9000012; \"account_type\" : \"Saver Account\"; ato : 0; balance : \"0.0\";});}";

But still not working?

UPDATED

I managed to convert in this way:

NSDictionary *account = @{ @"account_type":@"Account Type XXX",
                           @"account_number":@"Account Number 123" };

NSMutableDictionary *mainDict = [[NSMutableDictionary alloc] init];
[mainDict setValue:@[account] forKey:@"accounts"];

For two arrays:

NSDictionary *account1 = @{ @"account_type":@"Account Type XXX",
                           @"account_number":@"Account Number 123" };

NSDictionary *account2 = @{ @"account_type":@"Account Type YYY",
                           @"account_number":@"Account Number 456" };


NSMutableDictionary *mainDict = [[NSMutableDictionary alloc] init];
[mainDict setValue:@[account1,account2] forKey:@"accounts"];

But @Duncan C claimed this way is not safe!

Community
  • 1
  • 1
Bernard
  • 4,240
  • 18
  • 55
  • 88

3 Answers3

2

Don't do that. The output of NSLog is not in any particular format and is not guaranteed to stay consistent between OS versions. You would have to write a bunch of custom code and it would be fragile and subject to breaking on any OS change.

You should write a function that takes your dictionary and outputs it as pretty JSON. Also write another function the takes JSON as input and returns a dictionary. Then call those functions from the debugger.

EDIT:

I created a Github project that defines an NSDictionary category NSDictionary+JSON

DictionaryToJSON project on Github

If you addd NSDictionary+JSON.h and NSDictionary+JSON.m to your project and #import the header in any file that uses it, you can type a line like this into the debugger:

e [someDictionary jsonString]

That will take someDictionary and convert it to a JSON string. It also escapes any quotes in the string so that you can copy/paste it, and then you can go to your other program (That also has the category included) and type

e dict = [NSDictionary dictionaryFromJSONString: @"<the JSON string>"]

(Where you replace "<the JSON string>" with the actual JSON string you get from the previous debugger command.

Note that in order to be able to copy/paste the JSON from the debugger console and into a debugger command, I had to escape any quotes in the JSON data as \".

Community
  • 1
  • 1
Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • Well not sure about consistency. I am using this for my tests I need to mcok server calla. Actually I managed now to convert but as you said format is going to change! How to print NSDictionary as JSON format? – Bernard Jun 02 '16 at 11:06
  • I already told you. Write a function in your code that takes a dictionary as input and returns JSON data. Call that function from the debugger and output the results to the console. (Yes you can call your program code from the debugger.) – Duncan C Jun 02 '16 at 11:39
  • See the edit to my answer. I created a project that defines a category in NSdictionary to do what you want. – Duncan C Jun 02 '16 at 13:53
0

When you print a dictionary in console, its not printed in JSON format. So you have to convert the dictionary to JSON string and you will be able to return it back to NSDictionary. You can use these helper methods for that (convert object to JSON string, convert it back to object):

+ (NSData *)dataFromJSONObject:(id)object {
    NSError *error = nil;
    NSData *data = [NSJSONSerialization dataWithJSONObject:object options:0 error:&error];

    return data;
}

+ (NSString *)stringFromJSONObject:(id)object {
    NSData *data = [self dataFromJSONObject:object];
    return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}

+ (id)JSONObjectFromData:(NSData *)data {
    NSError *error = nil;
    id object = [NSJSONSerialization JSONObjectWithData:data
                                                options:0
                                                  error:&error];
    if (!object || error != nil) {
    }

    return object;
}

+ (id)JSONObjectFromString:(NSString *)string {
    return [self JSONObjectFromData:[string dataUsingEncoding:NSUTF8StringEncoding]];
}
Hossam Ghareeb
  • 7,063
  • 3
  • 53
  • 64
  • 1
    before printing the dictionary, convert it to JSON using `stringFromJSONObject ` method. This you can use `JSONObjectFromString ` to convert it back to NSDictionary – Hossam Ghareeb Jun 02 '16 at 11:09
  • The printed dictionary is just for testing/debug. Never use it or do anything with it. If you need to use NSDictionary as String, convert it to JSON, so you can deal with it later. – Hossam Ghareeb Jun 02 '16 at 11:10
0

Add a JSON type file in your App bundle and read it programmatically.

Here is how you can do it:

(1) Open TextEdit and create new document.

(2) In that empty document, PASTE the response of the web service. I used Postman to get the response. It was in JSON format. You can take any JSON string (from other project in your case..).

(3) Click Format > Make Plain Text

(4) Save as: "yourFileName.json" enter image description here

(5) Now, just put this json file in your App bundle.

(6) Read content:

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

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

(7) Enjoy :D

NSPratik
  • 4,714
  • 7
  • 51
  • 81