0

My Ruby class Routeguide::Rectangle object looks like this, (Pay attention on lo & hi variables, those are objects of class Routeguide::Point)

<Routeguide::Rectangle: lo: <Routeguide::Point: latitude: 400000000, longitude: -750000000>, hi: <Routeguide::Point: latitude: 420000000, longitude: -730000000>>`

I have correct json string for this object,

json_string = '{"lo":{"latitude":400000000,"longitude":-750000000},"hi":{"latitude":420000000,"longitude":-730000000}}'

I need to parse this json string again to create Routeguide::Rectangle class object like:

<Routeguide::Rectangle: lo: <Routeguide::Point: latitude: 400000000, longitude: -750000000>, hi: <Routeguide::Point: latitude: 420000000, longitude: -730000000>>`

I am using below code to achieve this:

JSON.parse(json_string, object_class: Routeguide::Rectangle)

But that is giving me error on JSON.parse method: #<ArgumentError: Unknown field: latitude>

Stacktrace:

[
  "/Users/psen/.rbenv/versions/2.7.7/lib/ruby/2.7.0/json/common.rb:156:in `[]='",
  "/Users/psen/.rbenv/versions/2.7.7/lib/ruby/2.7.0/json/common.rb:156:in `parse'",
  "/Users/psen/.rbenv/versions/2.7.7/lib/ruby/2.7.0/json/common.rb:156:in `parse'"
]
1
  • 1
    object_class sets the class which will be used for all JSON objects. However, not all your JSON objects do represent Routeguide::Rectangle instances. Some represent Routeguide::Point instances which have different attributes, hence the error.
    – Stefan
    Commented Mar 14 at 13:34

1 Answer 1

1

Assuming that you're also generating that json string, you could look into using JSON Additions. You'd have to define a Custom Addition to help with the serialization & deserialization.

1
  • Thanks for response, but I don't think this could solve my problem completely because Routeguide::Rectangle class is not fixed for me and there could be any class. Basically I will know the class at runtime only and hence I don't think json addition will help in any way. any further comments? @goalaleo Commented Mar 14 at 17:16

Not the answer you're looking for? Browse other questions tagged or ask your own question.