簡體   English   中英

無法從JSON響應中提取密鑰

[英]Unable to extract the keys from a 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": []
}

為了從中提取所有鍵,我正在使用遞歸函數,將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,購物車,defaultHeaderLineLevels ....我的意思是荒謬的。 我應該包括哪些其他條件?或者是否有一種簡單的方法來從JSON響應中獲取所有密鑰,這是我的真正目標。

您能否將NSString轉換為NSData並嘗試以下代碼行?

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

嘗試以下代碼,讓我知道反饋。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM