使用Objective-C解析JSON字符串响应时出错

时间:2014-01-17 13:26:40

标签: ios objective-c json

我得到的回应:

  

{ “响应”:{ “ID”: “R1”, “CMD”:[{ “BATCHSIZE”:50, “STARTROW”:0, “姓名”: “doLogin”, “结果”: “OK” “属性”:[{ “名称”: “BUSINESSNAME”, “类型”: “字符串”},{ “名称”: “OBJID”, “类型”: “长”},{ “名称”: “businessType” , “类型”: “字符串”},{ “名称”: “名字”, “类型”: “字符串”},{ “名称”: “BUSINESSNAME”, “类型”: “字符串”},{ “名” : “OBJID”, “类型”: “龙”},{ “名”: “businessType”, “类型”: “字符串”},{ “名”: “名字”, “类型”: “字符串”}] “记录”:[ “BUSINESSNAME \”:\“帕洛阿尔托   中音蛋 -   分销商 “ ”OBJID \“:\ ”200“, ”businessType \“:\ ”d“, ”名字\“:\ ”系统“],[ ”BUSINESSNAME \“:\” 帕洛阿   中音蛋 -   分销商 “ ”OBJID \“:\ ”200“, ”businessType \“:\ ”d“, ”名字\“:\ ”系统“],[ ”BUSINESSNAME \“:\” 帕洛阿   中音蛋 -   分销商 “ ”OBJID \“:\ ”200“, ”businessType \“:\ ”d“, ”名字\“:\ ”系统“],[ ”BUSINESSNAME \“:\” 帕洛阿   中音蛋 -   分销商”, “OBJID \”:\ “200”, “businessType \”:\ “d”, “名字\”:\ “系统”]]}]}}

现在的问题是....... NSDictionary * json = [NSJSONSerialization JSONObjectWithData:(NSData *)obj options:kNilOptions error:& error];

NSDictionary *first = [json objectForKey:@"response"];
NSArray *second = [first objectForKey:@"cmd"];
NSArray *attribute_array = [[second objectAtIndex:0] objectForKey:@"result"];
NSLog(@"Resultttttttttt=%@",attribute_array);

//Value of Result
NSString *resultVal = [NSString stringWithFormat:@"%@",attribute_array];

NSArray *record_array = [[second objectAtIndex:0] objectForKey:@"records"];

NSLog(@"Resultttttttttt Nisarg = %@",[[record_array objectAtIndex:0] objectForKey:@"firstName\\"]);

在我尝试获取键 firstName 的值的最后一句中,它给出了Error,因为结构类似于“firstName \”而不是键< strong>“firstName”所以任何建议用“firstName \”键解析字符串......

2 个答案:

答案 0 :(得分:1)

您的JSON格式正确,但每条记录都是字符串列表,而不是字典,即您有

[
    "businessName\":\"Palo Alto Egg - Distributor",
    "objId\":\"200",
    "businessType\":\"D",
    "firstName\":\"System"
],

而不是

{
    "businessName": "Palo Alto Egg - Distributor",
    "objId": "200",
    "businessType": "D",
    "firstName": "System"
},

因此[record_array objectAtIndex:0]是一个数组,而不是字典。

如果您可以控制JSON输出,则应检查代码并使其返回正确的格式。 如果您无法更改输出,并且您不希望在原始JSON数据中进行复杂的字符串操作,则最佳替代方法如下:

NSString *firstName = NULL;

for (NSString *line in record) {
    if ([line hasPrefix:@"firstName"]) {
        firstName = [[line componentsSeparatedByString:@"\":\""] objectAtIndex:1];
    }
}

NSLog(@"%@", firstName);

答案 1 :(得分:0)

为什么要转义报价?:

[["businessName\":\"Palo Alto Egg - Distributor","objId\":\"200","businessType\":\"D","firstName\":\"System"],["businessName\":\"Palo Alto Egg - Distributor","objId\":\"200","businessType\":\"D","firstName\":\"System"],["businessName\":\"Palo Alto Egg - Distributor","objId\":\"200","businessType\":\"D","firstName\":\"System"]

必须是:

[["businessName":"Palo Alto Egg - Distributor","objId":"200","businessType":"D","firstName":"System"],["businessName":"Palo Alto Egg - Distributor","objId":"200","businessType":"D","firstName":"System"],["businessName":"Palo Alto Egg - Distributor","objId":"200","businessType":"D","firstName":"System"]