Converting C++ class to JSON

前端 未结 11 982
轮回少年
轮回少年 2020-12-02 11:56

I\'d like to create a JSON string containing the instance variables of my class.

For example,

class Example {  
    std::string string;  
    std::ma         


        
11条回答
  •  甜味超标
    2020-12-02 12:33

    If the question is still actual, then look at json_dto library, a small header-only helper for converting data between JSON representation and c++ structs.

    For example having the following structs:

    struct message_source_t
    {
      // Worker thread.
      std::int32_t m_thread_id;
    
      // Sender.
      std::string m_subsystem;
    };
    
    struct message_t
    {
      // Who sent a message.
      message_source_t m_from;
    
      // When the message was sent (unixtime).
      std::tm m_when;
    
      // Message text.
      std::string m_text;
    };
    

    with the help of json_dto you can create the following JSON:

    {
      "from" : 
        {
          "thread_id" : 4242,
          "sybsystem" : "json_dto"
        },
      "when" : "2016.09.28 19:55:00",
      "text" : "Hello world!"
    }  
    

    And given such JSON string you can convert it to structs.

提交回复
热议问题