我正在尝试从NSDictionary
的 JSON 响应中获取对象列表,然后将其存储在NSMutableArray
中,但它在数组中只给我一个对象, 你能帮我一个示例代码吗,
以下是 json 响应:
{
"errorCd": "00",
"desc": "Success",
"ref": 83,
"statusCode": "1",
"extraData": [
{
"key": "bal",
"value": "80"
},
{
"key": "txs",
"value": "[{"id":2268099999,"amnt":100.0,"curr":"JOD","sender":"PSPCI","receiver":"00962799999992","date":"Feb 1, 2016 4:03:25 PM","status":1,"type":5,"fees":0.0,"reference":40},{"id":2357099999,"amnt":20.0,"curr":"JOD","sender":"00962799999992","receiver":"PSPCI","date":"Feb 2, 2016 12:52:35 PM","status":1,"type":6,"fees":0.0,"reference":68}]"
}
]
}
我正在尝试获取密钥 tx 的值中的列表。
这就是我试图做的:
-(NSDictionary *)getListOfExtraData:(NSMutableArray *)extras{
NSDictionary *array = [[NSDictionary alloc] init];
for (NSDictionary *dictionary in extras) {
if([[dictionary valueForKey:@"key"] isEqualToString:@"txs"])
array = [dictionary objectForKey:@"value"];
}
if (array != nil && array.count > 0)
return array;
return nil;
}
JSON 数据无效,因为value
内部有一个对象"
你应该像这样发送你的 JSON
{
"errorCd": "00",
"desc": "Success",
"ref": 83,
"statusCode": "1",
"extraData": [
{
"key": "bal",
"value": "80"
},
{
"key": "txs",
"value": [
{
"id": 2268099999,
"amnt": 100.0,
"curr": "JOD",
"sender": "PSPCI",
"receiver": "00962799999992",
"date": "Feb 1, 2016 4:03:25 PM",
"status": 1,
"type": 5,
"fees": 0.0,
"reference": 40
},
{
"id": 2357099999,
"amnt": 20.0,
"curr": "JOD",
"sender": "00962799999992",
"receiver": "PSPCI",
"date": "Feb 2, 2016 12:52:35 PM",
"status": 1,
"type": 6,
"fees": 0.0,
"reference": 68
}
]
}
]
}
好吧,我会说JSON是不寻常的;看起来它可以是一个字符串化的数字("80"
)或JSON数组。
您需要进一步解析内部数组,使用:
NSData *jsonResponse = ...; // Response from server
NSError *error = nil;
NSDictionary *topLevelDict = [NSJSONSerialization JSONObjectWithData:jsonResponse
options:0
error:&error];
if (topLevelDict) {
NSArray *extraData = topLevelDict[@"extraData"];
for (NSDictionary *innerDict in extraData) {
if ([innerDict[@"key"] isEqualToString:@"txs"]) {
NSString *valueStr = innerDict[@"value"];
NSArray *innerArray = [NSJSONSerialization JSONObjectWithData:[valueStr dataUsingEncoding:NSUTF8StringEncoding]
options:0
error:&error];
if (innerArray) {
// FINALLY! WE HAVE IT!
} else {
// Report error
}
break;
}
}
} else {
// report error
}
After the json is in correct format,i.e.
{
"errorCd": "00",
"desc": "Success",
"ref": 83,
"statusCode": "1",
"extraData": [
{
"key": "bal",
"value": "80"
},
{
"key": "txs",
"value": [
{
"id": 2268099999,
"amnt": 100.0,
"curr": "JOD",
"sender": "PSPCI",
"receiver": "00962799999992",
"date": "Feb 1, 2016 4:03:25 PM",
"status": 1,
"type": 5,
"fees": 0.0,
"reference": 40
},
{
"id": 2357099999,
"amnt": 20.0,
"curr": "JOD",
"sender": "00962799999992",
"receiver": "PSPCI",
"date": "Feb 2, 2016 12:52:35 PM",
"status": 1,
"type": 6,
"fees": 0.0,
"reference": 68
}
]
}
]
}
要存储数组,您需要将变量数组声明为 NSArray 或 NSMutableArray,而不是 NSDictionary