json输出中的MongoDB对象id问题


MongoDB object id issue in json output

I使用必须通过PHPMongoDB读取一些数据。当我将MongoDB结果转换为Json时,我得到如下结果:

{    
    "records":
    [            
        {
            "_id":
            {
                "id": "567f18f21e2e328206d3d91e"
            },
            "title": "test",
            "price": 5000,
            "date": "1394-09-05 11:30",
            "images":
            [
                {
                    "_id":
                    {
                        "id": "567f18f21e2e328206d3d91f"
                    },
                    "url": "a"
                },
                {
                    "_id":
                    {
                        "id": "567f18f21e2e328206d3d920"
                    },
                    "url": "x"
                },
                {
                    "_id":
                    {
                        "id": "567f18f21e2e328206d3d921"
                    },
                    "url": "c"
                }
            ]
        }
    ]
}

正如你所看到的,我们有一个如下的id:

"_id":
 {
     "$id": "567f18f21e2e328206d3d91e"
  },

当我想用Java解析这个json时,它给我带来了一些问题,我想把它转换成这样的东西:

{    
    "records":
    [
        {
            "id": "567f18f21e2e328206d3d91e"           
            "title": "test",
            "price": 5000,
            "date": "1394-09-05 11:30",
            "images":
            [
                {
                    "id": "567f18f21e2e328206d3d91f",
                    "url": "a"
                },
                {
                    "id": "567f18f21e2e328206d3d920",
                    "url": "x"
                },
                {
                    "id": "567f18f21e2e328206d3d921",
                    "url": "c"
                }
            ]
        }
    ]
}

我该怎么做
我不能使用foreach方法来编辑这个数组,因为我有无限的子数组

首先解码json数据并将其转换为数组。从转换后的数组中,您可以格式化所需的模式。array_map可以帮助你。

$data = json_decode($old_json_data, true);
$new_data_format = [];
if(isset($data['records'])){
    $data = $data['records'];
    $new_data_format = array_map(function($val){
        return [
            'id' => $val['_id']['id'],
            'title' => $val['title'],
            'price' => $val['price'],
            'date' => $val['date'],
            'images' => array_map(function($v){
                return [
                    'id' => $v['_id']['id'],
                    'url' => $v['url'],
                ];
            }, $val['images'])
        ];
    }, $data);
}
$new_data_format = json_encode(['records' => $new_data_format]);

希望它能帮助你。