如何在ios中将nsstring格式转换为json响应格式



我的Json响应:

{
"xxx": {
"y": {
"id": 1,
"name": "z"
},
"startday": "2016-01-10",
"status": "New",
"total": 1,
"a": [
{
"id": 766,
"b": {
"id": 3,
"name": "c"
},
"d": {
"id": 4
 },
"e": {
"id": 1,
"name": "f"
},
"g": {
"id": 8,
"name": "h"
},
"hours": 1,
"comments": "",
"spent_on": "2016-01-10"
}
]
}
}

由此我创建了一个字符串,如下所示:

 NSString * str = @"{"xxx":{"y":{"id":1,"name":"z"},"startday":"2016-01-10","status":"New","total":1.0,"a":[{"id":766,"b":{"id\":3,\"name\":\"c\"},\"d\":{\"id\":4},\"e\":{\"id\":1,\"name\":\"f\"},\"g\":{\"id\":8,\"name\":\"h\"},\"hours\":1.0,\"comments\":\"\",\"spent_on\":\"2016-01-10\"}]}}";

然后我通过下面的代码发布这个值:

NSData *objectData = [str  dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:objectData options:NSJSONReadingMutableContainers error:&jsonError];
if (jsonError == NULL)
{
msgView =@"error msg null";
NSURL *url = [NSURL URLWithString:@"xxx"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                             cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:@"POST"];
[request setHTTPBody: requestData];
}

它访问服务器并得到响应。类似地,我得到用户输入应用程序的所有值。我使用串联创建NSstring。

NSString* concate = [NSString stringWithFormat:@"%@%@%@%@,%@%@%@,%@,%@%@,%@%,%@,%@,%@%@%@%@%@%@,%@%@,%@%@,%@%@",xx,....];

所以我在连接后得到这样的输出响应:

{"x":{"y":{"id":1,
"name":"a"
},
"startday":"2016-01-10"
,
"status":"New"
,{"total":1,"time_entries":[{"id":766,
"b":{
"id":8,
"name":"c"
}
,
"u":{
"id":22
}
,"d":{"id":1
"name":"e"
},
"l":{
"id":8,
"name":"g"
}
,"hours":1,"comments":"","spent_on":"2016-01-12"}]}}

因此,如果通过这个,它会抛出错误。在这里,我必须将不同的字符串与其他方法连接或组合。或者,有没有任何可能将字符串转换为json响应格式。或者,还有任何其他简单的方法来完成这项任务。请给我一些想法。

首先,您需要通过执行以下将NSString转换为NSData

NSData *data = [concate dataUsingEncoding:NSUTF8StringEncoding];

然后简单地使用NSJSONSerializationJSONObjectWithData:方法将其转换为JSON

NSError *error = nil;
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if(!error) {
    NSLog(@"%@", json);
}

首先需要将NSString转换为NSData

NSString * str = @"{"xxx":{"y":{"id":1,"name":"z"},"startday":"2016-01-10","status":"New","total":1.0,"a":[{"id":766,"b":{"id\":3,\"name\":\"c\"},\"d\":{\"id\":4},\"e\":{\"id\":1,\"name\":\"f\"},\"g\":{\"id\":8,\"name\":\"h\"},\"hours\":1.0,\"comments\":\"\",\"spent_on\":\"2016-01-10\"}]}}";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];

现在,使用NSJSONSerialization 将该NSData转换为id

id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

在这里,您有您的json数据

NSLog(@"%@",json);

最新更新