如何从ios中的字符串响应中创建数组或字典?
我正在为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个字符的字符串。
但我没有任何想法如何将此字符串转换为数组或字典来获取键值。
感谢,
最后我用以下解决我的问题。我在这里发布我的代码,以便其他任何人都可以解决像我这样的问题;
//在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;
}
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.
而不是objectForKey这样的解决方法,您还可以为valueForKey提供valueForKey。 – user3182143 2014-10-27 04:52:32
我没有得到JSON格式的响应,我正在使用WSDL webservice,即通过xml解析 – Rohan 2014-10-27 05:02:28
k.I现在将帮助您。 – user3182143 2014-10-27 05:04:22
在您的.h部分
-
//第1步:添加代表类
First of all you should add <NSXMLParserDelegate>
-
//第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; }
我没有像这样得到回复。我得到整个响应字符串中的方法** - (无效)解析器:(NSXMLParser *)解析器foundCharacters:(NSString *)字符串**而不是元素由元素 – Rohan 2014-10-27 05:49:34
你应该按照这种方式。否则很难得到响应罗汉。 – user3182143 2014-10-27 05:51:49
如果你想要字符串,使用字符串,而不是数组。获取字符串中的值。 – user3182143 2014-10-27 05:53:18
为什么你使用字符串作为响应,使用JSON轻松实现。 – 2014-10-27 04:36:06
@KumarKL,但我没有得到JSON格式的响应。 API由第三方制作。所以我不能告诉他们改变为JSON响应 – Rohan 2014-10-27 04:37:51
我可以看到一种可能性,即搜索'“”'并将字符串值视为键和值。请使用 – 2014-10-27 04:41:32