Is it possible to skip write null for json_type_trails ? #594
-
Example
Is it possible skip write null then result like |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
@hiepsahplydia, I'm not sure I understand your question. If you want to return a result like |
Beta Was this translation helpful? Give feedback.
-
@danielaparker This is my code example:
Result:
I want the value to be null or some way for the json to not write that value anymore.
|
Beta Was this translation helpful? Give feedback.
-
@hiepsahplydia, I made two changes to your code, replacing
with
(1 is the number of mandatory parameters). Then your example becomes: #include <jsoncons/json.hpp>
#include <iostream>
using namespace jsoncons;
struct OptionalExample {
std::string text;
std::optional<std::string> optional;
std::optional<std::string> optional_skip;
explicit OptionalExample() = default;
~OptionalExample() = default;
};
namespace jsoncons
{
template <typename Json>
struct json_type_traits<Json, std::optional<std::string>>
{
static bool is(const Json& val) noexcept
{
return true; // always true, this value can nul or empty.
}
static std::optional<std::string> as(const Json& val)
{
if (!val.has_value()) {
return std::optional<std::string>();
}
else {
return std::optional(val.as_string());
}
}
static Json to_json(std::optional<std::string> const& val)
{
if (val.has_value()) {
return Json(val.value());
}
else {
return nullptr;
}
}
};
}
JSONCONS_N_MEMBER_TRAITS(OptionalExample, 1, text, optional, optional_skip);
int main()
{
std::error_code ec;
OptionalExample val;
val.text = "Sample!";
val.optional = "Available Value";
std::string buffer;
json_string_encoder encoder{ buffer };
encode_traits<OptionalExample, char>::encode(val, encoder, ojson{}, ec);
std::cout << buffer << "\n";
} Output: {
"text": "Sample!",
"optional": "Available Value"
} See also this example, Serialize non-mandatory std::optional values using the convenience macros |
Beta Was this translation helpful? Give feedback.
@hiepsahplydia, I made two changes to your code, replacing
OptionalV
withstd::optional
, andwith
(1 is the number of mandatory parameters). Then your example becomes: