我有一些存盤在資料庫中的JSON欄位,其中包含一個String -> Double的映射,例如:
{}。
"某種型別的東西": 0.45,
"其他型別的東西": 0.35,
"別的東西": 0.2
}
我想把這個表示為ThingComposition:
data ThingType = ThingTypeSome
| ThingTypeOther[/span
| ThingTypeUnknown Text
-- | 從文本表示創建一個ThingType Text
txtToThing :: Text -> ThingType
txtToThing "某種型別的東西" = ThingTypeSome[/span
txtToThing "其他型別的事物" = ThingTypeOthertxtToThing s = ThingTypeUnknown s
--從JSON文本反序列化ThingType。
instance FromJSON ThingType where
parseJSON val = withText "ThingType" (return . txtToThing) val
data ThingComposition = ThingComposition [ (ThingType, Double)]。
| InvalidThingComposition[/span
instance FromJSON ThingComposition where
parseJSON val = withObject "ThingComposition"
_
價值
_是我不知道如何填寫的地方。我已經嘗試了像下面這樣的方法,但是我無法讓型別對齊,考慮到JSON表示法有可能與型別不匹配,我無法找出最好的方法,但是我不想創建一個[(Either String ThingType, Either String Double)]的串列。我怎樣才能將頂部的那個物件決議為ThingComposition型別呢?
_ = (return . ThingComposition) . map (bimap parseJSON parseJSON) . toList
uj5u.com熱心網友回復:
我將為你的ThingType制作一些支持實體,然后重新使用FromJSON (HashMap k v)實體。
--在你的宣告中添加了 "deriving Eq";其他方面沒有改變。
data ThingType = ThingTypeSome
| ThingTypeOther[/span
| ThingTypeUnknown Text
deriving Eq
thingToTxt :: ThingType -> Text
thingToTxt ThingTypeSome = "某種型別的東西"。
thingToTxt ThingTypeOther = "其他型別的東西"。
thingToTxt (ThingTypeUnknown s) = s
instance FromJSONKey ThingType where>
fromJSONKey = FromJSONKeyText txtToThing
instance Hashable ThingType where
hashWithSalt n = hashWithSalt n . thingToTxt
有了這些支持代碼,你現在有了一個FromJSON實體,用于HashMap ThingType Double,它在很多方面都優于[(ThingType, Double)]。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/316940.html
標籤:
上一篇:如何更新元組串列中的一個元素?
