AlexR
AlexR

Reputation: 5634

Converting a Dictionary with a value of [NSNull null] to JSON

I am trying to use this code:

NSDictionary *innerMessage 
      = @{@"nonce":[NSNumber numberWithInteger:nonce],
          @"payload":@{@"login": [NSNull null]}};

NSError * err;
NSData * innerMessageData = [NSJSONSerialization 
     dataWithJSONObject:innerMessage options:0  
     error:&err];

to create a JSON object with the following structure:

{
    "apikey": "e418f5b4a15608b78185540ef583b9fc",
    "signature": "FN6/9dnMfLh3wZj+cAFr82HcSvmwuniMQqUlRxSQ9WxRqFpYrjY2xlvDzLC5+qSZAHts8R7KR7HbjiI3SzVxHg==",
    "message":{
        "nonce": 12, 
        "payload": {
            "Login": {}
        }
    }
}

However, this is the actual result which I get:

{"nonce":1398350092512,"payload":{"login":null}}

Thank you!

Upvotes: 2

Views: 1225

Answers (3)

Suhit Patil
Suhit Patil

Reputation: 12023

Change code to

NSDictionary *innerMessage = @{
                                   @"nonce":@12,
                                   @"payload":@{@"login": @{}}
                              };

NSError * err;
NSData * innerMessageData = [NSJSONSerialization 
     dataWithJSONObject:innerMessage options:0  
     error:&err];

This will create the desired response

{
    nonce = 12,
    payload =  {
        login = {}
    },
}

Upvotes: 1

bdesham
bdesham

Reputation: 16089

null is a perfectly valid JSON value; what were you expecting? How should NSJSONSerialization know that you wanted [NSNull null] to be converted to an empty object? (For that matter, why wouldn’t nulls be converted to an empty array, an empty list, or numeric zero?)

The solution is to process your innerMessage before you serialize it, replacing any instances of [NSNull null] with @{} (or, equivalently, [NSDictionary dictionary]).

Upvotes: 0

Vatev
Vatev

Reputation: 7590

NSNull is suppose to become null in the JSON.

If you want an empty dictionary in the JSON ({}) you should use an empty dictionary - @{}.

Upvotes: 3

Related Questions