Dimitri
Dimitri

Reputation: 633

How to overload json deserialization of float?

I try to get how can I deserialize json like

 '{…, "money":{"amount":1.45674,"currency":"ETH"}, …}'

to my custom class or struct or whatever, using my own function. The goal is to convert the float to integer without rounding errors, and I want to use my own money classes, depending of currency name. So there must not interfere BigDecimal or other numeric in the middle of conversion.

Or maybe the 1.45674 can be inside quotes, it's not a problem in that case.

Upvotes: 0

Views: 120

Answers (1)

Max
Max

Reputation: 1957

If you're using JSON from the Ruby standard library, the following should make Ruby use your class:

  • Add a json_class key to the JSON object with a value of your class name (for example, '{"json_class":"Money::Ethereum","amount":1.45674}')
  • Add a class method to your class called json_create that creates an object based on the JSON data (for example, new(json_data['amount']))
  • When you do the parsing, add a "create_additions" option: JSON.parse(json_string, create_additions: true)

You can see an example of this in the JSON extension for Range, which has a json_create class method, as well as as_json and to_json instance methods that output the value that can be fed back into json_create.

require 'json/add/range'
output = (0..10).to_json
JSON.parse(output, create_additions: true) # Returns the range 0..10

Upvotes: 1

Related Questions