gpt4 book ai didi

iOS 错误解析 JSON

转载 作者:行者123 更新时间:2023-11-28 22:01:03 25 4
gpt4 key购买 nike

我是 iOS 新手。我有需要解析的 JSON 数据:

{  
"allseries":[
{
"type":"HR",
"title":"Heart Rate",
"xLabel":"Time",
"yLabel":"Beats per Min",
"defaultUnit":"BPM",
"url":"info/info?user=admin%40korrent.com&type=HR",
"size":18,
"firstTs":1406755651,
"lastTs":1406841254
},
{
"type":"TEMP",
"title":"Temperature",
"xLabel":"Time",
"yLabel":"Temperature",
"defaultUnit":"F",
"url":"info/info?user=admin%40korrent.com&type=TEMP",
"size":6,
"firstTs":1406854147,
"lastTs":1406854283
}
],
"status":"OK"
}

到目前为止,这是我的代码:

NSString *dataReceived= [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
NSLog(@"--> async response data (string): %@", dataReceived);
NSData *jsonData = [dataReceived dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:nil error:&jsonError];
NSLog(@"JSON key and value %@", [dict description]);
NSLog(@" %@ ", dict[@"allseries"]);
NSString *jsonString=dict[@"allseries"];
if (_programState == 4){
NSLog(@"state is 4");
NSLog(@"%@",jsonString);
NSData *Data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

但是,代码会为这一行抛出无效参数异常:

 NSData *Data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

此外,jsonString 似乎完全“无法操作”。我无法拆分它,无法向其附加字符串等。那怎么了?

最佳答案

// The following two lines are just for logging and otherwise are not needed.
NSString *dataReceived= [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
NSLog(@"--> async response data (string): %@", dataReceived);

// Deserialize the JSON data into a dictionary
NSError *jsonError;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData: _responseData options:nil error:&jsonError];
NSLog(@"JSON key and value %@", dict);

// Get the array from the dictionary element "allseries".
NSArray *jsonArray = dict[@"allseries"];
NSLog(@"jsonArray: %@", jsonArray);

这里 jsonArray 是 JSON 中“allseries”的字典数组

关于iOS 错误解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25088902/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com