简体   繁体   English

JSON序列化返回Null

[英]JSON Serialization Returns Null

In our project we are taking values as json from services 在我们的项目中,我们从服务中获取值作为json

Most probably my questions were asked many times but I could not find any solution. 我的问题很可能被问过很多次,但是我找不到任何解决方案。

Here is the code block: 这是代码块:

  NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

  NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
  NSLog(@"Response ==> %@", responseData);
  NSError *error = nil;

  NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:urlData options:NSJSONReadingMutableContainers error:&error];

  NSString* userID = [jsonData objectForKey:@"user_ID"];
  NSLog(@"Success: %ld userID: %ld",(long)success, (long)userID);

Log: 日志:

Response code: 200 响应码:200

Response ==> 响应==>

{"user_ID":4} { “USER_ID”:4}

Success: 0 userID: 0 成功:0用户ID:0

As you can see I want to convert json object to string but when I printout content of jsonData it returns null I guess I have an issue with JSONSerializaton. 如您所见,我想将json对象转换为字符串,但是当我打印出jsonData的内容时,它返回null,我想我在JSONSerializaton上遇到了问题。 Can anyone suggest solution? 谁能建议解决方案?

Thanks, Umit 谢谢,Umit

Just test with the following code, it's OK. 只需测试以下代码,就可以了。 You should log the error and check the response data, it may contain some invalid encoding. 您应该记录该错误并检查响应数据,其中可能包含一些无效的编码。

const char *jsonStr = "{\"user_ID\":4}\n";
NSData *jsonData = [NSData dataWithBytes:jsonStr length:strlen(jsonStr)];
NSError *error = NULL;
NSDictionary *jsonObj = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
NSNumber *userIDObj = [jsonObj objectForKey:@"user_ID"];
NSInteger userID = [userIDObj integerValue];
NSLog(@"=========>User ID: %d", userID);

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

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