yaron
0.01D
V2EX  ›  问与答

请教大佬一个 C++ 结构体与 json 转换的问题

  •  
  •   yaron · Dec 27, 2021 · 1387 views
    This topic created in 1607 days ago, the information mentioned may be changed or developed.

    之前依赖 rapidjson 写过结构体转 json 的工具,使用的方法主要是手动往结构体里加可变参数的宏,然后使用__VA_ARGS__进行成员遍历与赋值,具体的宏如下代码。

    但这会破坏原有的结构体,就想能不能在结构体外面进行注册。想问下有没有什么好的办法?

    /******************************************************
     * Register class or struct members
     * eg:
     * struct Test
     * {
     *      string A;
     *      string B;
     *      AIGC_JSON_HELPER(A, B)
     * };         
     ******************************************************/
    #define AIGC_JSON_HELPER(...)                                                            \
        std::map<std::string, std::string> __aigcDefaultValues;                              \
        bool AIGCJsonToObject(aigc::JsonHelperPrivate &handle,                               \
                              rapidjson::Value &jsonValue,                                   \
                              std::vector<std::string> &names)                               \
        {                                                                                    \
            std::vector<std::string> standardNames = handle.GetMembersNames(#__VA_ARGS__);   \
            if (names.size() <= standardNames.size())                                        \
            {                                                                                \
                for (int i = names.size(); i < (int)standardNames.size(); i++)               \
                    names.push_back(standardNames[i]);                                       \
            }                                                                                \
            return handle.SetMembers(names, 0, jsonValue, __aigcDefaultValues, __VA_ARGS__); \
        }                                                                                    
    
    2 replies    2021-12-28 09:10:36 +08:00
    wtfdsy
        1
    wtfdsy  
       Dec 27, 2021
    试试 https://github.com/nlohmann/json 这个?
    NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE 这个宏可以在结构体外部用
    yaron
        2
    yaron  
    OP
       Dec 28, 2021
    @wtfdsy 谢谢
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2567 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 15:59 · PVG 23:59 · LAX 08:59 · JFK 11:59
    ♥ Do have faith in what you're doing.