In some cases, in swift, you want a dictionary key to be null, such as when interacting with the server, some parameters must be required to be transmitted regardless of value. However, if you assign nil to the key of the dictionary, the dictionary will remove the key value pair as follows: Var dict1= Dictionary<string,anyobject> () dict1["name"]= "Jack" dict1["Age"]=16 dict1["nickname"]=nil println (DICT1)//"[ Age:16, Name:jack] "Let jsonData1 = Nsjsonserialization.datawithjsonobject (Dict1, Options:
Nsjsonwritingoptions.allzeros, Error:nil)!
Let jsonString1 = NSString (data:jsondata1, encoding:nsutf8stringencoding)! println (JSONSTRING1)//"{" "Age": +, "name": "Jack"} "if the value of the dictionary is null, you can use nsnull so you can achieve the desired effect: Var dict2=dictionary< String,anyobject> () dict2["name"]= "Jack" dict2["Age"]=16 dict2["nickname"]=nsnull () println (DICT2)//[age:16, Nickname: <null>, name:jack] Let jsonData2 = Nsjsonserialization.datawithjsonobject (dict2, Options:
Nsjsonwritingoptions.allzeros, Error:nil)!
Let jsonString2 = NSString (DATA:JSONDATA2, encoding:nsutf8stringencoding)! println (jsonString2)//{"age": +, "nickname": null, "name": "Jack"}