JSON and NSDictionary

Discussion in 'iOS Programming' started by mngoose, Jun 1, 2012.

  1. mngoose, Jun 1, 2012
    Last edited: Jun 2, 2012

    mngoose macrumors member

    Joined:
    May 26, 2012
    #1
    Greetings all,

    I am really new to IPHone coding (I use android programming mostly but have delved into the world of Apple now)

    Here is what I am looking to do

    Use inputs specific variables that they setup on my server then go get the app.
    When they run the app they put in the same variables into the phone and push a button to get the infromation that they are allowed to under their specific varialbes which the PHP file creates (I know that it works because the android app is working just fine)...

    I can see the JSON string in the variable that I have setup through NSLog strings and the results are stored in an NSString variable that is identified and available.

    What I need to know now is to how to input it in a NSDictionary and then parse out the JSON once the button is pushed

    I have tried over 300 variations of things that I have found on the web and I am beating my head against the wall for three days straight on this.

    Anyone have any suggestions for me?

    I am also having significant problems inputing things like SBJSON and JSON.h into my fiels and I could use some help with that as well

    Thanks
    John

    Code:
    - (IBAction)retrieve : (id) sender {
        PhoneText = PhoneTextField.text;
        PinText   = PinTextField.text;
        ConfirmText = ConfirmTextField.text;
        NSLog (@"%@", PhoneText);
        NSLog (@"%@", PinText);
        NSLog (@"%@", ConfirmText);
        NSString *strURL = [NSString stringWithFormat:@"http://x.x.x.x/order/mobile.php?Fone=%@&pincode=%@&confirm=%@&edit=Register", PhoneText, PinText,ConfirmText ];
        
        NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString : strURL]];
        
        NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
        NSLog (@"%@", strURL);
        NSLog (@"Result = %@", strResult);
        
        NSDictionary *RetorderTicket = [[[NSDictionary alloc] initWithObjectsAndKeys:strResult @"id", 
                                    @"firstname",
                                   @"lastname",
                                   @"phonenumber",
                                   @"companycode",
                                   @"email",
                                   @"confirmationcode",
                                   @"part",
                                   @"desc",
                                   @"price",
                                   @"retrieved",
                                   @"sku",
                                   @"item"
                                   @"itemimg",
                                   @"salesperson",
                                   @"companyimg",
                                   @"datetime",
                                   @"location",
                                   @"count",
                                   nil];
        NSLog (@"%@", RetorderTicket);
     
  2. xStep macrumors 68000

    Joined:
    Jan 28, 2003
    Location:
    Less lost in L.A.
    #2
    Well first you need to supply the entire NSLog result of strResult. We don't know what it actually looks like.

    Based on your attempt to populate the dictionary I suspect the line of interest is an array and it looks something like the following ;
    Code:
    ["value1","value2","value3"]
    Perhaps strResult is an entire HTML page with headers and footers. If so, then you have some parsing to do to get to the JSON line.

    I don't see any NSDictionary methods that deal with either of those scenarios. A sting that contains a list is not a list of objects which is what NSDictionary methods deal with.

    I suspect you want to look at using NSJSONSerialization. Review the following little test I did.
    Code:
        NSError * localError = nil;
        //NSString * mystr = @"{\"myarray\":[\"value1\",\"value2\",\"value3\"]}"; // <-- JSON Dictionary
        NSString * mystr = @"[\"value1\",\"value2\",\"value3\"]"; <-- JSON Array
        NSLog(@"mystr: %@", mystr);
        
        NSData * data = [mystr dataUsingEncoding: NSUTF8StringEncoding];
        NSLog(@"data: %@", data);
        
        NSMutableArray * myConvertedJSONData = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &localError];
        if (localError == nil)
            NSLog(@"myConvertedJSONData: %@", myConvertedJSONData);
        else {
            NSLog(@"json error: %@", [localError userInfo]);
        }

    Given a valid array of values, the way to populate a dictionary is like this.
    Code:
        NSDictionary * dict1 = [[NSDictionary alloc] initWithObjects: myConvertedJSONData forKeys: [NSArray arrayWithObjects: @"key1", @"key2", @"key3", @"key4", nil]];
        NSLog(@"dict1: %@", dict1);
    
    Given an array with key value pairs you'll want something like this. It's up to you to check that there an even number of entries in the array.
    Code:
    NSMutableDictionary * dict2 = [[NSMutableDictionary alloc] initWithCapacity: [myConvertedJSONData count]];
    for (NSInteger iterator = 0; iterator < [myConvertedJSONData count]; iterator = iterator + 2) {
            [dict2 setObject: [myConvertedJSONData objectAtIndex: iterator] forKey:[myConvertedJSONData objectAtIndex: iterator + 1]];
        } 
    NSLog(@"dict2: %@", dict2);
    
     
  3. mngoose, Jun 2, 2012
    Last edited: Jun 2, 2012

    mngoose thread starter macrumors member

    Joined:
    May 26, 2012
    #3
    thanks for the reply.

    Code:
    NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString : strURL]];
        
        NSString *strResult = [[NSString alloc] initWithData:dataURL    encoding:NSUTF8StringEncoding];
        NSLog (@"%@", strURL);
        NSLog (@"Result = %@", strResult);
        NSArray *jsonStr = strResult; 
        NSLog (@"jsonstr = %@", jsonStr);
        NSObject *json2 = strResult;
    
    
    and here is the result of strResult - Eventually this will be placed on the screen but that will be another days work.
    
    Result = [{"id":"1","firstname":"John","lastname":"Schimanski","phonenumber":"9093768439","companycode":"195300","pincode":"12345678","email":"test@gmail.com","confirmationcode":"12345","part":"tire","desc":"truck tire","price":"$12.00","retrieved":"no","sku":"154784596124","item":"three","itemimg":"tire.png","salesperson":"name","companyimg":"icon.png","datetime":"2013-01-01 19:00:00","location":"Las Vegas","count":"155"}]
    

    When I look at the NSDictionary variable it looks almost the same but with every field surround with \ for example \"id\"

    thanks
    John
     
  4. xStep macrumors 68000

    Joined:
    Jan 28, 2003
    Location:
    Less lost in L.A.
    #4
    First, please fix you CODE tags.

    Place the following code right after your assignment to strResult. By the way, I don't think you need to assign your NSData value to the string as you likely can use your dataURL where I use my datajson below my assignment of it. Oh, the name, dataURL is misleading to. That indicated to me an NSURL type. A better name might be dataURLFetchResult.

    Code:
        NSData * datajson = [strResult dataUsingEncoding: NSUTF8StringEncoding];
    
        id my2ConvertedJSONData = [NSJSONSerialization JSONObjectWithData: datajson options: NSJSONReadingMutableContainers error: &localError];
        
        if ([my2ConvertedJSONData isKindOfClass:[NSDictionary class]]) {
            NSLog(@"DICTIONARY");
            NSLog(@"dict3: %@", my2ConvertedJSONData);
        }
        
        if ([my2ConvertedJSONData isKindOfClass:[NSArray class]]) 
        {
            NSArray * anArray = my2ConvertedJSONData;
            NSLog(@"ARRAY count: %i", [anArray count]);
            if ([[anArray objectAtIndex: 0] isKindOfClass:[NSDictionary class]]) NSLog(@"Yep, dictionary inside of an array!");
            NSLog(@"Array dict index 0: %@", [anArray objectAtIndex: 0]);
        }
    
    Based on what we've exchanged, I'd say you have the information you require to solve the problem.

    I'm no JSON expert, but I think your server is overworking the solution. There isn't a need for the dictionary to be in an array, unless there are more than one dictionary.
     
  5. mngoose thread starter macrumors member

    Joined:
    May 26, 2012
    #5
    xStep,

    First thanks for your help. As I said I'm new to this, and I did fix the CODE tags... Sorry about that...

    and that worked thanks for the help....
    John
     
  6. Ron C macrumors member

    Joined:
    Jul 18, 2008
    Location:
    Chicago-area
    #6
    Try SBJSON for JSON interactions. Already tested and free. I've used this before and it's pretty simple; I also have the sense that it's fairly widely used, but I have no data to back at up.

    A quick google search returns this page that seems helpful, which kinda makes me want to try out NSJSONSerialization.
     
  7. mngoose thread starter macrumors member

    Joined:
    May 26, 2012
    #7
    Ron,

    The solution that was given to me by xstep worked for what I needed it to do. I am sure that SBJSOn works well but I had problems importing it into my files (seriously new to IPHONE and xcode programming).

    As I understand it xcode and iphone layers already come with a json parser and it works well for what I need. I'll post the code later (not at my MAC right now) in order to take the values from the JSON and put it to the variables for you.

    John
     

Share This Page