From: jsimomaa Date: Thu, 14 Feb 2019 11:24:34 +0000 (+0200) Subject: Add lookupJsonField to Data/Json SCL module X-Git-Tag: v1.43.0~136^2~198 X-Git-Url: https://gerrit.simantics.org/r/gitweb?a=commitdiff_plain;h=66b0fd2ee69d84d3107f109679b6fd1866f8f3fc;p=simantics%2Fplatform.git Add lookupJsonField to Data/Json SCL module gitlab #256 Change-Id: If3be1a2f355f4542ffb60e0984ceec2b8771ed0f --- diff --git a/bundles/org.simantics.scl.data/scl/Data/Json.scl b/bundles/org.simantics.scl.data/scl/Data/Json.scl index 659329df7..2190287fc 100644 --- a/bundles/org.simantics.scl.data/scl/Data/Json.scl +++ b/bundles/org.simantics.scl.data/scl/Data/Json.scl @@ -1,3 +1,23 @@ +/* + +An example how to implement + +data GeographicalLocation = GeographicalLocation { + latitude :: Double, + longitude :: Double +} + +instance Json GeographicalLocation where + toJson GeographicalLocation { latitude, longitude } = JsonObject [ + JsonField "latitude" (toJson latitude), + JsonField "longitude" (toJson longitude) + ] + fromJson object = GeographicalLocation { + latitude = fromJson $ fromJust $ lookupJsonField "latitude" object, + longitude = fromJson $ fromJust $ lookupJsonField "longitude" object + } +*/ + import "StandardLibrary" import "Data/Writer" import "JavaBuiltin" as Java @@ -298,6 +318,12 @@ data Json = | JsonObject [JsonField] data JsonField = JsonField String Json +lookupJsonField :: String -> Json -> Maybe Json +lookupJsonField fieldName (JsonObject fields) = mapFirst selector fields + where + selector (JsonField name value) | name == fieldName = Just value + selector _ = Nothing + deriving instance Show Json deriving instance Show JsonField