Reputation: 633
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
Reputation: 1957
If you're using JSON from the Ruby standard library, the following should make Ruby use your class:
json_class
key to the JSON object with a value of your class name (for example, '{"json_class":"Money::Ethereum","amount":1.45674}'
)json_create
that creates an object based on the JSON data (for example, new(json_data['amount'])
) 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