0

以下是有效的 JSON 响应:

**{
    "responseHeader": null,
    "cart": {
        "locale": "en_US",
        "currency": "USD",
        "purchaseRequestId": 0,
        "stuid": 0,
        "defaultHeaderLineLevels": {},
        "invalidMaterialIDs": [
            {
                "@class": "com.insight.web.domain.transaction.LineItem",
                "ewrFee": null,
                "name": null,
                "currency": null,
                "description": null,
                "categoryId": null,
                "poolID": null,
                "contractReportingFields": {},
                "selectedwarrantyDetails": null,
                "manufacturerName": null,
                "warrantyDetails": [],
                "vspp": false,
                "softwareLicense": false,
                "sourceContractId": null,
                "softwareLicenseType": "",
                "nonShipabble": false,
                "configured": false,
                "partnerID": null,
                "cartModifiedByConvertQuote": false,
                "stock": 0,
                "deletable": false,
                "duplicatable": false,
                "softwareLicensePhone": null,
                "softwareLicenseName": null,
                "zp00MaterialCategory": false,
                "quotedShippingPrice": null,
                "diversityPartners": [],
                "labFeesExists": false,
                "quoteConfigured": false,
                "quotedOrderConditions": null,
                "ruleID": ""
            },
            {
                "@class": "com.insight.web.domain.transaction.LineItem",
                "ewrFee": null,
                "name": null,
                "currency": null,
                "description": null,
                "selectPlus": false,
                "lineLevels": {},
                "materialID": "4434HE1-OPY",
                "materialIDKey": "",
                "isDiscontinued": false,
                "itemNumber": null,
                "quoteItemNumber": null,
                "price": 0,
                "quantity": 0,
                "materialCategory": null,
                "ruleID": ""
            }
        ],
        "webLoginProfile": null,
        "requestorGroupId": null,
        "defaultLineLevels": {},
        "totalCost": 0,
        "dpasCode": null,
        "orderedDate": null,
        "hasSPLAAndNonSPLAContracts": false,
        "cartItemsForEmail": [],

    },
    "materialIdKeyList": []
}

要从中提取所有键,我使用递归函数将 JSON 响应作为字典对象“数据”传递:

    -(NSMutableDictionary *)recurse:(NSDictionary *)data counter:(NSInteger *)i parent:(NSString *)parent
    {
        self.mDict =   [NSMutableDictionary dictionary];

        for (NSString* key in [data allKeys])
        { 
            NSDictionary

 *value = [data objectForKey:key];

        if ([value isKindOfClass:[NSDictionary class]])
        {
            i++;
            NSDictionary *newDict = (NSDictionary*)value;
            [self recurse:newDict counter:i parent:key];
            [self.mDict setValue:value forKey:key];
            i--;
            if(i==0)
            {
                return self.mDict;
            }

        }
        else if([value isKindOfClass:[NSArray class]])
        {
            // loop through the NSArray and traverse any dictionaries found
            NSArray *a = (NSArray *)value;
            for(id child in a)
            {
                if([child isKindOfClass:[NSDictionary class]])
                {
                    i++;
                    NSDictionary *newDict = (NSDictionary *)child;
                    [self recurse:newDict counter:i parent:key];
                    [self.mDict setValue:value forKey:key];
                    i--;

                    if(i==0)
                    {
                        return self.mDict;
                    }
                }
                else
                {
                    [self.mDict setValue:value forKey:key];
                }
            }
        }
        else 
        {
           [self.mDict setValue:value forKey:key];
        }
    }

    return self.mDict;
}

输出只为键提供 3 个键值对:postLoginRedirectUrl、cart、defaultHeaderLineLevels ......我的意思是它的荒谬。我应该包括哪些其他条件?或者是否有一种简单的方法可以从 JSON 响应中获取所有密钥,这是我的真正目标。

4

2 回答 2

0

您能否将 NSString 转换为 NSData 并尝试以下代码行?

NSDictionary *dictionaryResponse = [NSJSONSerialization JSONObjectWithData:[stringResponse dataUsingEncoding:NSASCIIStringEncoding] options:0 error:nil];
于 2012-12-18T06:10:15.680 回答
0

试试下面的代码,让我知道反馈。

 id jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:nil];



    if ([jsonObject respondsToSelector:@selector(objectForKey:)])

    {
NSDictionary *cart_Dict=[jsonObject valueForKey:@"cart"];
NSString *responseHeader=[jsonObject valueForKey:@"responseHeader"];
NSArray *invalidMaterial_CartDict_array=[[jsonObject valueForKey:@"cart"] objectForKey:@"invalidMaterialIDs"];
 NSArray *materialIdKeyList_array=[[jsonObject valueForKey:@"materialIdKeyList"]        

 }

如果您不知道响应字符串是什么,那么您必须找到所有键

 if ([jsonObject isKindOfClass: [NSArray class]])
    {
       //for Array you have to access by Object at Index
    }
    else if ([jsonObject isKindOfClass: [NSDictionary class]])
    {
       for (NSString *key in [jsonObject allKeys])
          {
              NSDictionary *feed = [jsonObject objectForKey:key];

           //do stuff with feed.
           }
    }
    else
    {
        // deal with it.
    }
于 2012-12-18T06:30:32.173 回答