简体   繁体   English

连接字典的字符串:语法错误

[英]Concatenate Strings for Dictionary:syntax error

The following code to conditionally concatenate strings for a dictionary seems to work up to the point where I try to place the concatenated result in the dictionary. 下面的代码有条件地将字典中的字符串连接起来的代码似乎可以正常工作,直到我尝试将连接后的结果放入字典中。 Can anyone see the error? 谁能看到错误?

 NSDictionary *jsonDictionary;
        NSString* dictString = @"@\"first\":first,@\"last"
                NSString *dictString2=dictString;
                if (date.length>0&&![date isKindOfClass:[NSNull class]]) {
//only include this key value pair if the value is not missing 
                    dictString2 = [NSString stringWithFormat:@"%@%s", dictString, "@\"date\":date"];

                }

                jsonDictionary = @{dictString2}; //syntax error. Says expected colon but that does not fix anything

The syntax for creating an NSDictionary using object literals is: 使用对象文字创建NSDictionary的语法为:

dictionary = @{key:value}

(and optionally, it can contain multiple key/value pairs separated by commas, but never mind that right now.) (并且可选,它可以包含多个用逗号分隔的键/值对,但现在不必介意。)

Where "key" and "value" are both NSObject s. 其中“键”和“值”都是NSObject

Your line that is throwing the error only contains 1 thing. 您引发错误的行仅包含1个内容。 The contents of a the string in dictString2 has nothing to do with it. dictString2中字符串的内容与它无关。

It looks to me like you are trying to build a JSON string manually. 在我看来,您正在尝试手动构建JSON字符串。 Don't do that. 不要那样做 Use NSJSONSerialization . 使用NSJSONSerialization That class has a method dataWithJSONObject that takes an NSObject as input and returns NSData containing the JSON string. 该类具有dataWithJSONObject方法,该方法将NSObject用作输入并返回包含JSON字符串的NSData That's how you should be creating JSON output. 那就是您应该如何创建JSON输出。

Creating an NSDictionary with values that may be null: 创建一个NSDictionary,其值可以为null:

NSDictionary *dict = @{
                       @"key" : value ?: [NSNull null],
                      };

When serializing a dictionary, NSNull s are translated to null in the JSON. 序列化字典时, NSNull会在JSON中转换为null

If you want to exclude such keys completely, instead of having them with a null value, you'll have to do more work. 如果要完全排除此类键,而不是让它们具有null值,则必须做更多的工作。 The simplest is to use an NSMutableDictionary and test each value before adding it. 最简单的方法是使用NSMutableDictionary并在添加每个值之前对其进行测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM