2015-12-26 27 views
4

我有客觀C.兩個數組他們的數據結構如下:如何將兩個數組與不同類型的實體組合成一個json對象?

{"index":"1","lastName":"Brown","firstName":"Kathy","company":"ABC inc."}, 
{"index":"2","lastName":"Smith","firstName":"Mike","company":"XYZ inc."} 

{"index":"1","make":"Toyota","model":"RAV4","year":"2009"}, 
{"index":"2","make":"Honda","model":"Pilot","year":"2012"} 

我的任務是把這兩個數組到一個JSON NSData對象。同時,在json數據中,我應該將名稱「People」分配給第一種數組實體,將「Car」分配給第二種數組實體,所以稍後在PHP一側,我應該能夠分辨出哪些是哪個並分別放在不同的表格中。你能幫我找到正確的方法來生成所需的json對象嗎?

+0

請分享您的代碼。請在密鑰中提供所提到的關鍵字詞典,並將這些數組放入相應的鍵中。 –

+0

顯示最終的數組結果。 – jitendrapurohit

回答

2

你可以把你的兩個數組,然後建立一個新的字典與兩個鍵,peoplecars,使用你的兩個數組作爲與這兩個鍵相關聯的值。例如:

NSArray *people = @[@{@"index":@"1",@"lastName":@"Brown",@"firstName":@"Kathy",@"company":@"ABC inc."}, 
        @{@"index":@"2",@"lastName":@"Smith",@"firstName":@"Mike",@"company":@"XYZ inc."}]; 

NSArray *cars = @[@{@"index":@"1",@"make":@"Toyota",@"model":@"RAV4",@"year":@"2009"}, 
        @{@"index":@"2",@"make":@"Honda",@"model":@"Pilot",@"year":@"2012"}]; 

NSDictionary *fullDictionary = @{@"people": people, @"cars": cars}; 

NSError *error; 
NSData *data = [NSJSONSerialization dataWithJSONObject:fullDictionary options:0 error:&error]; 

產生的JSON(格式化,以便您可以更輕鬆地閱讀它)看起來像:

{ 
    "cars" : [ 
    { 
     "model" : "RAV4", 
     "year" : "2009", 
     "make" : "Toyota", 
     "index" : "1" 
    }, 
    { 
     "model" : "Pilot", 
     "year" : "2012", 
     "make" : "Honda", 
     "index" : "2" 
    } 
    ], 
    "people" : [ 
    { 
     "lastName" : "Brown", 
     "firstName" : "Kathy", 
     "company" : "ABC inc.", 
     "index" : "1" 
    }, 
    { 
     "lastName" : "Smith", 
     "firstName" : "Mike", 
     "company" : "XYZ inc.", 
     "index" : "2" 
    } 
    ] 
} 

要發送請求時,你可以不喜歡以下內容:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
request.HTTPBody = data; 
request.HTTPMethod = @"POST"; 

NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
    // check for fundamental networking error (e.g. not connected to Internet) 

    if (error) { 
     NSLog(@"error = %@", error); 
     return; 
    } 

    // also check to see if the server reported some HTTP error 

    if ([response isKindOfClass:[NSHTTPURLResponse class]]) { 
     NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode]; 
     if (statusCode != 200) { 
      NSLog(@"statusCode = %ld", (long)statusCode); 
      return; 
     } 
    } 

    // OK, if we've gotten here, let's parse the response; I'm assuming you'll send JSON response; so parse it 

    NSError *parseError; 
    NSDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError]; 
    if (parseError) { 
     NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
     NSLog(@"responseString = %@", responseString); 
    } else { 
     NSLog(@"responseObject = %@", responseObject); 
    } 
}]; 
[task resume]; 

而且在PHP,解析這個響應,你可以這樣做:

<?php 

header("Content-Type: application/json"); 

$handle = fopen("php://input", "rb"); 
$raw_post_data = ''; 
while (!feof($handle)) { 
    $raw_post_data .= fread($handle, 8192); 
} 
fclose($handle); 

$json_data = json_decode($raw_post_data, true); 

$people = $json_data["people"]; 
$cars = $json_data["cars"]; 

foreach ($people as $person) { 
    $index  = $person["index"]; 
    $last_name = $person["lastName"]; 
    $first_name = $person["firstName"]; 
    $company = $person["company"]; 

    // use these four variables to insert row of data here; note, make sure you either use 
    // `mysqli::real_escape_string` or that you manually bind these values to `?` placeholders 
} 

foreach ($cars as $car) { 
    $index = $car["index"]; 
    $make = $car["make"]; 
    $model = $car["model"]; 
    $year = $car["year"]; 

    // again, use these four variables to insert row of data here; note, make sure you either use 
    // `mysqli::real_escape_string` or that you manually bind these values to `?` placeholders 
} 

// obviously, if we had errors above, we'd send something like Array("success" => false, ...) with error messages and error codes 
$response = Array("success" => true); 
echo json_encode($response); 

?> 
0

在PHP中你可以結合2個jsons像下面

$j1 = '[{"index":"1","lastName":"Brown","firstName":"Kathy","company":"ABC inc."}, 
    {"index":"2","lastName":"Smith","firstName":"Mike","company":"XYZ inc."}]'; 

$j2 = '[{"index":"1","make":"Toyota","model":"RAV4","year":"2009"}, 
    {"index":"2","make":"Honda","model":"Pilot","year":"2012"}]'; 

$combined_array = array("People"=>json_decode($j1, true)) + array("Cars"=>json_decode($j2, true)); 
$combined_json = json_encode($combined_array); 

print_r($combined_array); 
print_r($combined_json); 

輸出:

Array 
(
    [Peolpe] => Array 
     (
      [0] => Array 
       (
        [index] => 1 
        [lastName] => Brown 
        [firstName] => Kathy 
        [company] => ABC inc. 
       ) 

      [1] => Array 
       (
        [index] => 2 
        [lastName] => Smith 
        [firstName] => Mike 
        [company] => XYZ inc. 
       ) 

     ) 

    [Cars] => Array 
     (
      [0] => Array 
       (
        [index] => 1 
        [make] => Toyota 
        [model] => RAV4 
        [year] => 2009 
       ) 

      [1] => Array 
       (
        [index] => 2 
        [make] => Honda 
        [model] => Pilot 
        [year] => 2012 
       ) 

     ) 

) 
{"Peolpe":[{"index":"1","lastName":"Brown","firstName":"Kathy","company":"ABC inc."}, 
    {"index":"2","lastName":"Smith","firstName":"Mike","company":"XYZ inc."}], 
"Cars":[{"index":"1","make":"Toyota","model":"RAV4","year":"2009"}, 
    {"index":"2","make":"Honda","model":"Pilot","year":"2012"}]} 

,如果你要打印的JSON字符串的輸出,你可以使用JSON_PRETTY_PRINT選項json_encode

$combined_json = json_encode($combined_array, JSON_PRETTY_PRINT); 
相關問題