簡體   English   中英

在iOS中解析Google Speech Kit JSON

[英]Parse Google Speech Kit JSON in iOS

我收到來自Google Speech API的以下JSON響應

    {
    "result": [

    ]
}{
    "result": [
        {
            "alternative": [
                {
                    "transcript": "testing 123"
                },
                {
                    "transcript": "listing 123"
                },
                {
                    "transcript": "casting 123"
                },
                {
                    "transcript": "fasting 123"
                },
                {
                    "transcript": "listing 1 2 3"
                },
                {
                    "transcript": "Justin 123"
                },
                {
                    "transcript": "listening 123"
                },
                {
                    "transcript": "listen 123"
                }
            ],
            "final": true
        }
    ],
    "result_index": 0
}

但是我在解析JSON響應時遇到困難。 我有以下代碼

第一種方法:嘗試打印時得到的結果為空

NSDictionary *results = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableContainers error:nil];
NSDictionary *resultsDictionary = [[results objectForKey:@"result"] objectAtIndex:0];
    NSLog(@"result %@", resultsDictionary);

第二種方法:嘗試打印時得到相同的空白結果

NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data
                                                     options:kNilOptions 
                                                       error:&error];

NSArray* ResultArray = [json objectForKey:@"result"];

NSLog(@"result: %@", ResultArray);

另外,當我嘗試通過http://jsonlint.com/驗證JSON響應時,我收到以下消息

Parse error on line 5:
...: [            ]}{    "result": [  
--------------------^
Expecting 'EOF', '}', ',', ']'

您的回復格式不正確。 首先添加以下行以通過以下行刪除多余的空結果字符串:

yourJsonString = [yourJsonString stringByReplacingOccurrencesOfString:@"{\"result\":[]}" withString:@""];

然后,嘗試以下代碼:

    yourJsonString = [yourJsonString stringByReplacingOccurrencesOfString:@"{\"result\":[]}" withString:@""];

    NSData* jsonData = [yourJsonString dataUsingEncoding:NSUTF8StringEncoding];

    NSError *error = nil;
    NSDictionary *responseObj = [NSJSONSerialization
                                 JSONObjectWithData:jsonData
                                 options:0
                                 error:&error];

    if(! error) {
        NSArray *responseArray = [responseObj objectForKey:@"result"];
        for (NSDictionary *alternative in responseArray) {
            NSArray *altArray = [alternative objectForKey:@"alternative"];
            for (NSDictionary *transcript in altArray) {
                NSLog(@"transcript : %@",[transcript objectForKey:@"transcript"]);
            }
        }

    } else {
        NSLog(@"Error in parsing JSON");
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM