在C++中创建一个json数组。

15

我正在尝试在C++中动态创建一个JSON对象。我想添加一个时间戳,然后是包含数据的数组。

那么这就是我的JSON字符串的样子:

{
    "timestep": "2160.00",
    "vehicles": [
        {
            "id": "35092_35092_353",
            "x": "6.988270",
            "y": "50.872139",
            "angle": "-20.812787",
            "type": "passenger_P_14_1",
            "speed": "0.000000",
            "pos": "4.600000",
            "lane": "4.600000",
            "slope": "4.600000"
        },
        {
            "id": "35092_35092_353",
            "x": "6.988270",
            "y": "50.872139",
            "angle": "-20.812787",
            "type": "passenger_P_14_1",
            "speed": "0.000000",
            "pos": "4.600000",
            "lane": "4.600000",
            "slope": "4.600000"
        },
        {
            "id": "35092_35092_353",
            "x": "6.988270",
            "y": "50.872139",
            "angle": "-20.812787",
            "type": "passenger_P_14_1",
            "speed": "0.000000",
            "pos": "4.600000",
            "lane": "4.600000",
            "slope": "4.600000"
        }
    ]
}

我完全是C++的新手,正在使用Casablanca(C++ REST SDK)包。因此,我很难编写代码,并且找不到任何可行的解决方案。我在维基百科上找到了这个:

创建一个JSON对象:

json::value obj;
obj[L"key1"] = json::value::boolean(false);
obj[L"key2"] = json::value::number(44);
obj[L"key3"] = json::value::number(43.6);
obj[L"key4"] = json::value::string(U("str"));

对我来说那很有效。但是我该如何创建一个数组呢?

我尝试了几个方法,但都没有成功。也许有更好的包可以使用?但据我所知,这是微软官方的用于JSON和HTTP的包。

求助会让我非常感激!

6个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
13

有2个机制。如果您习惯使用标准的C++库,这应该会很熟悉。Element vector 派生自 std::vector。

json::value::element_vector e;
// the first item in the pair is the array index, the second the value
e.push_back(std::make_pair(json::value(0), json::value(false)));
e.push_back(std::make_pair(json::value(1), json::value::string(U("hello"))));
json::value arr(e);

如果您喜欢更干净的外观,并且可以接受较低效的编译结果:

json::value arr;
arr[0] = json::value(false);
arr[1] = json::value(U("hello"));

从您的消息中可以看出,您已经尝试了很多方法。如果您尝试了这些机制但它们没有奏效,请提供一个演示失败的示例程序,我们会试着解决它。

要在您的文件中获取基本结构:

json::value vehicles;
vehicles[0] = // 1st vehicle object
vehicles[1] = // 2nd vehicle object
// etc
json::value root;
root[L"timestep"] = json::number(2160.0);
root[L"vehicles"] = vehicles;

如果我在我的代码中加入json::value::element_vector e;,就会得到一个错误,说element_vector不是json::value类的一部分。对于第二个解决方案,它说arr3未定义,这很有道理...那么arr3从哪里来? - Hannes
最新版本是2.0.1,我真的希望有一个高效的解决方案,因为这个JSON对象将被大量用于通信... - Hannes
关于您的第二条评论...您想解决什么问题?是为了让代码更加紧凑吗? - FatalFlaw
不像我之前发布的那样,我的JSON字符串中有多个数组条目,而不仅仅是一个。所以我想知道那会是怎么工作的。 - Hannes
已添加到上面的答案。 - FatalFlaw
显示剩余2条评论

7
这里是使用 vector 动态创建数组的方法。假设您需要添加10辆车。
std::vector<web::json::value> arrayVehicles;
for(int i = 0; i < 10; i++)
{
    web::json::value vehicle;
    std::string vehicleID = "id_prefix_" + std::to_string(i);
    vehicle["id"] = web::json::value::string(vehicleID);
    vehicle["x"] = web::json::value::number(6.988270);
    vehicle["y"] = web::json::value::number(50.872139);

    arrayVehicles.push_back(vehicle);
}

web::json::value myJSON;
myJSON["vehicles"] = web::json::value::array(arrayVehicles);

你能否编辑这段代码,使其动态地找到车辆的数量?我不知道“车辆”的总数,因此需要动态创建for循环的大小。 - Jolley71717

5
你可以这样表达:

你可以像这样放置:

json::value vehicle1;
vehicle1[L"id"] = json::value::string(L"35092_35092_353");
vehicle1[L"x"] = json::value::number(6.988270);
vehicle1[L"y"] = json::value::number(50.872139);

json::value vehicle2;
vehicle2[L"id"] = json::value::string(L"35092_35092_353");
vehicle2[L"x"] = json::value::number(1.23456);
vehicle2[L"y"] = json::value::number(6.78901);

json::value vehicles;
vehicles[L"timestamp"] = json::value::number(2160);
vehicles[L"vehicles"] = json::value::array({vehicle1, vehicle2});

1
但是有没有一种方法可以动态地将车辆添加到数组中呢?因为我不知道会有多少辆车... - Hannes
@Hannes:你可以使用向量来动态创建和存储车辆。 - Thanh-Nhon Nguyen

5

以下是在 Casablanca 中生成 JSON 数组的另一种方法:

int size = 3;
web::json::value yourJson;
yourJson[U("vehicles")] = web::json::value::array(size);

yourJson[U("vehicles")].as_array()[0] = web::json::value(U("some entry"));
yourJson[U("vehicles")].as_array()[1] = web::json::value(U("another entry"));
//...

0

如果您希望在接收到的 http_request(在下面的示例中为 http_request request)上将数组用作答案,可以使用以下代码片段作为示例:

    json::value answer;
    auto array = answer.array();

    for (size_t i = 0; i < GenFile.GetNumberOfCurves(); i++)
    {
        web::json::value vehicle;

        vehicle[L"smth"] = web::json::value::number(WhatEverArray[i].whatever());

        array[i] = vehicle;
    }

    request.reply(status_codes::OK, array);

GenFile.GetNumberOfCurves()是什么,它如何与WhatEverArray相连? - Jolley71717
@Jolley71717 抱歉,这段代码片段是从我的大学项目中获取的(带有一些更改)。您可以指定任何限制而不是 GenFile.GetNumberOfCurves(),并且可以使用任何数字值代替 WhatEverArray[i].whatever() - Dmitry

-1

下面这个字符串的 C++ 数组示例对我有效。

const char * const line_items_items =
"[\
    {\
        \"commodity_code\": \"44121903\",\
        \"description\": \"Miscellaneous goods\",\
        \"upc\": \"65100004327\",\
        \"quantity\": \"2\",\
        \"unit_of_measurement\": \"M62\",\
        \"unit_cost\": \"23.09\",\
        \"discount_amount\": \"10.03\",\
        \"total_amount\": \"50.03\",\
        \"tax_amount\": \"10.05\",\
        \"extended_amount\": \"76.04\",\
        \"debit_or_credit_indicator\": \"credit\",\
        \"net_or_gross_indicator\": \"net\"\
    },\
    {\
        \"commodity_code\": \"44121809\",\
        \"description\": \"Miscellaneous goods\",\
        \"upc\": \"65100007654\",\
        \"quantity\": \"4\",\
        \"unit_of_measurement\": \"M66\",\
        \"unit_cost\": \"35.09\",\
        \"discount_amount\": \"5.06\",\
        \"total_amount\": \"0.53\",\
        \"tax_amount\": \"8.07\",\
        \"extended_amount\": \"96.12\",\
        \"debit_or_credit_indicator\": \"debit\",\
        \"net_or_gross_indicator\": \"gross\"\
    }\
]";

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,