Search code examples
haskellaeson

How to override type class instance from package


In aeson.Types.ToJSON, there is already one call instances for ToJSON (Ratio Integer) but it is show number like ("A" % "B") in JSON, I would like to make a custom version (sort of float-alike numbers) some where in my code:

instance ToJSON (Ratio Integer) where
  toJSON r = String $ pack $ show $ (numerator r) / (denominator r)

Then the GHC tells me it's overlapping, is there any way I can override the one from Data.Aeson.Typtes.ToJSON for Ratio Integer ?

Thank you

enter image description here


Solution

  • You don't, typically you introduce a "signal interface", like:

    newtype MyRatio = MyRatio (Ratio Integer)
    
    instance ToJSON MyRatio where
      toJSON (MyRatio r) = String $ pack $ show $ (numerator r) / (denominator r)

    and you thus wrap the values to serialize in the MyRatio data constructor.