无法从JSON Webservice获取值

时间:2012-06-05 16:20:55

标签: asp.net ios xcode json web-services

我有一个Web服务,它从数据库中选择数据并将它们以JSON格式发送到Iphone

我的网络服务:

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
       [WebMethod]
       public string Person()
       {
           return Helper.Person();
       }

My Helper.cs

public class Helper
{
   internal static string Person()
   {
       List<object> person = new List<object>();

       using (SqlConnection con = new SqlConnection(@"Data Source=Localhost\SQLEXPRESS;Initial Catalog=BOOK-IT-V2;Integrated Security=true;"))
       using (SqlCommand cmd = new SqlCommand(@"SELECT EMAIL FROM PERSON", con))
       {
           con.Open();
           using (SqlDataReader rdr = cmd.ExecuteReader())
           {
               while (rdr.Read())
               {
                   if (rdr["EMAIL"] != DBNull.Value)
                   {
                       raumKlassenObject.Add(new {
                           Email=rdr["EMAIL"].ToString()});
                   }
               }
           }
       }

       return new JavaScriptSerializer().Serialize(person.ToArray());
   }
}

在Xcode中:

  #import "RaumklasseViewController.h"

@interface RaumklasseViewController ()

@end

@implementation RaumklasseViewController
@synthesize result;
@synthesize dic;
@synthesize array;



- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (void) sendRequest:(NSString*)jsonText
{
    NSURL *url = [[NSURL alloc]initWithString:@"http://ndqqxtsdsdoludwons-entwickludng.de/Webdiendst22/service1.asmx/Raumklasse"];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    [request setHTTPMethod: @"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    NSData *reqData = [NSData dataWithBytes:[jsonText UTF8String] length:[jsonText length]];
    [request setHTTPBody:reqData];
    NSURLResponse *response =[[NSURLResponse alloc]init];
    NSError* error;
    result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

}
- (void)viewDidLoad

{
    [super viewDidLoad];
    [self sendRequest:@""];
    dic = [NSJSONSerialization JSONObjectWithData:result options:kNilOptions error:nil];

    self.array= [dic objectForKey:@"d"];

    NSMutableArray *finalArray = [[NSMutableArray alloc] init];
    for(int n=0; n<[self.array count]; n++)
        [finalArray addObject:[[self.array objectAtIndex:n] objectForKey:@"Email"]];

}
- (void)viewDidUnload
{
    [super viewDidUnload];


}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{


    return [self.array count];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    cell.textLabel.text=[array objectAtIndex:indexPath.row];

    return cell;


}



@end

到目前为止它的确有效,我的输出是:

[{"Email":"abcd@web.de"},{"Email":"acsb@web.de"},{"Email":"asbd@gmx.de"},{"Email":"abcdw@web.de"},{"Email":"absds@web.de"}]

但如果我尝试

self.array = [[dic objectForKey:@"d"] objectForKey:@"Email"];

仅获取值:abcd @ web.de,acsb @ web.de,asbd @ gmx.de等。

所以我得到一个错误:

 [__NSCFString objectForKey:]: unrecognized selector sent to instance 0x6a4ccb0.

我认为Webservice正在回错。 ,但我不知道是什么。也许你可以帮助我。

提前谢谢。

2 个答案:

答案 0 :(得分:2)

问题在于:

[dic objectForKey@"d"]

返回字典数组。无法像使用objectForKey一样访问数组:

// the second objectForKey message is being sent to the array returned by the first objectForKey
[[dic objectForKey:@"d"] objectForKey:@"Email"];

但是,valueForKey确实对数组有效,并返回一个新数组,该数组是在每个数组的元素上调用valueForKey产生的:

NSArray *objects = [dict objectForKey:@"d"];
NSArray *emails = [objects valueForKey:@"Email"];

这将为您提供字典数组中的所有电子邮件地址。

答案 1 :(得分:0)

每个字典中都有一个字典数组,其中只有一个键("Email")。

objectForKey:是一个返回字典中键的对象的方法。

您无法在从[dic objectForKey:@"d"]接收的阵列上调用此方法,因为此方法不适用于阵列。

改为使用objectAtIndex:,如下所示:

self.array = [dic objectForKey:@"d"];
NSMutableArray *finalArray = [[NSMutableArray alloc] init];
for(int n=0; n<[self.array count]; n++)
    [finalArray addObject:[[self.array objectAtIndex:n] objectForKey:@"Email"]];

一旦完成运行,finalArray将仅包含电子邮件地址的字符串数组。