[英]How to obtain a String from a dictionary and make sure it is not null? (Swift / iOS)
[英]How to make array or dictionary from string response in ios?
我正在为ios应用程序调用php webservice。 我得到的响应如下字符串:
a: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:“ cookie”; s:0:“”; s:6:“访问”; a:5:{s:4:“角色“; s:6:” TESTER“; 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
注意:其中a:10表示10个对象的数组,而s:11表示长度为10个字符的字符串。
但我不知道如何将该字符串转换为数组或字典以获取键值。
谢谢,
好吧,这很容易得到。如果您遵循以下代码
//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.
在您的.h部分
//步骤1:添加Delegate类
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; }
最后,我通过关注解决了我的问题。 我将代码发布在这里,以便其他任何人都可以解决我的相同问题;
//在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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.