JSON support
graphs
supports the serialization of graphs as via circe.
You need to add the graphs-json
dependency to use it:
libraryDependencies += "com.flowtick" %% "graphs-json" % "0.8.0"
For the conversion you need to have an Identifiable
instance for the node type:
Example: primitive types with defaults
sourceimport com.flowtick.graphs._
import com.flowtick.graphs.defaults._
import com.flowtick.graphs.json.format.default._
import io.circe._
import io.circe.syntax._
import io.circe.parser._
val graph: Graph[Unit, String] = Graph.fromEdges(
Set(
"A" --> "D",
"A" --> "C",
"A" --> "B",
"B" --> "E",
"B" --> "F",
"B" --> "G",
"E" --> "H"
)
)
val json: Json = graph.asJson
val parsed: Either[Error, Graph[Unit, String]] = decode[Graph[Unit, String]](json.noSpaces)
require(parsed == Right(graph))
Example: providing the ID for a custom type
sourceimport com.flowtick.graphs._
import com.flowtick.graphs.defaults._
import com.flowtick.graphs.json.format.default._
import io.circe._
import io.circe.generic.auto._
import io.circe.syntax._
import io.circe.parser._
case class MyNode(id: String, value: Double)
implicit val myNodeId: Identifiable[MyNode] = (value: MyNode) => value.id
val graph: Graph[Unit, MyNode] = Graph.fromEdges(
Set(
MyNode("1", 42) --> MyNode("2", 43)
)
)
val json: Json = graph.asJson
val parsed = decode[Graph[Unit, MyNode]](json.noSpaces)
require(parsed == Right(graph))
Note that this example is also importing to option to treat unit as null
in the JSON representation.
The source code for this page can be found here.