【问题标题】:Json Data converted to Json string but not in Json DictionaryJson 数据转换为 Json 字符串但不在 Json 字典中
【发布时间】:2013-08-12 05:16:53
【问题描述】:

这个问题已经被问过很多次了,但使用相同的代码我得到了工作。

我使用下面的代码来生成 Json 字典和 Json 字符串。它成功创建了 json 字符串,但没有创建 json 字典。

 NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:&writeError];

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

 NSDictionary *dicJsonRequest = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&convertError];

NSLog(@"\n dicjson : %@ \n json string : %@ \n error : %@",dicJsonRequest,strJsonRequest,convertError.localizedDescription);

我用来传递数据的这个方法,这需要 NSDictionary

- (void)postPath:(NSString *)path
      parameters:(NSDictionary *)parameters
         success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
         failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;

如果我使用此处创建的 JsonString 创建 NSDictionary,那么它将被转换为 Web 服务端不接受的不同格式

NSDictionary *WSCALL = [NSDictionary dictionaryWithObjectsAndKeys:strJsonRequest,"Post", nil];
 NSLog(@"WSCALL : %@",WSCALL);

输出:

WSCALL : {
    Post = "{\n  \"email\" : \"test@test.com\",\n  \"password\" : \"test\",\n  \"name\" : \"abcd\",\n ";
}

编辑

我在这里可以得出的结论是,webservice 需要创建相同的 json 字符串,但没有这个 "\n" 和 \"email\" (FALSE) -> "email"(TRUE) 但我无法替换“\n”,因为它是在我为字典中的键设置值时添加的。

有了这个我得到输出

dicjson : {
    email = "test@test.com";
    name = abcd;
    password = test;
} 
 json string : {
  "email" : "test@test.com",
  "name" : "abcd",
  "password" : "test"
} 
 error : (null)

【问题讨论】:

  • 问题出在哪里?你得到一个字典,一个字符串,并且没有错误。我不明白你想要达到什么目的。
  • 我的问题是我没有得到 json 格式的字典。即使我可以将字符串转换为 json,但我需要 json 字典
  • 我正在使用 ASIHTTP,它需要 NSDictionary 作为请求参数,在 web 服务中我需要传递在 json 字符串中创建的结构。我已将 json 字符串直接检查到 REST,然后它正在工作,但代码中的数据类型不起作用
  • 不能像用“:”代替“=”吗?
  • 如果你这样做会发生什么...NSLog(@"%@", dicJsonRequest[@"email"]);?

标签: iphone objective-c json nsjsonserialization


【解决方案1】:

嗯,您所做的事情没有错误,并且日志清楚地表明您正在获取 NSDictionary,如果您尝试记录 NSDictionary,很明显您会收到 json 字符串响应。请参阅这一行

NSLog(@"\n dicjson : %@ \n json string : %@ \n error : %@",dicJsonRequest,strJsonRequest,convertError.localizedDescription);

这里 NDDictionary 包含正确的值,因为日志显示

dicjson : {
    email = "test@test.com";
    name = abcd;
    password = test;
} 

所以你手头有一本有效的字典。只需进行剩余的编码

【讨论】:

  • 它需要我得到的字典的 json 字符串格式。像“:”而不是“=”
  • 我不明白为什么如果我将字符串设置为字典,它会变成Post = "{\n \"email\" : \"test@test.com\",\n \"password\" : \"test\",\n \"name\" : \"abcd\",\n ";,然后如果我得到valueforkey:@"Post",它会打印普通字符串{"email" : "test@test.com", "name" : "abcd", "password" : "test"}
猜你喜欢
  • 2021-11-04
  • 2018-06-28
  • 1970-01-01
  • 2016-12-06
  • 2017-04-27
  • 2013-10-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多