1

I have a JSON like below (getting from an URL)-

{
action :getAllJournal;
data :{
    journalList :[{
            cancelled : F;
            "cust_code" : "700-T022";
            "journal_amount" : 2216;
            "journal_code" : "JV1603/001";
            "journal_date" : "2016-03-15 00:00:00";
            "journal_id" : 1;
            outstanding : 0;
        },
                    {
            cancelled : F;
            "cust_code" : "700-0380";
            "journal_amount" : 120;
            "journal_code" : "JV1605/006";
            "journal_date" : "2016-05-31 00:00:00";
            "journal_id" : 2;
            outstanding : 120;
        },
                    {
            cancelled : F;
            "cust_code" : "700-T280";
            "journal_amount" : 57;
            "journal_code" : "JV1609/001";
            "journal_date" : "2016-09-22 00:00:00";
            "journal_id" : 3;
            outstanding : 0;
        }
    ];
};
message = "";
"message_code" = "";
result = 1;}

The code below doing is getting the JSON from URL and storing them in NSMutableArray. Until storing them into array, it's working fine but I'm bit confused with the JSON format and don't know how to get result by a key.

__block NSMutableArray *jsonArray = nil;
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
NSString *urlString = [NSString stringWithFormat:@"http://xxxxxxx/api.php?action=getAllJournal"];
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * response, NSData * data, NSError * connectionError)
 {
     if (data)
     {
         id myJSON;
         @try {
             myJSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
         }
         @catch (NSException *exception) {
         }
         @finally {
         }
         jsonArray = (NSMutableArray *)myJSON;

         NSString *nsstring = [jsonArray description];
         NSLog(@"IN STRING -> %@",nsstring);

         NSData *data = [nsstring dataUsingEncoding:NSUTF8StringEncoding];
         NSError *jsonError;
         NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
         if(jsonObject !=nil){

             if(![[jsonObject objectForKey:@"journalList"] isEqual:@""]){

                 NSMutableArray *array=[jsonObject objectForKey:@"journalList"];

                 NSLog(@"array: %lu",(unsigned long)array.count);

                 int k = 0;
                 for(int z = 0; z<array.count;z++){

                     NSString *strfd = [NSString stringWithFormat:@"%d",k];
                     NSDictionary *dicr = jsonObject[@"journalList"][strfd];
                     k=k+1;
                     // NSLog(@"dicr: %@",dicr);
                     NSLog(@"cust_code - journal_amount   : %@ - %@",
                           [NSMutableString stringWithFormat:@"%@",[dicr objectForKey:@"cust_code"]],
                           [NSMutableString stringWithFormat:@"%@",[dicr objectForKey:@"journal_amount"]]);
                 }

             }

         }else{
             NSLog(@"Error - %@",jsonError);
         }

     }
 }];

From this, I am able to get the JSON successfully. But it's always giving me this error: Error Domain=NSCocoaErrorDomain Code=3840 "No string key for value in an object around character 6." UserInfo={NSDebugDescription=No string key for value in an object around character 6.} How can I get all values from journalList? I'm new to iOS, that's why not sure what I'm missing.

8
  • You can create a model class for journalist and then use libs like github.com/stig/json-framework that will help you easily parse jsons to objects Commented Aug 3, 2017 at 9:09
  • Your JSON is invalid. Fix it check your json here : jsonlint.com Commented Aug 3, 2017 at 9:15
  • @kapsym I'm not willing to use any libs right now..is there any possible ways of doing that without using libs? Commented Aug 3, 2017 at 9:15
  • 1
    may be your json serialization is not getting the right json format. could you tell exactly where your code getting this error. Commented Aug 3, 2017 at 9:17
  • 1
    NSString *nsstring = [jsonArray description]; NSLog(@"IN STRING -> %@",nsstring); NSData *data = [nsstring dataUsingEncoding:NSUTF8StringEncoding]; No and No. NSArray *journalList = myJSON[@"data"][@"journalList"], and that's an array of dictionaries. Commented Aug 3, 2017 at 9:41

6 Answers 6

3
id myJSON;
 @try {
     myJSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
 }
 @catch (NSException *exception) {
 }
 @finally {
 }
 jsonArray = (NSMutableArray *)myJSON;

 NSString *nsstring = [jsonArray description];
 NSLog(@"IN STRING -> %@",nsstring);

 NSData *data = [nsstring dataUsingEncoding:NSUTF8StringEncoding];
 NSError *jsonError;
 NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];

I'd say: NO and NO.

I wouldn't do a @try/@catch on a NSJSONSerialization, because the real issues are on the error parameter (and they won't throw a NSException for most of the cases). Just check if (data) is quite efficient.

Then, let's say it worked, and you have myJSON. In fact, myJSON is a NSDictionary, not a NSArray, so the cast is useless and doesn't make sense.

Next issue: Your are using -description (okay, if you want to debug), but you CAN'T use it to reconstruct AGAIN a JSON. It's not a valid JSON, it's the way the compiler "print" an object, it adds ";", etc. If your print [nsstring dataUsingEncoding:NSUTF8StringEncoding] and data you'll see that they aren't the same. For a more readable: NSString *dataJSONStr = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];, it's clearly not the same structure as your nsstring.

Then, you are redoing the JSON serialization? Why ?

So:

NSError *errorJSON = nil;
NSDictionary *myJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:&errorJSON];
if (errorJSON)
{
    NSLog(@"Oops error JSON: %@", errorJSON);
}
NSDictionary *data = myJSON[@"data"];
NSArray *journalList = data[@"journalList"]
for (NSDictionary *aJournalDict in journalList)
{
    NSUInteger amount = [aJournalDict[@"journal_amount"] integerValue];
    NSString *code = aJournalDict[@"journal_code"];
}
Sign up to request clarification or add additional context in comments.

Comments

1

There is a dictionary named "data" you're not fetching, represented by {}.

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

if (!jsonError) {

    // Fetch the journalList
    NSArray *journalList = json[@"data"][@"journalList"];

    // iterate over every entry and output the wanted values
    for (NSDictionary *journal in journalList) {
        NSLog(@"%@ %@", journal[@"cust_code"], journal[@"journal_amount"]);
    }
}

json[@"key"] is a short form of [json objectForKey:@"key"] I find easier to read.

1 Comment

Your approach is correct. I have already posted the correct ans and mentioned your name for credit ;)
0

That is not a valid JSON. Entries should be separated by comma ,, not semicolon ;

2 Comments

I copied that from console may be that's why showing ; .. but in the API, it's showing ,
Of course it's a string in the web API. What you printed is not JSON.
0

You need to fetch journalList from data.

Try below code:

This is demo code to create array like you:

NSMutableDictionary *jsonObject = [NSMutableDictionary new];
jsonObject[@"action"]= @"";
jsonObject[@"message"]= @"";
jsonObject[@"message_code"]= @"";
jsonObject[@"result"]= @"1";
NSMutableArray *ary1 = [NSMutableArray new];
for(int i=0;i<5;i++)
{
    NSMutableDictionary *dd = [NSMutableDictionary new];
    dd[@"cancelled"]= @"F";
    dd[@"cust_code"]= @"F";
    [ary1 addObject:dd];
}


NSMutableDictionary *dicjournal = [NSMutableDictionary new];
[dicjournal setObject:ary1 forKey:@"journalList"];
[jsonObject setObject:dicjournal forKey:@"data"];

This is main Logic:

NSMutableArray *journalList = [NSMutableArray new];
NSMutableDictionary *dic = [jsonObject valueForKey:@"data"];
journalList = [[dic objectForKey:@"journalList"] mutableCopy];

9 Comments

I'm getting this error Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArray0 objectForKey:]: unrecognized selector sent to instance 0x145487b0
Give me 2 mins. Let me create a JSON Object and give you solutins.
I created array like and fatch the journalList value.
json is not valid one how you re creating the datas then
@Vinodh you can print "jsonObject" object and compare.
|
0

Looks like your JSON is invalid. You can see whether your JSON is correct or not using http://jsonviewer.stack.hu/ and moreover format it. Meanwhile your code is not using "data" key to fetch "journalList" array.

Code : -

NSDictionary *dic = [jsonObject valueForKey:@"data"];

NSMutableArray *arr = [dic objectForKey:@"journalList"];

for (int index=0 ; index < arr.count ; index++){

NSDictionary *obj = [arr objectAtIndex:index];

// Now use object for key from this obj to get particular key 

}

Comments

0

Thanks @Larme and @Amset for the help. I was doing wrong the in the NSMutableArray part. The correct version of this code is in the below:

[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
NSString *urlString = [NSString stringWithFormat:@"http://xxxxxxx/api.php?action=getAllJournal"];
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * response, NSData * data, NSError * connectionError)
 {
     if (data)
     {
         id myJSON;
         @try {
             myJSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
         }
         @catch (NSException *exception) {
         }
         @finally {
         }

         NSArray *journalList = myJSON[@"data"][@"journalList"];
         for (NSDictionary *journal in journalList) {
             NSLog(@"%@ %@", journal[@"journal_date"], journal[@"journal_amount"]);
         }
     }
 }];

1 Comment

accept the answer so that others will know whats the problem you have faced

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.