如何从json中提取数字?

yc0p9oo0  于 2022-12-27  发布在  其他
关注(0)|答案(1)|浏览(208)

我想从一个json文件中提取一个特定的数组:

{
    "status": "OK",
    "type": "startVehicle",
    "info": {
        "idTransit": 36612,
        "timestampUTCTransit": {
            "epochUTCTransitMS": 1606935562810,
            "dateUTCTransit": "2020/12/2",
            "hourUTCTransit": "18:59:22.810"
        },
        "timestampUTCReported": {
            "epochUTCReportedMS": 1606935562810,
            "dateUTCReported": "2020/12/2",
            "hourUTCReported": "18:59:22.810"
        },
        "road": 0,
        "lane": 0,
        "xCoordinates": [
            143.6,
            -456.335
        ]
    }
}

我想提取x坐标的值。这是我尝试的:

#include <rapidjson/document.h>

void Vdac::addStart(std::string json_str)
{
    Document rjsondoc;

    rjsondoc.Parse(json_str.c_str());
    if(rjsondoc.HasParseError())
        slog.getLogger()->debug("Invalid json");
 
    else
    {              
        auto coordinates = rjsondoc["info"]["xCoordinates"].GetArray();

        for(SizeType i=0;i<coordinates.Size();i++)
            slog.getLogger()->debug("The start coordinates are: {0:d}",coordinates[i].GetInt());

        return;
    }
}

但是我在程序访问值的时候出现了一个错误,错误是:

../include/rapidjson/document.h:1737: int rapidjson::GenericValue<Encoding, Allocator>::GetInt() const [with Encoding = rapidjson::UTF8<>; Allocator = rapidjson::MemoryPoolAllocator<>]: Assertion `data_.f.flags & kIntFlag' failed.

如何提取值?

rdlzhqv9

rdlzhqv91#

不能给予你任何帮助与rapidjson。
但另一种方法是ThorsSerializer(注:我写的。所以你可以接受它)。但是它的设计很容易使用。不需要(或者很少)代码就可以把JSON解析成C++对象。
注意:如果您不想读取某个字段,只需将其删除。

#include <fstream>

#include "ThorSerialize/Traits.h"
#include "ThorSerialize/JsonThor.h"

struct TimeStamp
{
    long        epochUTCTransitMS;
    std::string dateUTCTransit;
    std::string hourUTCTransit;
};
// If you want to read a class then
// Add this declaration with the name of the class and the
// fields you want to read/write in JSON.
ThorsAnvil_MakeTrait(TimeStamp, epochUTCTransitMS, dateUTCTransit, hourUTCTransit);

struct Info
{
    long        idTransit;
    TimeStamp   timestampUTCTransit;
    TimeStamp   timestampUTCReported;
    int         road;
    int         lane;
    std::vector<double> xCoordinates;
};
ThorsAnvil_MakeTrait(Info, idTransit, timestampUTCTransit, timestampUTCReported, road, lane, xCoordinates);

struct Object
{
    std::string status;
    std::string type;
    Info        info;
};
ThorsAnvil_MakeTrait(Object, status, type, info);

int main()
{
    std::ifstream   data("pl1.data");

    Object      object;

    using ThorsAnvil::Serialize::jsonImporter;
    // jsonImporter to read or jsonExporter to write:
    data >> jsonImporter(object);

    std::cout << object.info.xCoordinates[0] << "\n";
}

易于通过brew安装:

> brew install thors-serializer

使用以下工具构建代码:

> g++ -std=c++17 <file>.cpp -lThorSerialize17 -lThorsLogging17

请注意,在新的M1机器上,您还需要-L /opt/homebrew/lib(仍在处理)。
github上的所有代码

相关问题