Converting NSArray -> JSON -> NSData -> PHP server ->JSON representation

后端 未结 3 1652
谎友^
谎友^ 2020-12-05 08:47

I am converting an Array of NSDictionaries to JSON data with the following...

Create my data...

NSMutableArray *arrayOfDicts = [[NSMutableArray alloc         


        
相关标签:
3条回答
  • 2020-12-05 09:03

    You can't send it this way. NSJSONSerialization is for iOS use. It is basically a plist. You will need a way to decode it on PHP and I doubt it exists. Instead, you need to send a JSON string. I am not sure what you mean by "leaves quotes around titles." What are they doing there in the first place? Can you verify your original JSON string here?

    0 讨论(0)
  • 2020-12-05 09:06

    Turns out I needed to do it like this:

    To Create My data:

    NSMutableArray *arrayOfDicts = [[NSMutableArray alloc] init];
    
    for (int i = 0; i < 2; i++) {
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                                      @"MySong", @"title",
                                      @"MyArtist", @"artist",
                                      nil];
        [arrayOfDicts addObject:dict];         
    }
     NSArray *info = [NSArray arrayWithArray:arrayOfDicts];
    

    And Sent it like this:

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:info 
              options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
        // Start request
        NSURL *url = [NSURL URLWithString:@"http://www.mywebsite.com/index.php"];
        ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
        [request setPostValue:jsonString forKey:@"songs"];
        [request setDelegate:self];
        [request startAsynchronous];
    

    The key was to convert the info to NSData, then to a JSON String which I sent to my server, not just sending the raw NSData.

    Thanks everyone for the help!

    0 讨论(0)
  • 2020-12-05 09:18

    <?php $array = json_decode($_POST['songs']); ?> should work.

    0 讨论(0)
提交回复
热议问题