Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
kudoka-chear opened this issue Jan 18, 2023 · 3 comments
Closed

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

kudoka-chear opened this issue Jan 18, 2023 · 3 comments

Comments

@kudoka-chear
Copy link

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:
#114

thank you for you attation.

Regards,

@jgaa
Copy link
Owner

jgaa commented Jan 18, 2023

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
Copy link
Owner

jgaa commented Jan 18, 2023

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

@kudoka-chear
Copy link
Author

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

@jgaa jgaa closed this as completed Feb 11, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants