Deserialize super long number as string using serde_json

Hi, can someone help me deserialize a super long number in a json response into a String? The field contains a "uuid number", and the number is too big to fit in any rust number types.

I'm very new to rust. I'm trying to do this using serde_json, but some of the nuances just aren't clicking for me yet.

Example JSON API response:

  "uuidNumber": 2386290877745342463654898740001354837999050286499262318283

Possible desired implementation (open to alternatives):

struct UUIDNumber(String);

impl<'de> Deserialize<'de> for UUIDNumber {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        D: serde::Deserializer<'de>,
        // TODO!?

And the struct that I'd deserialize to would be written something like:

#[derive(serde::Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct APIResponse {
    uuid_number: UUIDNumber,

Although I'd still like to see a solution like this, I suppose I could also explore a BigInt crate as well.

Thanks so much!

You can turn on the arbitrary_precision feature of serde_json, and then serde_json::value::Number will deserialize from numbers of arbitrary size.



Hey, that's pretty cool! I just tried it and it parsed it to this:

uuid_number: Number(2386290877745342463654898740001354837999050286499262318283)

Thank you!

I'm still curious if there's a way to do it and convert it to a string without enabling that feature. Is that possible?

In general, if a type has a human-readable representation, then it should implement Display and transitively ToString. See example.

No, I don't think so. What's wrong with enabling the feature?


Actually I don't think there's anything wrong with enabling the feature. I'm writing a helper library for this API and for some reason I had it in my head that consumers of the library would have to enable the feature in their project dependencies. But I think if I implement UUIDNumber in my library, and enable the feature in the library's serde dependency, then they should be able to just use UUIDNumber and have it work (I hope).

I'll give it a go! Thank you very much!

No. If features worked like this, that would be scary. Then we would spend all of our time chasing features of all transitive dependencies.

Features are enabled automatically, and this is why they should be purely additive (which is what you'll see a lot of people mention in connection with them). Once a single transitive dependency enables a feature, it stays on for that crate, for the purposes of the entire dependency graph.

1 Like

Well when you say it like that it seems obvious! Yeah that would suck.

Hey I implemented your solution and it works perfectly :pinched_fingers:.

Thank you (this was my first time dipping my toe into the rust community. Thanks for being so helpful).


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.