We can C++ project and we need to (de) serialize objects from and into json.
In C# we are using JSON.NET. We simple call:
string json = JsonConvert.SerializeObject(product);
var myNewObject = JsonConvert.DeserializeObject<MyClass>(json);
Very simple and useful.
Does anybody know about free C++ library, which can be used in the same simple way like in C#?
We are using JsonCpp, but it does not support it.
Thanks very much Regards
JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).
A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.
To serialize a . Net object to JSON string use the Serialize method. It's possible to deserialize JSON string to . Net object using Deserialize<T> or DeserializeObject methods.
Deserializes the JSON to the specified . NET type. Deserializes the JSON to the specified . NET type using a collection of JsonConverter.
C++ does not support reflection so you necessarily have to write your own serialize and deserialize functions for each object.
I'm using https://github.com/nlohmann/json in a C++ websocket server talking to a html/javascript client. The websocket framework is https://github.com/zaphoyd/websocketpp. So sending the json structure 'matches' from the server goes like
msg->set_payload(matches.dump());
m_server.send(hdl, msg);
And like wise from the client
var m = "la_liga";
var msg = {
"type": "request",
"data": m
}
msg = JSON.stringify(msg);
ws.send(msg);
When I receive json on the server I parse it and then a try-catch
void on_message(connection_hdl hdl, server::message_ptr msg) {
connection_ptr con = m_server.get_con_from_hdl(hdl);
nlohmann::json jdata;
std::string payload = msg->get_payload();
try {
jdata.clear();
jdata = nlohmann::json::parse(payload);
if (jdata["type"] == "update") {
<do something with this json structure>
}
} catch (const std::exception& e) {
msg->set_payload("Unable to parse json");
m_server.send(hdl, msg);
std::cerr << "Unable to parse json: " << e.what() << std::endl;
}
}
And likewise on the client
ws.onmessage = function (e) {
var receivedMsg = JSON.parse(e.data);
if (receivedMsg.type == "table") {
<sort and display updated table standing>
}
}
Websocketpp requires boost libraries.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With