如何将两个具有不同类型实体的数组合并为一个json对象?

时间:2022-05-02 08:24:39

I have two arrays in objective C. Their data structures are as follows:

我在目标C中有两个数组。他们的数据结构如下:

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

and

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

My task is putting these two arrays into one json NSData object. Meanwhile, in the json data, I should assign the name "People" to the first type of array entities, and "Car" to the second type of array entities, so later on on the php side, I should be able to tell which is which and put them into different tables respectively. Could you help me find the right way to generate the desired json object?

我的任务是将这两个数组放入一个json NSData对象中。同时,在json数据中,我应该将名称“People”分配给第一类数组实体,将“Car”分配给第二类数组实体,所以稍后在php端,我应该能够分辨是哪个并分别将它们放入不同的表中。你能帮我找到生成所需json对象的正确方法吗?

2 个解决方案

#1


2  

You can take your two arrays and then build a new dictionary with two keys, people and cars, using your two arrays as the values associated with those two keys. For example:

您可以使用两个数组,然后使用两个键(人员和汽车)构建一个新字典,使用两个数组作为与这两个键相关联的值。例如:

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];

The resulting JSON (formatted so you can read it more easily) would look like:

生成的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"
    }
  ]
}

To send that request, you could do something like the following:

要发送该请求,您可以执行以下操作:

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];

And in PHP, to parse this response you can do something like:

在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);

?>

#2


0  

In PHP you can combine the 2 jsons like the following

在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);

Output:

输出:

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"}]}

if you want to print the output of the json string you can use JSON_PRETTY_PRINT option for json_encode

如果要打印json字符串的输出,可以使用JSON_PRETTY_PRINT选项为json_encode

$combined_json = json_encode($combined_array, JSON_PRETTY_PRINT);

#1


2  

You can take your two arrays and then build a new dictionary with two keys, people and cars, using your two arrays as the values associated with those two keys. For example:

您可以使用两个数组,然后使用两个键(人员和汽车)构建一个新字典,使用两个数组作为与这两个键相关联的值。例如:

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];

The resulting JSON (formatted so you can read it more easily) would look like:

生成的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"
    }
  ]
}

To send that request, you could do something like the following:

要发送该请求,您可以执行以下操作:

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];

And in PHP, to parse this response you can do something like:

在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);

?>

#2


0  

In PHP you can combine the 2 jsons like the following

在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);

Output:

输出:

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"}]}

if you want to print the output of the json string you can use JSON_PRETTY_PRINT option for json_encode

如果要打印json字符串的输出,可以使用JSON_PRETTY_PRINT选项为json_encode

$combined_json = json_encode($combined_array, JSON_PRETTY_PRINT);