Question

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}}
  • Why is [NSNull null] in my dictionary not being converted to {}?
  • How would I need to change my code to get the correct JSON structure?

Thank you!

Was it helpful?

Solution 2

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 = {}
    },
}

OTHER TIPS

NSNull is suppose to become null in the JSON.

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

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]).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top