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

Custom deserialization of number_float_t #1236

Closed
carlcook opened this issue Sep 11, 2018 · 3 comments
Closed

Custom deserialization of number_float_t #1236

carlcook opened this issue Sep 11, 2018 · 3 comments

Comments

@carlcook
Copy link

Hi,

Do you know if there is any way to provide a deserialization routine for number_float_t, where I can get access to the underlying json string?

Basically I have an arbitrary length Decimal class, and I can easily read this in from json as follows:

namespace nlohmann { template <typename T> struct adl_serializer<Decimal> { static void from_json(const json &j, Decimal& decimal) { decimal = Decimal::parse(j.get<std::string>()); } }; }

The above only works of course if I pass my "Decimals" as strings in json, e.g.:

{ "myPrice": "43.2" }

What I'd really like to be able to do is pass "myPrice" as a number (i.e. not in quotes). I've tried a few different approaches, but it seems that number_float_t really has to be an IEEE floating point type (i.e. I can't see a way to "access" the underlying string buffer of the number).

Any pointers would be appreciated!

@nlohmann
Copy link
Owner

You can use the SAX interface which contains a callback bool number_float(number_float_t val, const string_t& s) which contains the parsed string.

@carlcook
Copy link
Author

Excellent, thanks! Another approach (totally a hack) I just figured out is to call j.dump() within the adl serializer.

Aside from that, do you have any suggestions for how to serialize an arbitrary precision decimal type? I.e. the following gives me the same problem as deserialization (I can only write as a string, not a number):

static void to_json(json &j, const Decimal &decimal) { j = decimal.toString(); }

@carlcook
Copy link
Author

For now I'll leave this in the too hard basket. I tried experimenting with the output adpator (etc) but nothing great came of this...

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