简体   繁体   English

无法从JSON响应中提取密钥

[英]Unable to extract the keys from a JSON response

Following is valid JSON Response: 以下是有效的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": []
}

To extract all the keys from it I am using the recursive function passing the JSON response as dictionary object "data": 为了从中提取所有键,我正在使用递归函数,将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;
}

The output only gives 3 keys-values pairs for keys: postLoginRedirectUrl, cart, defaultHeaderLineLevels....I mean its absurd. 输出仅为键提供3个键-值对:postLoginRedirectUrl,购物车,defaultHeaderLineLevels ....我的意思是荒谬的。 What other conditions should i include ?or is there a easy way to get all the keys from the JSON response which is my true goal. 我应该包括哪些其他条件?或者是否有一种简单的方法来从JSON响应中获取所有密钥,这是我的真正目标。

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

NSDictionary *dictionaryResponse = [NSJSONSerialization JSONObjectWithData:[stringResponse dataUsingEncoding:NSASCIIStringEncoding] options:0 error:nil];

Try The Following Code and let me know the feedback. 尝试以下代码,让我知道反馈。

 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 you dont know what is the respond string then you have to find all Keys 如果您不知道响应字符串是什么,那么您必须找到所有键

 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.
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM