разбор json + iphone - PullRequest
       9

разбор json + iphone

0 голосов
/ 20 июня 2011

как сделать разбор json в iphone.i использовал следующий способ: -

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    NSLog(@"viewdidload");
    responseData = [[NSMutableData data] retain]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:
                             [NSURL URLWithString:@"https://maps.googleapis.com/maps/api/place/search/json?location=-33.8670522,151.1957362&radius=500&types=food&name=harbour&sensor=false&key=AIzaSyAbgGH36jnyow0MbJNP4g6INkMXqgKFfHk"]];
    [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    NSLog(@"didReceiveResponse");
    [responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {        
    [responseData appendData:data]; 
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {    
    NSLog(@"didFailWithError");
    label.text = [NSString stringWithFormat:@"Connection failed: %@",
                                            [error description]];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSLog(@"connectionDidFinishLoading");   
    [connection release];
}

пожалуйста, направь меня, это правда. И как я могу получить данные точного тега, который мы делаем в XML.

Ответы [ 4 ]

1 голос
/ 30 сентября 2011

* После 1001 *

 - (void)connectionDidFinishLoading:(NSURLConnection *)connection

Вы получите ответные данные здесь. Вы должны преобразовать его в NSString, затем просто написать

[responseString JSONValue];

Если ваш ответ находится в массиве или словаре, то вы должны соответствующим образом его уловить. Как и если ваш ответ в формате словаря, напишите

NSDictionary *tempDict = [responseString JSONValue];

Надеюсь, это поможет вам.

1 голос
/ 18 января 2012

Слушайте, это простая демонстрация подключения JSON к JSON-строке парсера JSON. Для этого нужно добавить фреймворк JSON, но теперь в IOS 5 json встроен в xcode

- (void)viewDidLoad
{
[super viewDidLoad];
[self MethodCalling:@"GET" Body:@"" ValueForPut:@""];
}
-(void)MethodCalling:(NSString *)HttpMethod Body:(NSString *)BodyString ValueForPut:(NSString *)valueforput
{

NSString *strUrl= @"http://xoap.weather.com/weather/local/33135?cc=*&dayf=5&link=xoap&prod=xoap&par=1251259247&key=39128d1062f86c8e";
NSURL *url=[NSURL URLWithString:strUrl];
 strUrl=[strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSLog(@"domainURL :: %@",url);
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];

[req setTimeoutInterval:60.0];
[req setHTTPMethod:@"GET"];
if(theConnection)//NSURLConnection
    [self Set2Defaults];
theConnection=[[NSURLConnection alloc]initWithRequest:req delegate:self];
if(theConnection)
    webData=[[NSMutableData data]retain];//NSMutableData
else
    NSLog(@"Connection Failed !!!");

NSLog(@"Has got response");
 }


#pragma mark -
#pragma mark NSURL Connection Delegate methods

-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *) respons{
[webData setLength: 0];

}

-(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *) data {
[webData appendData:data];
}

-(void) connection:(NSURLConnection *) connection didFailWithError:(NSError *) error {

NSLog(@"Connection Failed!!!");

UIAlertView *noConnect = [[UIAlertView alloc] initWithTitle:@"Error!!!" message:@"Request Failed." delegate:self cancelButtonTitle:@"Retry" otherButtonTitles:@"Cancel",nil];
[noConnect show];
[noConnect release];
 }


-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *theXML = @"";
theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSASCIIStringEncoding];

NSLog(@"theXML Values : %@", theXML);

ResponseDict = [theXML JSONValue];
NSLog(@"Responce is.........##%@",[ResponseDict description]);

}

-(void)Set2Defaults {

if (webData != nil){
    [webData release];
    webData = nil;
}

if (theConnection != nil) {
    [theConnection release];
    if (theConnection != nil) 
        theConnection = nil;
}
 }
1 голос
/ 20 июня 2011

... и вот как это делается на iPhone:

NSDictionary *feed = responseData;
// get the array of "results" from the feed and cast to NSArray
NSArray *results= (NSArray *)[feed valueForKey:@"results"];

// loop over all the results objects and print their names
int ndx;
NSDictionary *result;
for (ndx = 0; ndx < results.count; ndx++) {
    NSDictionary *result = (NSDictionary *)[results objectAtIndex:ndx];
    NSLog(@"This is the name of this result: %@", [resultvalueForKey:@"name"]); 
}
0 голосов
/ 11 апреля 2013
SBJSON *parser2 = [[SBJSON alloc] init];

NSString *url_str2=[NSString stringWithFormat:@"http://Example Api Here"];

url_str2 = [url_str2 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSURLRequest *request2 =[NSURLRequest requestWithURL:[NSURL URLWithString:url_str2]];


NSData *response1 = [NSURLConnection sendSynchronousRequest:request2 returningResponse:nil error:nil];

NSString *json_string2 = [[NSString alloc] initWithData:response1 encoding:NSUTF8StringEncoding];

NSDictionary *statuses3 = [parser2 objectWithString:json_string2 error:nil];

NSArray *news_array=[[statuses3 objectForKey:@"sold_list"] valueForKey:@"list"];

for(NSDictionary *news in news_array)
{

    @try {
      [title_arr addObject:[news valueForKey:@"gtitle"]];    //values Add to title array            

      NSLog(@"Display Title Array");

    }
    @catch (NSException *exception) {

        [title_arr addObject:[NSString stringWithFormat:@""]];
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...