не может разобрать строку json в nsdictionary - PullRequest
2 голосов
/ 12 августа 2011

Я пытаюсь разобрать строку json с помощью sbjsonparser.У меня возникли проблемы с преобразованием его в обязательный.Я использовал sbjsonparser в других своих классах, и все они работали нормально.см. мой код.

-(void)parseJsonString
{
    NSLog(@"%@",jsonString);
    SBJsonParser *parser = [[SBJsonParser alloc] init]; 
    NSDictionary *dict;
    dict = [parser objectWithString:jsonString error:nil];
    NSLog(@"%@",dict);


    NSDictionary *dict2;
    dict2 = [jsonString JSONValue];
    NSLog(@"%@",dict2);

   [parser release];

}

вот мой вывод на консоль:

2011-08-12 13:56:55.098 EasyQuiz[5446:13603] [{
"q": "Question Testing", 
"score": 1, 
"c3": "Choice C", 
"c2": "Choice B", 
"c1": "Choice A", 
"rev": 1, 
"id": 1, 
"c4": "Choice D"
}]
2011-08-12 13:56:55.686 EasyQuiz[5446:13603] (null)
2011-08-12 13:56:56.296 EasyQuiz[5446:13603] -JSONValue failed. Error is: Illegal start  
of token []
2011-08-12 13:56:56.297 EasyQuiz[5446:13603] (null)

Я проверил строку в http://jsonformatter.curiousconcept.com/, и она кажетсядействительный.Как вы думаете, что вызывает эту проблему?спасибо!

Я напечатал ошибку в dict = [parser objectWithString: jsonString error: nil];и он говорит:

  Error Domain=org.brautaset.SBJsonParser.ErrorDomain Code=0 "Illegal start of token []" 
  UserInfo=0x62eb920 {NSLocalizedDescription=Illegal start of token []}

РЕДАКТИРОВАТЬ Я попытался жестко закодировать jsonstring следующим образом

NSString *thisJsonString = @"[{\"q\": \"Question Testing\",\"score\": 1, \"c3\": \"Choice C\", \"c2\": \"Choice B\", \"c1\": \"Choice A\", \"rev\": 1, \"id\": 1, \"c4\": \"Choice D\"}]";

SBJsonParser *parser = [[SBJsonParser alloc] init];

NSDictionary *dict;

dict = [parser objectWithString:thisJsonString error:nil];
NSLog(@"dict %@",dict);

[parser release];

, и я получил то, что я хочу в консоли:

dict (
    {
    c1 = "Choice A";
    c2 = "Choice B";
    c3 = "Choice C";
    c4 = "Choice D";
    id = 1;
    q = "Question Testing";
    rev = 1;
    score = 1;
}
)

РЕДАКТИРОВАТЬ В случае, если вы хотите знать, где я получаю данные.Я загружаю zip-файл с веб-сайта, используя asihttprequest, и этот файл извлекается с помощью target-zip, а извлеченный файл читается следующим образом.

NSString *filePath = [[self applicationDocumentsDirectory]  
stringByAppendingPathComponent:@"json.zip"];

    //Opening zip file for reading...
    progressLabel.text = @"Reading file...";
    ZipFile *unzipFile= [[ZipFile alloc] initWithFileName:filePath mode:ZipFileModeUnzip];

    //Opening first file...
    progressLabel.text = @"Opening file...";
    [unzipFile goToFirstFileInZip];
    ZipReadStream *read1= [unzipFile readCurrentFileInZip];

    //Reading from first file's stream...
    NSMutableData *data1= [[[NSMutableData alloc] initWithLength:1000000] autorelease];//100MB
    int bytesRead1= [read1 readDataWithBuffer:data1];
    NSLog(@"bytes: %d",bytesRead1);
    if (bytesRead1 > 0) {
        progressLabel.text = @"File is good!";
        jsonString = [[[NSString alloc] initWithData:data1 encoding:NSUTF8StringEncoding] autorelease];
//.... more codes follow, but this is how I get jsonString

Ответы [ 2 ]

0 голосов
/ 12 августа 2011

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

-(void)parseJsonString
{

   NSArray *jsonArray = (*NSArray)[jsonString JSONValue];

   NSDictionary *jsonDict = [jsonArray objectAtIndex:0];

   NSString *q = [jsonDict objectForKey:@"q"];
   ...

}
0 голосов
/ 12 августа 2011

objectWithString: ошибка: возвращается тип id , измените код, как показано ниже, и дайте мне знать.

    NSString *str = [NSString stringWithFormat:@"%@", [parser objectWithString:jsonString error:nil]]; 
    NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:str,@"response", nil];
    NSLog(@"%@",[dict description]);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...