2017-06-14 91 views
0

我对数据库中的Answer列有以下格式的答案(来自服务器)。 enter image description hereNsdictionary格式问题

在应用程序端更新答案并将其保存到数据库时,它将被修改为以下格式(即:被替换为=)我想保持相同的格式。有人能让我知道什么是问题吗?我正在使用NSDictionary访问键值对,并将最终的nsdictionary分配给数据库。 enter image description here

+1

有一个在JSON字符串表示一个字典之间的差,并调用'一个'NSDictionary'对象的description'方法之前有一个NSJSONSerialization。 – Larme

回答

1

包含JSON的NSDictionary和NSString不是同一个对象,所以它们没有相同的格式。当你用NSLog打印这些对象时,它会调用这些对象的描述方法。此方法返回NSString的字符串和NSDictionary的特定格式字符串。

如果你要检索的JSON格式,你需要像下面再次改变你的NSDictionary以JSON字符串:

NSError *error; 
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error]; 
NSString *strJson = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; 

if (error) 
    NSLog(@"An error occured"); 

然后:

NSLog(@"%@", strJson); 

我希望我的英语是可以理解的。不要犹豫,纠正我。

1

As @Larme指出-[NSDictionary description]不返回字典的JSON表示。 NSArray以类似的方式工作。

NSDictionary的描述格式如下。

说明 NSArray
{ 
    key1 = value1; 
    key2 = value2; 
    ... 
    keyN = valueN; 
} 

看起来如下:

(
    object1, 
    object2, 
    ... 
    objectN 
) 

为了从字典中获得JSON你应该使用NSJSONSerialization(或第三方库)。

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:response options:0 error:nil]; 
//Use line below to see formatted JSON 
//NSData *jsonData = [NSJSONSerialization dataWithJSONObject:response options:NSJSONWritingPrettyPrinted error:nil]; 
NSString *string = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; 
1

诀窍是将它传递给的NSString

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:YOUR_OBJECT options:0 error:&error]; 


NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];