+/*
+
+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
readJson = getDoubleValue
toJson = JsonDouble
fromJson (JsonDouble value) = value
+ fromJson (JsonLong value) = Java.l2d value
instance Json Float where
writeJson = writeNumberFloat
toJson (a, b, c, d, e) = JsonArray [toJson a, toJson b, toJson c, toJson d, toJson e]
fromJson (JsonArray [a, b, c, d, e]) = (fromJson a, fromJson b, fromJson c, fromJson d, fromJson e)
+instance (Json a, Json b, Json c, Json d, Json e, Json f) => Json (a, b, c, d, e, f) where
+ writeJson g (a, b, c, d, e, f) = do
+ writeStartArray g
+ writeJson g a
+ writeJson g b
+ writeJson g c
+ writeJson g d
+ writeJson g e
+ writeJson g f
+ writeEndArray g
+ readJson p = (a, b, c, d, e, f)
+ where
+ assertStartArray p
+ a = readNextJson p
+ b = readNextJson p
+ c = readNextJson p
+ d = readNextJson p
+ e = readNextJson p
+ f = readNextJson p
+ assertEndArray p
+ toJson (a, b, c, d, e, f) = JsonArray [toJson a, toJson b, toJson c, toJson d, toJson e, toJson f]
+ fromJson (JsonArray [a, b, c, d, e, f]) = (fromJson a, fromJson b, fromJson c, fromJson d, fromJson e, fromJson f)
+
+
data Json =
JsonString String
| JsonDouble Double
| 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