2014-10-27 38 views
0

我正在爲ios應用程序調用php webservice。我收到如下字符串的迴應;如何從ios中的字符串響應中創建數組或字典?

一個:10:{S:11:「sso_user_id」; S:6:」 123456」 ; S:9:」姓名」; S:3:」 XYZ」,S:8:」姓氏」 S:3:」 ABC」; S:5:」 abono」; S:1:」 1」 ; S:4:」散列 「; S:32:」 638550add0b538a5a771d 「; S:5:」 令牌「; S :32: 「78451add0b51245789555514585」; S:5: 「登錄」; S:8: 「XXXXXXXX」; S:6: 「曲奇」; S:0: 「」; S:6: 「訪問」;一個:5: {S:4: 「角色」; S:6:「測試」; S:13: 」initial_reads「; S:1: 」8「; S:14: 」reads_remained「; S:1: 」8「; S :11: 「valid_until」; S:9: 「2014年11月1日」; S:10: 「tmp_portal」; S:10: 「google.com」;} S:5: 「錯誤」; S:0: 「」;}

......鍵.........和...........值

sso_user_id  123456 
firstname  xyz 
lastname  abc 
abono   1 
hash   638550add0b538a5a771d 
token   78451add0b51245789555514585 
login   xxxxx 
role   TESTER 
initial_reads 11 
valid_until  2014-11-1 
tmp_portal  google.com 

注意:其中:10表示10個對象的數組,s:11表示長度爲10個字符的字符串。

但我沒有任何想法如何將此字符串轉換爲數組或字典來獲取鍵值。

感謝,

+1

爲什麼你使用字符串作爲響應,使用JSON輕鬆實現。 – 2014-10-27 04:36:06

+0

@KumarKL,但我沒有得到JSON格式的響應。 API由第三方製作。所以我不能告訴他們改變爲JSON響應 – Rohan 2014-10-27 04:37:51

+1

我可以看到一種可能性,即搜索'「」'並將字符串值視爲鍵和值。請使用 – 2014-10-27 04:41:32

回答

0

最後我用以下解決我的問題。我在這裏發佈我的代碼,以便其他任何人都可以解決像我這樣的問題;

//在ParsedData.h

#import <Foundation/Foundation.h> 

@interface ParsedData : NSObject 
{ 

} 
@property(nonatomic,retain)NSMutableArray *parsedDataArr; 
@property(nonatomic,retain)NSMutableDictionary *finalDict; 

@end 

//在ParsedData.m

#import "ParsedData.h" 

@implementation ParsedData 

@synthesize parsedDataArr; 

-(id)init 
{ 
    parsedDataArr = [[NSMutableArray alloc]initWithObjects:@"sso_user_id",@"firstname", @"lastname",@"abono",@"hash",@"token",@"login",@"cookie",@"role",@"initial_reads",@"reads_remained",@"valid_until",@"tmp_portal",@"error",nil]; 

    return self; 
} 

//你ViewVontrller.m ..

#imprort「ParsedData.h」

-(void)buildDataFromString:(NSString*)stringToBuild; 
{ 
    ParsedData *pd = [[ParsedData alloc]init]; 

    pd.finalDict = [[NSMutableDictionary alloc]init]; 

    for (int i =0; i < pd.parsedDataArr.count; i++) 
    { 
     NSString *arrKey = [pd.parsedDataArr objectAtIndex:i]; 

     if ([stringToBuild rangeOfString:arrKey].location != NSNotFound) 
     { 
      int length = 0; 

      NSString *subString = [stringToBuild substringFromIndex:[stringToBuild rangeOfString:arrKey].location + arrKey.length + 2]; 

      if ([arrKey isEqualToString:@"initial_reads"] || [arrKey isEqualToString:@"reads_remained"]) 
      { 
       length = [self getIntLengthValue:subString]; 

       [pd.finalDict setValue:[NSNumber numberWithInt:length] forKey:arrKey]; 

      } 
      else 
      { 
       length = [self getStringLengthValue:subString]; 

       if (length == 0) 
       { 
        [pd.finalDict setValue:@"" forKey:arrKey]; 
       } 

       else 
       { 
        // Gets the string inside the first set of parentheses in the regex 
        NSString *inside = [self getKeyValue:subString]; 

        [pd.finalDict setValue:inside forKey:arrKey]; 
       } 
      } 
     } 
    } 

    NSLog(@"final parsed values dict - %@",pd.finalDict); 
} 

-(int)getIntLengthValue:(NSString *)subString 
{ 
    NSRegularExpression *regex1 = [NSRegularExpression 
            regularExpressionWithPattern:@"\"(.+?)\"" options:0 error:NULL]; 

    NSTextCheckingResult *result = [regex1 firstMatchInString:subString 
                 options:0 range:NSMakeRange(0, [subString length])]; 

    NSString *str =[subString substringWithRange:[result rangeAtIndex:1]]; 

    NSCharacterSet *alphaNums = [NSCharacterSet decimalDigitCharacterSet]; 
    NSCharacterSet *inStringSet = [NSCharacterSet characterSetWithCharactersInString:str]; 
    BOOL isDigitOnly = [alphaNums isSupersetOfSet:inStringSet]; 

    if (isDigitOnly) 
    { 
     return [str intValue]; 
    } 
    else 
    { 
     return 0; 
    } 
} 

-(int)getStringLengthValue:(NSString *)subString 
{ 
    NSRegularExpression *regex1 = [NSRegularExpression 
            regularExpressionWithPattern:@":(.+?):" options:0 error:NULL]; 

    NSTextCheckingResult *result = [regex1 firstMatchInString:subString 
                 options:0 range:NSMakeRange(0, [subString length])]; 

    NSString *str =[subString substringWithRange:[result rangeAtIndex:1]]; 

    int length = [str intValue]; 

    return length; 
} 

-(NSString *)getKeyValue:(NSString *)subString 
{ 
    NSRegularExpression *regex = [NSRegularExpression 
            regularExpressionWithPattern:@"\"(.+?)\"" options:0 error:NULL]; 

    NSTextCheckingResult *result = [regex firstMatchInString:subString 
                options:0 range:NSMakeRange(0, [subString length])]; 

    // Gets the string inside the first set of parentheses in the regex 
    NSString *inside = [subString substringWithRange:[result rangeAtIndex:1]]; 

    return inside; 
} 
0

Well.It是很容易得到this.If你按照下面的編碼

//just give your URL instead of my URL 

    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL  URLWithString:@"http://api.worldweatheronline.com/free/v1/search.ashx?query=London&num_of_results=3&format=json&key=xkq544hkar4m69qujdgujn7w"]]; 

    [request setHTTPMethod:@"GET"]; 

    [request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"content-type"]; 

    NSError *err; 

    NSURLResponse *response; 

    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err]; 

//You need to check response.Once you get the response copy that and paste in ONLINE JSON VIEWER.If you do this clearly you can get the correct results.  

//After that it depends upon the json format whether it is DICTIONARY or ARRAY 

    NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err]; 

    NSArray *array=[[jsonArray objectForKey:@"s"]objectForKey:@"sso_user_id "]objectForKey:@"firstname"]objectForKey:@"lastname"]objectForKey:@"abono"]objectForKey:@"hash"]objectForKey:@"token"]objectForKey:@"login"]objectForKey:@"role "]objectForKey:@"initial_reads"]objectForKey:@"valid_until"]objectForKey:@"tmp_portal"]; // Now i give your key all keys.So check it. 
+0

而不是objectForKey這樣的解決方法,您還可以爲valueForKey提供valueForKey。 – user3182143 2014-10-27 04:52:32

+0

我沒有得到JSON格式的響應,我正在使用WSDL webservice,即通過xml解析 – Rohan 2014-10-27 05:02:28

+0

k.I現在將幫助您。 – user3182143 2014-10-27 05:04:22

0

在您的.h部分

  1. //第1步:添加代表類

    First of all you should add <NSXMLParserDelegate> 
    
  2. //第2步:創建必要的對象

    NSXMLParser *parser; 
        NSMutableData *ReceviedData; 
        NSMutableString *currentStringValue; 
    
        NSMutableArray *sso_user_id; 
        NSMutableArray *firstName; 
        NSMutableArray *lastName; 
        NSMutableArray *abono; 
        NSMutableArray *hash; 
        NSMutableArray *token; 
        NSMutableArray *login; 
        NSMutableArray *role; 
        NSMutableArray *initial_reads; 
        NSMutableArray *valid_until; 
        NSMutableArray *tmp_portal; 
    

    在您的m部分

    //Step 3 - Allocate your all Arrays in your viewDidLoad method 
    
        sso_user_id = [NSMutableArray alloc]init]; 
        .... 
        tmp_portal = [NSMutableArray alloc]init]; 
    
    //Step 4 - Create Connection in your viewDidLoad Like 
    
        [self createConnection:@"http://www.google.com"];//give yoyur valid url. 
    
    - (void)createConnection:(NSString *)urlString 
    { 
        NSURL *url = [NSURL URLWithString:urlString]; 
    
        //Step 5 - parser delegate methods are using NSURLConnectionDelegate class or not. 
        BOOL success; 
        if (!parser) 
        { 
        parser = [[NSXMLParser alloc] initWithContentsOfURL:url]; 
        parser.delegate = self; 
        parser.shouldResolveExternalEntities = YES; 
        success = [parser parse]; 
        NSLog(@"Success : %c",success); 
        } 
    } 
    -(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict 
    { 
        NSLog(@"Current Element Name : %@",elementName); 
    
        if ([elementName isEqualToString:@"sso_user_id"]) 
        { 
        NSLog(@"The sso_user_id is==%@",elementName); 
        } 
        if ([elementName isEqualToString:@"firstName"]) 
        { 
        NSLog(@"The firstname is==%@",elementName); 
        } 
        if ([elementName isEqualToString:@"lastName"]) 
        { 
        NSLog(@"The lastname is==%@",elementName); 
        } 
    } 
    -(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string 
    { 
        currentStringValue = [[NSMutableString alloc] initWithString:string]; 
        NSLog(@"Current String Value : %@",currentStringValue); 
    } 
    -(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName 
    { 
        if ([elementName isEqualToString:@"sso_user_id"]) 
        { 
        [sso_user_id addObject:currentStringValue]; 
        } 
        if ([elementName isEqualToString:@"firstName"]) 
        { 
        [firstName addObject:currentStringValue]; 
        } 
        if ([elementName isEqualToString:@"lastName"]) 
        { 
        [lastName addObject:currentStringValue]; 
        } 
        currentStringValue = nil; 
    } 
    
+0

我沒有像這樣得到回覆。我得到整個響應字符串中的方法** - (無效)解析器:(NSXMLParser *)解析器foundCharacters:(NSString *)字符串**而不是元素由元素 – Rohan 2014-10-27 05:49:34

+0

你應該按照這種方式。否則很難得到響應羅漢。 – user3182143 2014-10-27 05:51:49

+0

如果你想要字符串,使用字符串,而不是數組。獲取字符串中的值。 – user3182143 2014-10-27 05:53:18