Search code examples
iosobjective-cjsonnsdictionarynsjsonserialization

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}}
  • 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!


Solution

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