Конвертировать канал JSON в NSDictionary

nth-of-type работает в соответствии с индексом того же типа элемента, но nth-child работает только в соответствии с индексом независимо от того, какой тип элементов сиблингов.

Например

<div class="one">...</div>
<div class="two">...</div>
<div class="three">...</div>
<div class="four">...</div>
<div class="five">...</div>
<div class="rest">...</div>
<div class="rest">...</div>
<div class="rest">...</div>
<div class="rest">...</div>
<div class="rest">...</div>

Предположим, что в выше html мы хотим скрыть все элементы, имеющие класс отдыха.

В этом случае nth-child и nth-of-type будут работать точно так же, как и все элементы одного типа, <div>, поэтому css должен быть

.rest:nth-child(6), .rest:nth-child(7), .rest:nth-child(8), .rest:nth-child(9), .rest:nth-child(10){
    display:none;
}

OR

.rest:nth-of-type(6), .rest:nth-of-type(7), .rest:nth-of-type(8), .rest:nth-of-type(9), .rest:nth-of-type(10){
    display:none;
}

Теперь вам должно быть интересно узнать, в чем разница между nth-child и nth-of-type, так что это разница

Предположим, что html is

<div class="one">...</div>
<div class="two">...</div>
<div class="three">...</div>
<div class="four">...</div>
<div class="five">...</div>
<p class="rest">...</p>
<p class="rest">...</p>
<p class="rest">...</p>
<p class="rest">...</p>
<p class="rest">...</p>

В приведенном выше html тип элемента .rest отличается от других .rest - это абзацы, а другие - div, поэтому в этом случае if вы используете nth-child, вы должны писать так

.rest:nth-child(6), .rest:nth-child(7), .rest:nth-child(8), .rest:nth-child(9), .rest:nth-child(10){
    display:none;
}

, но если вы используете nss-тип css, это может быть

.rest:nth-of-type(1), .rest:nth-of-type(2), .rest:nth-of-type(3), .rest:nth-of-type(4), .rest:nth-of-type(5){
    display:none;
}

Как тип Элементом .rest является <p>, поэтому здесь nth-of-type обнаруживает тип .rest, а затем он накладывает css на 1-й, 2-й, 3-й, 4-й, 5-й элементы <p>.

29
задан Carl Veazey 25 October 2013 в 06:25
поделиться

5 ответов

Вы не можете просто привести строку в качестве словаря и ожидать, что она проанализирует JSON. Вы должны использовать библиотеку анализа JSON, чтобы взять эту строку и преобразовать ее в словарь.

8
ответ дан Carl Veazey 25 October 2013 в 06:25
поделиться

В IOS5 вы можете использовать NSJSONSerialization для сериализации JSON.

NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
100
ответ дан Cœur 25 October 2013 в 06:25
поделиться

Я сделал класс, который облегчает эту задачу. Он использует NSJSONSerialization для iOS 5. Клонируйте его из github здесь .

2
ответ дан Jagat Dave 25 October 2013 в 06:25
поделиться

Вам нужно использовать анализатор JSON. вот отредактированный код

+ (NSDictionary *)downloadJSON
{

NSDictionary *json_string;
NSString *dataURL = [NSString stringWithFormat:@"%@", JSON_CATEGORY_DATA_URL_STRING];
NSLog(@"%@",dataURL);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:dataURL]];    
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

json_string = [[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]autorelease];
//JSONValue is a function that will return the appropriate object like dictionary or array depending on your json string.
NSDictionary *json_dict = [json_string JSONValue];
NSLog(@"json_dict\n%@",json_dict);
    NSLog(@"json_string\n%@",json_string);

return json_dict;
}

это должен быть код для получения NSDictionary. но ваша строка json является массивом, поэтому вместо этого используйте.

+ (NSArray *)downloadJSON
{

NSDictionary *json_string;
NSString *dataURL = [NSString stringWithFormat:@"%@", JSON_CATEGORY_DATA_URL_STRING];
NSLog(@"%@",dataURL);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:dataURL]];    
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

json_string = [[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]autorelease];
NSArray *json_dict = [json_string JSONValue];
NSLog(@"json_dict\n%@",json_dict);
    NSLog(@"json_string\n%@",json_string);

return json_dict;
}

Редактировать: вам нужно использовать JSON.framework для вызова метода JSONValue.
также вам нужно вернуть json_dict вместо json_string, поскольку json_string имеет тип NSString, а не NSDictionary или NSArray.
и не выпускайте его автоматически, так как это ваша переменная класса

1
ответ дан Robin 25 October 2013 в 06:25
поделиться

создайте метод для извлечения данных. Передайте ваш URL в строке urlwithstring.

-(void)fetchjsondata
{
     NSString *login= [[NSString stringWithFormat:@"your url string"]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSLog(@"----%@", login);
    NSURL *url = [NSURL URLWithString:[login stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    //-- Get request and response though URL
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];


    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                               dispatch_async(dispatch_get_main_queue(), ^{
                                   if (data) {
                                       dic_property= [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                                       NSLog(@"%@", dic_property);
                                       NSLog(@"counts=%d",[[dic_property objectForKey:@"Data"]count]);



                                   }
                                   else {
                                       NSLog(@"network error, %@", [error localizedFailureReason]);
                                   }
                               });

                           }];

}

вызовите fetchjsonmethod в любом месте.

[NSThread detachNewThreadSelector: @selector (fetchdata) toTarget: self withObject: nil];

0
ответ дан Jigar Darji 25 October 2013 в 06:25
поделиться