Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to convert Class structure and json in C++

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article is about how class structures and json convert each other in C++. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

1. Background and demand

When writing C # before, parsing json strings generally uses the open source class library Newtonsoft.Json, which is very concise, such as:

Class Project {public string Input {get; set;} public string Output {get; set;} JavaScriptSerializer serializer = new JavaScriptSerializer (); Project test = serializer.Deserialize (@ "{" Input ":" 1 "," Output ":" 2 "}")

A single line of code can convert the json string to the corresponding class object.

Recently, writing C++ needs to deal with json data, so I found a lot of powerful open source libraries on github, such as jsoncpp, rapidjson, json, which basically meet the development needs, but if you want to be like writing C #, you have to do secondary development. So I came up with the idea of writing a simple json conversion | structure tool (open source address).

The requirements are as follows:

Only header files, easy to use

Up to three lines of code to resolve the conversion

Support class | conversion between structure and json

Supports many basic data types, such as int, float, string, bool, etc.

Support STL basic types, such as vector, list, map, etc.

Support for nested relationships

Member renaming is supported, for example, the keyword in json is name, and the member name can be written as Name or other.

two。 The final sample code class Student {public: string Name; int Age; AIGC_JSON_HELPER (Name, Age) / / member registration AIGC_JSON_HELPER_RENAME ("name", "age") / / member rename, you can delete this} without the need; int main () {/ / json converted object Student person; JsonHelper::JsonToObject (person, R "({" name ":" XiaoMing "," age ": 15})") / / Class objects are transferred to json string jsonStr; JsonHelper::ObjectToJson (person, jsonStr); return 0;} 3. Realization method

Because rapidjson only needs header files to be used, rapidjson is selected as the basic library for secondary development.

3.1 conversion of basic types

As the lowest-level interface, you only need to perform an assignment operation, and it is also convenient to add some other types of support later.

Static bool JsonToObject (int & obj, rapidjson::Value & jsonValue) {if (jsonValue.IsNull () | |! jsonValue.IsInt ()) return false; obj = jsonValue.GetInt (); return true;} static bool JsonToObject (unsigned int & obj, rapidjson::Value & jsonValue) {if (jsonValue.IsNull () | | jsonValue.IsUint ()) return false; obj = jsonValue.GetUint (); return true } static bool JsonToObject (int64_t & obj, rapidjson::Value & jsonValue) {if (jsonValue.IsNull () | |! jsonValue.IsInt64 ()) return false; obj = jsonValue.GetInt64 (); return true;} / / other types. 3.2 class member registration

The method of macro definition + variable parameter template is used to realize this, and the registered members can be assigned in turn.

Template static bool WriteMembers (std::vector & names, int index, rapidjson::Value & jsonValue, TYPE & arg, TYPES &... Args) {if (! WriteMembers (names, index, jsonValue, arg)) return false; return WriteMembers (names, + + index, jsonValue, args...);} template static bool WriteMembers (std::vector & names, int index, rapidjson::Value & jsonValue, TYPE & arg) {const char * key = namesindex. C _ str (); if (! jsonValue.HasMember (key)) return true; if (! JsonToObject (arg, jsonValuekey)) return false Return true;} # define AIGC_JSON_HELPER (...)\ bool AIGC_CONVER_JSON_TO_OBJECT (rapidjson::Value & jsonValue, std::vector & names)\ {\ if (names.size () static inline bool JsonToObject (T & obj, rapidjson::Value & jsonValue) {return false Brief conver json string to class / * * @ param obj: class or struct * @ param jsonStr: json string * / template static inline bool JsonToObject (T & obj, const std::string & jsonStr) {rapidjson::Document root; root.Parse (jsonStr.c_str ()); if (root.IsNull ()) return false; return JsonToObject (obj, root);}

The most core part is just the above modules, and the rest are trivial operations such as adding type support.

Thank you for reading! This is the end of the article on "how to convert class structure and json in C++". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report