回應範例
{
"ErrorCode": 0,
"IsCompleted": true,
"Result": "{\"CompanyCode\":\"100000\",\"CompanyName\":\"...\"}" // Result 是字串化的 JSON
}
解析步驟
- 第一層解析:
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:received
options:NSJSONReadingMutableLeaves
error:nil];
NSInteger errorCode = [dict[@"ErrorCode"] integerValue];
BOOL completed = [dict[@"IsCompleted"] boolValue];
- 第二層解析(
Result 為 JSON 字串):
NSString *resultStr = dict[@"Result"];
NSData *resultData = [resultStr dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *resultDict = [NSJSONSerialization JSONObjectWithData:resultData
options:0
error:nil];
NSString *companyCode = resultDict[@"CompanyCode"];
NSString *companyName = resultDict[@"CompanyName"];
// ... 其他欄位
關鍵點
- 使用
NSJSONSerialization(iOS 5+ 內建),無需第三方庫。
- 巢狀 JSON 字串需**二次解析**:先取出字串 → 轉
NSData → 再解析。
- 建議統一錯誤處理:檢查
error 指標,ErrorCode 非 0 時拋出業務異常。