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

8
  • 1
    Use the error parameter. Commented May 6, 2016 at 4:45
  • {"result":[{"alternative":[{"transcript":"free","confidence":0.63226712},{"transcript":"we"}],"final":true}],"result_index":0} is it full response string ? Commented May 6, 2016 at 5:04
  • @pkt thanks. how to resolve this error. i want to get transcript values Commented May 6, 2016 at 5:08
  • i think you need to add "\" before and after keys and values. Like this stackoverflow.com/questions/8606444/…. otherwise it shouldn't be a json string Commented May 6, 2016 at 5:13
  • i have checked your answer bro but still now json and result values will be null. Commented May 6, 2016 at 5:14

8 Answers 8

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");
    }
Sign up to request clarification or add additional context in comments.

3 Comments

Don't just post code. Explain what was wrong with the code in the question and explain how your answer fixes the issue.
@Raj just add responseString = [responseString stringByReplacingOccurrencesOfString:@"{\"result\":[]}" withString:@""]; to remove extra empty result string from response. And then convert it into NSData.
@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
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

2 Comments

i have added your coding but still it will be null @abhinandan
This doesn't help. The OP already has the NSData. That's not the problem.
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.

4 Comments

i have added your coding but app will be forcecolsed @Richard
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 please try out my answer.
Don't just post code. Explain what was wrong with the code in the question and explain how your answer fixes the issue.
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");
}

}

3 Comments

@ pkt i have tested your code. but still it will be null. please guide
2016-05-06 10:41:15.858 SpeechToTextDemo[84733:3022050] ====(null) 2016-05-06 10:41:15.858 SpeechToTextDemo[84733:3022050] (null)
now the possible issue is with your response string
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");
    }

2 Comments

Don't just post code. Explain what was wrong with the code in the question and explain how your answer fixes the issue.
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.
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.

1 Comment

i have tested bro. still it will be null. i dont know how to resolve this. please guide
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.

4 Comments

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
Whenever in doubt, ask the OP about his intents in comments section.
@NSNoob we have to do this process first time when we create object. then we have to manage from creared object
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
0

Try this code

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.