jgaa / restc-cpp

Modern C++ REST Client library
MIT License
615 stars 95 forks source link

Serialize data of type int which has value of 0 to json #146

Closed kudoka-chear closed 1 year ago

kudoka-chear commented 1 year ago

Hi,

I'm trying to serialize a struct to json, I find that if one data's type is int and it has a value of 0, This data will not be displayed in json.

For example, i want serialize this struct to json with userId has a value of 0, id has a value of 1;

struct Post {
    int userId;
    int id;
};

The json I get is

{
    "id": 1
}

"userId" disappeared.

By the way, i also meet the same situation with this issues: https://github.com/jgaa/restc-cpp/issues/114

thank you for you attation.

Regards,

jgaa commented 1 year ago

By default, the JSON serializer ignores data values it consider "empty". This is configurable with the SerializeProperties::ignore_empty_fileds flag. Unfortunately, I don't think I have documented this in the tutorial. I will do that.

Another option (that I use in cases where I need some numeric 0 values to be sent because the presence of the attribute is required on the receiving end) is to use std::optional<int> as the data-type and set the value to 0. In this case the serializer will see that the optional variable has a value, and it will serialize it.

jgaa commented 1 year ago

Regarding #114, what operating system / CPU are you using?

kudoka-chear commented 1 year ago

It works! Thank you!!!! And I'm using Linux Intel(R) Xeon(R) Gold 6226R CPU