2

I am new to ios development. i have a json that looks like

{"result":[]}
{"result":[{"alternative":[{"transcript":"free","confidence":0.63226712},{"transcript":"we"}],"final":true}],"result_index":0} 

my coding part

- (BOOL)didReceiveVoiceResponse:(NSData *)data
{
//    NSLog(@"data :%@",data);
//    NSError *jsonError = nil;
////
  NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
 NSLog(@"responseString: %@",responseString);



    NSData *data1 = [responseString dataUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"data1: %@",data1);

    NSData *data2 = [responseString dataUsingEncoding:NSUTF8StringEncoding];
    id json = [NSJSONSerialization JSONObjectWithData:data2 options:0 error:nil];
        NSLog(@"====%@",json);
    NSLog(@"%@",[json objectForKey:@"result"]);

console log

2016-05-06 09:55:34.909 SpeechToTextDemo[79631:2980023] responseString: {"result":[]}
{"result":[{"alternative":[{"transcript":"free","confidence":0.63226712},{"transcript":"we"}],"final":true}],"result_index":0}
2016-05-06 09:55:34.909 SpeechToTextDemo[79631:2980023] data1: <7b227265 73756c74 223a5b5d 7d0a7b22 72657375 6c74223a 5b7b2261 6c746572 6e617469 7665223a 5b7b2274 72616e73 63726970 74223a22 66726565 222c2263 6f6e6669 64656e63 65223a30 2e363332 32363731 327d2c7b 22747261 6e736372 69707422 3a227765 227d5d2c 2266696e 616c223a 74727565 7d5d2c22 72657375 6c745f69 6e646578 223a307d 0a>
2016-05-06 09:55:34.909 SpeechToTextDemo[79631:2980023] ====(null)
2016-05-06 09:55:34.910 SpeechToTextDemo[79631:2980023] (null)

kindly find my coding part and console log above. please guide me how to resolve this think. i want to tanscript values. how to get this value. thanks

Raj
  • 485
  • 9
  • 18
  • 1
    Use the `error` parameter. – vadian May 06 '16 at 04:45
  • {"result":[{"alternative":[{"transcript":"free","confidence":0.63226712},{"transcript":"we"}],"final":true}],"result_index":0} is it full response string ? – Prashant Tukadiya May 06 '16 at 05:04
  • @pkt thanks. how to resolve this error. i want to get transcript values – Raj May 06 '16 at 05:08
  • i think you need to add "\" before and after keys and values. Like this http://stackoverflow.com/questions/8606444/how-do-i-deserialize-a-json-string-into-an-nsdictionary-for-ios-5. otherwise it shouldn't be a json string – Smit Shah May 06 '16 at 05:13
  • i have checked your answer bro but still now json and result values will be null. – Raj May 06 '16 at 05:14
  • @Raj As was stated earlier, make use of the `error` parameter to the call to `JSONObjectWithData`. When `json` comes back as `nil`, log `error` and it will tell you the problem. Update your question with the log output of the error. – rmaddy May 06 '16 at 05:18
  • @Rmady i have try to implement speech to text in ios app. once i say one or two it will be coming following type of speech response to google speech api. "result":[{"alternative":[{"transcript":"one","confidence":0.63226712},{"trans‌​cript":"we"}],"final":true}],"result_index":0} – Raj May 06 '16 at 05:25
  • now i am try to implement filter speech particular word like one and two.@rmaddy – Raj May 06 '16 at 05:27

8 Answers8

4

Your response is not in proper json format. First add the below line to remove the extra empty result string by following line:

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

Then, Try out the below code:

    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");
    }
Dinesh
  • 1,137
  • 9
  • 14
  • Don't just post code. Explain what was wrong with the code in the question and explain how your answer fixes the issue. – rmaddy May 06 '16 at 05:15
  • @Raj just add responseString = [responseString stringByReplacingOccurrencesOfString:@"{\"result\":[]}" withString:@""]; to remove extra empty result string from response. And then convert it into NSData. – Dinesh May 06 '16 at 05:50
  • @Microprocessor8085 {"result":[{"alternative":[{"transcript":"5"},{"transcript":"v"},{"transcript":"five"}],"final":true}],"result_index":0} 2016-05-06 11:16:50.493 SpeechToTextDemo[88576:3054271] transcript : 5 thanks you very much for your help. it help me a lot. once again thanks. it will be working good. thanks lot – Raj May 06 '16 at 05:51
0

use this code it will help you to convert your Response string

NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];

after getting values add received values in Dictionary then use it according to your need

0
NSData *data = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"data1: %@",data);

NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSLog(@"Result = %@", dict);

if (error == nil) {

    if([dict valueForKey:@"result"]) {

        NSLog(@"%@", [[dict valueForKey:@"result"] objectAtIndex:0]);

        //you need to do loop to get all transcript data
        //NSArray *array = [[[dict valueForKey:@"result"] objectAtIndex:0] valueForKey:@"alternative"];

        NSString *transcript = [[[[[dict valueForKey:@"result"] objectAtIndex:0] valueForKey:@"alternative"] objectAtIndex:1] valueForKey:@"transcript"];

        NSLog(@"transcript = %@", transcript);
    }

} else {
    NSLog(@"Error = %@",error);
}

I hope it will help you.

Mahendra
  • 8,448
  • 3
  • 33
  • 56
  • i have added your coding but app will be forcecolsed @Richard – Raj May 06 '16 at 05:00
  • error : SpeechToTextDemo[83330:3010284] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array' *** First throw call stack: ( – Raj May 06 '16 at 05:00
  • @Raj please try out my answer. – Dinesh May 06 '16 at 05:02
  • Don't just post code. Explain what was wrong with the code in the question and explain how your answer fixes the issue. – rmaddy May 06 '16 at 05:15
0

You already have data as a parameter in your function

then why you convert it to string and back to data again

- (BOOL)didReceiveVoiceResponse:(NSData *)data
{
//    NSLog(@"data :%@",data);
//    NSError *jsonError = nil;
   NSError *error;

   NSDictionary  *json = [NSJSONSerialization JSONObjectWithData:data options:0  error:&error];
if (error == nil) {
    // no error
 NSLog(@"====%@",json);
 NSLog(@"%@",[json objectForKey:@"result"]);
} else {
    NSLog(@"error");
}

}
Prashant Tukadiya
  • 15,838
  • 4
  • 62
  • 98
0

try this may be it will help you-

 NSData* jsonData = [yourJsonString dataUsingEncoding:NSUTF8StringEncoding];


    NSError *error = nil;
   NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSLog(@"Result = %@", dict);

    if(! error) {
        NSArray *Array1 = [dict objectForKey:@"result"];
//now you will go inside dict having key "result"
        for (NSDictionary *dict2 in Array1) {
            NSArray *Array2 = [dict2 objectForKey:@"result"];
            for (NSDictionary *dict3 in Array2) {
                NSArray *array3 = [dict3 objectForKey:@"alternative"]);
for(NSDictionary *dict4 in array3)
NSLog(@"transcript--",[dict4 objectForKey:@"transcript"]);
            }
        }

    } else {
        NSLog(@"Error");
    }
  • Don't just post code. Explain what was wrong with the code in the question and explain how your answer fixes the issue. – rmaddy May 06 '16 at 05:15
  • I'm offering helpful advice on how to post useful answers. A good answer explains things. It will better help future readers of your answer. You will get more up votes by writing a better answer. – rmaddy May 06 '16 at 06:13
0

your json string is not well formatted:

{"result":[]}
{"result":[{"alternative":[{"transcript":"free","confidence":0.63226712},    {"transcript":"we"}],"final":true}],"result_index":0}

this indicate that the two items should be in a array, but in you json string, they stand alone.

[
    {"result":[]},
    {"result":[{"alternative":[{"transcript":"free","confidence":0.63226712},{"transcript":"we"}],"final":true}],"result_index":0}
]

your code is ok, you can pass an error object into [NSJSONSerialization JSONObjectWithData:data2 options:0 error:nil]; to know what's the matter.

Frog Tan
  • 79
  • 4
  • i have tested bro. still it will be null. i dont know how to resolve this. please guide – Raj May 06 '16 at 05:35
0

You have to use Object Class(Model Class) generator tool for iOS and Android both, just copy and paste your response and get Object Class from tool.

Its my Duplicate answer for my question but it's very useful.visit my question here

  • Download JSON Accelerator from AppStore (Mac AppStore).
  • Copy your JSON Responce from browser.(responce must be JSON Validated).

  • paste in Json Accelerator >> Click Generate and Save With Your Modelname.

  • Select Output language and add base Class name.(Class Prefix Not Required)
  • See Below Generated Model Classes and SubModel Classe (It automatically generates All JSON Object Classes)


Use Like This >>> For Example Your JSON Respoce Dictionary is

{"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}
  • make Employee Array and then create Object With Created Model Classes like below code and you have to use For loop or enumerateObjectsUsingBlock any one for create and then Add in Mutable Array.

    NSArray *arrTemp = [NSArray arrayWithArray:yourResponceDict[@"employees"]];
    NSMutableArray *myMutableArray = [NSMutableArray array];
    
    [arrTemp enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        Employee *aObj = [Employee modelObjectWithDictionary:obj];
        [myMutableArray addObject:aObj];
    }];
    

This Tool is Very easy and Time Saving For Creating Json Object Classes for parsing data anywhere in Development.

Community
  • 1
  • 1
Vvk
  • 4,031
  • 29
  • 51
  • I doubt the OP is getting JSON response from browser or if he wants to paste it into a mac app. Rather he is getting the response from a backend API and he simply wants to parse it into a Dictionary and later use it in his iOS App. Your answer is invalid and based on a wrong assumption – NSNoob May 06 '16 at 05:59
  • Whenever in doubt, ask the OP about his intents in comments section. – NSNoob May 06 '16 at 05:59
  • @NSNoob we have to do this process first time when we create object. then we have to manage from creared object – Vvk May 06 '16 at 06:28
  • No you can process and manage it within the app without any need to to include some weird unfeasible dependency on browser, mac OS and external tools. I don't know why do you think that is how iOS Apps work – NSNoob May 06 '16 at 08:05
0

Try this code

- (BOOL)didReceiveVoiceResponse:(NSData *)data
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
        NSLog(@"Dict=%@",dict);
}
Atanu Mondal
  • 1,714
  • 1
  • 24
  • 30