{"id":231,"date":"2022-04-17T10:29:32","date_gmt":"2022-04-17T10:29:32","guid":{"rendered":"https:\/\/www.kindsonthegenius.com\/scala\/?p=231"},"modified":"2022-04-28T20:43:42","modified_gmt":"2022-04-28T20:43:42","slug":"scala-json-encoding-with-circe","status":"publish","type":"post","link":"https:\/\/www.kindsonthegenius.com\/scala\/scala-json-encoding-with-circe\/","title":{"rendered":"Scala &#8211; Json Encoding With Circe"},"content":{"rendered":"<p>In this tutorial series, you will learn how to build an encoder to encode Scala types into Json representations. We&#8217;ll first see how to used encoders provided by Circe and in the next tutorial, we&#8217;ll build our own encoders.<\/p>\n<ol>\n<li><a href=\"#t1\">Introduction to Circe and Json Encoding<\/a><\/li>\n<li><a href=\"#t2\">Building an Encoder &#8211; Setup<\/a><\/li>\n<li><a href=\"#t3\">Building an Encoder &#8211; Build Json Values<\/a><\/li>\n<li><a href=\"#t4\">Building an Encoder &#8211; Manipulating Json Values<\/a><\/li>\n<li><a href=\"#t5\">Manipulating Nested Values<\/a><\/li>\n<li><a href=\"https:\/\/youtu.be\/8l5RiZfWI70\" target=\"_blank\" rel=\"noopener\">JSON Encoding Video Tutorial 1<\/a><\/li>\n<\/ol>\n<h4><strong id=\"t1\">1. Introduction to Circe and Json Encoding<\/strong><\/h4>\n<p>In many programming languages, JavaScript for example, converting back and forth between data structures and their JSON strings is quite easy. You could simply use the <em>JSON.stringify()<\/em> function as shown below:<\/p>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #888888;\">\/\/ Original User object<\/span>\r\n<span style=\"color: #008800; font-weight: bold;\">const<\/span> User <span style=\"color: #333333;\">=<\/span> {\r\n    name<span style=\"color: #333333;\">:<\/span> <span style=\"background-color: #fff0f0;\">\"Kindson\"<\/span>,\r\n    location<span style=\"color: #333333;\">:<\/span> <span style=\"background-color: #fff0f0;\">\"Budapest\"<\/span>,\r\n    department<span style=\"color: #333333;\">:<\/span> <span style=\"background-color: #fff0f0;\">\"Computer Science\"<\/span>\r\n}\r\n\r\n<span style=\"color: #008800; font-weight: bold;\">var<\/span> userString <span style=\"color: #333333;\">=<\/span> JSON.stringify(User) <span style=\"color: #888888;\">\/\/JSON string of User object<\/span>\r\n\r\n<span style=\"color: #008800; font-weight: bold;\">var<\/span> parsedUser <span style=\"color: #333333;\">=<\/span> JSON.parse(userString) <span style=\"color: #888888;\">\/\/User object gotten from JSON string<\/span>\r\n<\/pre>\n<p>You can run this code and use console.log() to view the variables.<\/p>\n<p>In functional programming languages like Scala, things are a bit different. The\u00a0 process is more involved and that is why we need <a href=\"https:\/\/circe.github.io\/circe\/\" target=\"_blank\" rel=\"noopener\">Circe<\/a>. Circe uses type classes to describe how types in Scala should be serialized and deserialized. For instance, for the User type, we can have two type classes:<\/p>\n<ul>\n<li><strong>Encoder[User]<\/strong> &#8211; this encoder means that a User instance can be transformed into a Json representation (<em>io.circe.Json<\/em>)<\/li>\n<li><strong>Decoder[User]<\/strong> &#8211; this decoder means that Json value can be transformed into DecodedResult[A]<\/li>\n<\/ul>\n<p>The figure below illustrates how serialization works in Circe<\/p>\n<figure id=\"attachment_234\" aria-describedby=\"caption-attachment-234\" style=\"width: 1024px\" class=\"wp-caption aligncenter\"><a href=\"https:\/\/www.kindsonthegenius.com\/scala\/wp-content\/uploads\/sites\/14\/2022\/04\/circe-codec-2500x825.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"size-large wp-image-234\" src=\"https:\/\/www.kindsonthegenius.com\/scala\/wp-content\/uploads\/sites\/14\/2022\/04\/circe-codec-1024x338.jpg\" alt=\"Serialization in Scala with Circe\" width=\"1024\" height=\"338\" srcset=\"https:\/\/www.kindsonthegenius.com\/scala\/wp-content\/uploads\/sites\/14\/2022\/04\/circe-codec-1024x338.jpg 1024w, https:\/\/www.kindsonthegenius.com\/scala\/wp-content\/uploads\/sites\/14\/2022\/04\/circe-codec-300x99.jpg 300w, https:\/\/www.kindsonthegenius.com\/scala\/wp-content\/uploads\/sites\/14\/2022\/04\/circe-codec-768x253.jpg 768w, https:\/\/www.kindsonthegenius.com\/scala\/wp-content\/uploads\/sites\/14\/2022\/04\/circe-codec-1536x507.jpg 1536w, https:\/\/www.kindsonthegenius.com\/scala\/wp-content\/uploads\/sites\/14\/2022\/04\/circe-codec-2048x676.jpg 2048w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/a><figcaption id=\"caption-attachment-234\" class=\"wp-caption-text\">Serialization in Scala with Circe<\/figcaption><\/figure>\n<p>&nbsp;<\/p>\n<h4><strong id=\"t2\">2. Encoding to Json with Circe\u00a0 &#8211; Setup<\/strong><\/h4>\n<p>Let&#8217;s follow the procedure the build a decoder in Scala using Circe.<\/p>\n<p><strong>Step 1<\/strong> &#8211; Create a Scala project in IntelliJ. (you can review the procedure to setup IntelliJ and create a project here. <a href=\"https:\/\/www.kindsonthegenius.com\/scala\/scala-ide-installation-and-setup\/\" target=\"_blank\" rel=\"noopener\">Setup Scala in IntelliJ<\/a>, <a href=\"https:\/\/www.kindsonthegenius.com\/scala\/scala-your-first-program\/\" target=\"_blank\" rel=\"noopener\">Write Your First Scala Program<\/a>)<\/p>\n<p><strong>Step 2<\/strong> &#8211; Open your<em> build.sb<\/em>t file and add the following line to add the Circe dependency to your project<br \/>\n<!-- HTML generated using hilite.me --><\/p>\n<pre style=\"margin: 0; line-height: 125%;\">libraryDependencies <span style=\"color: #333333;\">+=<\/span> <span style=\"background-color: #fff0f0;\">\"io.circe\"<\/span> <span style=\"color: #333333;\">%%<\/span> <span style=\"background-color: #fff0f0;\">\"circe-core\"<\/span> <span style=\"color: #333333;\">%<\/span> <span style=\"background-color: #fff0f0;\">\"0.14.1\"<\/span>\r\nlibraryDependencies <span style=\"color: #333333;\">+=<\/span> <span style=\"background-color: #fff0f0;\">\"io.circe\"<\/span> <span style=\"color: #333333;\">%%<\/span> <span style=\"background-color: #fff0f0;\">\"circe-parser\"<\/span> <span style=\"color: #333333;\">%<\/span> <span style=\"background-color: #fff0f0;\">\"0.14.1\"<\/span>\r\nlibraryDependencies <span style=\"color: #333333;\">+=<\/span> <span style=\"background-color: #fff0f0;\">\"io.circe\"<\/span> <span style=\"color: #333333;\">%%<\/span> <span style=\"background-color: #fff0f0;\">\"circe-generic\"<\/span> <span style=\"color: #333333;\">%<\/span> <span style=\"background-color: #fff0f0;\">\"0.14.1\"<\/span>\r\n<\/pre>\n<ul>\n<li><strong>circe-core<\/strong> &#8211; exposes the encoders and decoder type classes as well as Json structures and cursors that allow you to traverse and modify Json trees.<\/li>\n<li><strong>circe-parser<\/strong> &#8211; allows you to parse serialized Json into abstract syntax tree (AST)<\/li>\n<li><strong>circe-generic<\/strong> &#8211; allows you to derive encoders and decoders automatically using macros<\/li>\n<\/ul>\n<p><strong>Step 3<\/strong> &#8211; Create an Object that extends App<\/p>\n<p>&nbsp;<\/p>\n<h4><strong id=\"t3\">3. Encoding to Json with Circe\u00a0 &#8211; Build JSON Values<\/strong><\/h4>\n<p>Remember that encoder takes an instance of a data type into JSON value (io.circe.Json). So we would encode instances of the following types:<\/p>\n<ul>\n<li>String<\/li>\n<li>Integer<\/li>\n<li>Array<\/li>\n<li>Object<\/li>\n<\/ul>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #888888;\">\/\/Building Json values<\/span>\r\n<span style=\"color: #008800; font-weight: bold;\">val<\/span> jsonString <span style=\"color: #008800; font-weight: bold;\">=<\/span> <span style=\"background-color: #fff0f0;\">\"Kindson The Genius\"<\/span><span style=\"color: #333333;\">.<\/span>asJson <span style=\"color: #888888;\">\/\/ Json String, can be written as Json.fromString<\/span>\r\n<span style=\"color: #008800; font-weight: bold;\">val<\/span> jsonInt <span style=\"color: #008800; font-weight: bold;\">=<\/span> <span style=\"color: #bb0066; font-weight: bold;\">Json<\/span><span style=\"color: #333333;\">.<\/span>fromInt<span style=\"color: #333333;\">(<\/span><span style=\"color: #0000dd; font-weight: bold;\">43<\/span><span style=\"color: #333333;\">);<\/span>              <span style=\"color: #888888;\">\/\/ Json Int<\/span>\r\n<span style=\"color: #008800; font-weight: bold;\">val<\/span> jsonArray <span style=\"color: #008800; font-weight: bold;\">=<\/span> <span style=\"color: #bb0066; font-weight: bold;\">Json<\/span><span style=\"color: #333333;\">.<\/span>arr<span style=\"color: #333333;\">(<\/span>jsonString<span style=\"color: #333333;\">,<\/span> jsonInt<span style=\"color: #333333;\">)<\/span><span style=\"color: #888888;\">\/\/ Json Array<\/span>\r\n\r\n<span style=\"color: #008800; font-weight: bold;\">val<\/span> jsonObject <span style=\"color: #008800; font-weight: bold;\">=<\/span> <span style=\"color: #bb0066; font-weight: bold;\">Json<\/span><span style=\"color: #333333;\">.<\/span>obj<span style=\"color: #333333;\">(<\/span>                   <span style=\"color: #888888;\">\/\/ Json Object<\/span>\r\n    <span style=\"background-color: #fff0f0;\">\"name\"<\/span> <span style=\"color: #333333;\">-&gt;<\/span><span style=\"background-color: #fff0f0;\">\"Tech Pro\"<\/span><span style=\"color: #333333;\">.<\/span>asJson<span style=\"color: #333333;\">,<\/span>\r\n    <span style=\"background-color: #fff0f0;\">\"title\"<\/span> <span style=\"color: #333333;\">-&gt;<\/span> <span style=\"background-color: #fff0f0;\">\"Software Engineer\"<\/span><span style=\"color: #333333;\">.<\/span>asJson\r\n<span style=\"color: #333333;\">)<\/span>\r\n<\/pre>\n<p>The code above shows how you can encode various data types into Json values. I have added comments to indicate the various data types.<\/p>\n<p><strong>Note:<\/strong> for the array types, we specify Json values as the elements.\u00a0 Similarly, for the object, each of the members has values that are Json values<\/p>\n<p>&nbsp;<\/p>\n<h4><strong id=\"t4\">4. Encoding to Json with Circe\u00a0 &#8211; Manipulating JSON Values<\/strong><\/h4>\n<p>Json values has various methods that can be used to manipulated them. These methods are prefixed with &#8220;map&#8221;. For example:<\/p>\n<ul>\n<li><em><strong>mapString<\/strong><\/em> is used to manipulate Json string<\/li>\n<li><strong><em>mapArray<\/em><\/strong> is used to manipulate Json array<\/li>\n<\/ul>\n<p>To use the <em>mapString()<\/em>, you need to call it on the Json string and pass it a function that does the transformation. In the example below, we use the function toUpperCase() to transform the given string to upper case<!-- HTML generated using hilite.me --><\/p>\n<pre style=\"margin: 0; line-height: 125%;\">jsonString<span style=\"color: #333333;\">.<\/span>mapString<span style=\"color: #333333;\">(<\/span><span style=\"color: #008800; font-weight: bold;\">_<\/span><span style=\"color: #333333;\">.<\/span>toUpperCase<span style=\"color: #333333;\">())<\/span>\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p>To use the <em>mapArray(),<\/em> we call the <em>mapArray()<\/em> function, then we map through each element of the array with the<em> map()<\/em> function and for each element, we call the mapString() to transform them with the toUpperCase() function. This is shown below:<\/p>\n<pre style=\"margin: 0; line-height: 125%;\">jsonArray<span style=\"color: #333333;\">.<\/span>mapArray<span style=\"color: #333333;\">(<\/span><span style=\"color: #008800; font-weight: bold;\">_<\/span><span style=\"color: #333333;\">.<\/span>map<span style=\"color: #333333;\">(<\/span><span style=\"color: #008800; font-weight: bold;\">_<\/span><span style=\"color: #333333;\">.<\/span>mapString<span style=\"color: #333333;\">(<\/span><span style=\"color: #008800; font-weight: bold;\">_<\/span><span style=\"color: #333333;\">.<\/span>toUpperCase<span style=\"color: #333333;\">())))<\/span>\r\n<\/pre>\n<p>Note that this is the same as the line below, without using the _. operator.<\/p>\n<pre style=\"margin: 0; line-height: 125%;\">jsonArray<span style=\"color: #333333;\">.<\/span>mapArray<span style=\"color: #333333;\">(<\/span>ar <span style=\"color: #008800; font-weight: bold;\">=&gt;<\/span>ar<span style=\"color: #333333;\">.<\/span>map<span style=\"color: #333333;\">(<\/span>el <span style=\"color: #008800; font-weight: bold;\">=&gt;<\/span>el<span style=\"color: #333333;\">.<\/span>mapString<span style=\"color: #333333;\">(<\/span>str <span style=\"color: #008800; font-weight: bold;\">=&gt;<\/span> str<span style=\"color: #333333;\">.<\/span>toUpperCase<span style=\"color: #333333;\">())))<\/span>\r\n<\/pre>\n<p>&nbsp;<\/p>\n<h4><strong id=\"t5\">5. Manipulating Nested Values<\/strong><\/h4>\n<p>In this case, we would have an object nested inside another object. In other words, the value of the field in the Json structure is an object.<\/p>\n<p>Let&#8217;s assume we have an object called <em>personalData<\/em> and inside this object, we have a field called <em>address<\/em> whose value is an object called <em>addressObject<\/em>,\u00a0 made up of two fields: <em>city<\/em> and <em>street<\/em>. The <em>addressObject<\/em> (encoded to Json) is given below:<\/p>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #008800; font-weight: bold;\">val<\/span> addressObj <span style=\"color: #008800; font-weight: bold;\">=<\/span> <span style=\"color: #bb0066; font-weight: bold;\">Json<\/span><span style=\"color: #333333;\">.<\/span>obj<span style=\"color: #333333;\">(<\/span>\r\n  <span style=\"background-color: #fff0f0;\">\"city\"<\/span> <span style=\"color: #333333;\">-&gt;<\/span> <span style=\"background-color: #fff0f0;\">\"Akocity\"<\/span><span style=\"color: #333333;\">.<\/span>asJson<span style=\"color: #333333;\">,<\/span>\r\n  <span style=\"background-color: #fff0f0;\">\"street\"<\/span> <span style=\"color: #333333;\">-&gt;<\/span> <span style=\"color: #6600ee; font-weight: bold;\">56.<\/span>asJson\r\n<span style=\"color: #333333;\">)<\/span>\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p>With this, the personalData object with the nested addressObj is given below:<\/p>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #008800; font-weight: bold;\">val<\/span> personalData <span style=\"color: #008800; font-weight: bold;\">=<\/span> <span style=\"color: #bb0066; font-weight: bold;\">Json<\/span><span style=\"color: #333333;\">.<\/span>obj<span style=\"color: #333333;\">(<\/span>\r\n   <span style=\"background-color: #fff0f0;\">\"name\"<\/span> <span style=\"color: #333333;\">-&gt;<\/span> <span style=\"background-color: #fff0f0;\">\"Kindson\"<\/span><span style=\"color: #333333;\">.<\/span>asJson<span style=\"color: #333333;\">,<\/span>\r\n   <span style=\"background-color: #fff0f0;\">\"address\"<\/span> <span style=\"color: #333333;\">-&gt;<\/span> addressObj\r\n<span style=\"color: #333333;\">)<\/span>\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p>So the goal is the manipulate the values inside the addressObj<span style=\"color: #008800;\"><b>. <\/b><\/span><span style=\"font-family: 'Source Sans Pro', Graphik, -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif; font-size: 1.125rem;\">Now we would like to manipulate this object and reverse the value of city field. We have four functions to use:<\/span><\/p>\n<ul>\n<li><strong><em>hcursor()<\/em><\/strong> &#8211; used to obtain an cursor on the object<\/li>\n<li><em><strong>downField()<\/strong> <\/em>&#8211; is used to capture a child field<\/li>\n<li><strong>withFocus()<\/strong> &#8211; returns an <em>Acursor<\/em> on the nested object<\/li>\n<li><strong><em>top()<\/em><\/strong> &#8211; is used to step up to the top of the hierarchy<\/li>\n<\/ul>\n<p>The code is give below<\/p>\n<pre style=\"margin: 0; line-height: 125%;\">personalData<span style=\"color: #333333;\">.<\/span>hcursor\r\n<span style=\"color: #333333;\">  .<\/span>downField<span style=\"color: #333333;\">(<\/span><span style=\"background-color: #fff0f0;\">\"address\"<\/span><span style=\"color: #333333;\">)<\/span><span style=\"color: #333333;\">.<\/span>downField<span style=\"color: #333333;\">(<\/span><span style=\"background-color: #fff0f0;\">\"city\"<\/span><span style=\"color: #333333;\">)<\/span>\r\n  <span style=\"color: #333333;\">.<\/span>withFocus<span style=\"color: #333333;\">(<\/span><span style=\"color: #008800; font-weight: bold;\">_<\/span><span style=\"color: #333333;\">.<\/span>mapString<span style=\"color: #333333;\">(<\/span><span style=\"color: #008800; font-weight: bold;\">_<\/span><span style=\"color: #333333;\">.<\/span>reverse<span style=\"color: #333333;\">))<\/span>\r\n  <span style=\"color: #333333;\">.<\/span>top\r\n  <span style=\"color: #333333;\">.<\/span>map<span style=\"color: #333333;\">(<\/span><span style=\"color: #008800; font-weight: bold;\">_<\/span><span style=\"color: #333333;\">.<\/span>spaces2<span style=\"color: #333333;\">)<\/span>\r\n<\/pre>\n<p>The code above reverses the value of the title property and returns that Json representation of the object. I recommend you watch the video for clarification.<\/p>\n<p><strong>HCursor vs ACursor<\/strong> &#8211; Just like the HCursor, the ACursor also tracks the history, but and ACursor also represents the possibility of failure.<\/p>\n<p>In the next part, we would actually be building decoders. I recommend you watch the video tutorial for clarification.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial series, you will learn how to build an encoder to encode Scala types into Json representations. We&#8217;ll first see how to used &hellip; <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[48,2],"tags":[41,43,42],"class_list":["post-231","post","type-post","status-publish","format-standard","hentry","category-circe","category-scala-programming","tag-circe","tag-encoder","tag-json"],"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/www.kindsonthegenius.com\/scala\/wp-json\/wp\/v2\/posts\/231","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.kindsonthegenius.com\/scala\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.kindsonthegenius.com\/scala\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.kindsonthegenius.com\/scala\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.kindsonthegenius.com\/scala\/wp-json\/wp\/v2\/comments?post=231"}],"version-history":[{"count":10,"href":"https:\/\/www.kindsonthegenius.com\/scala\/wp-json\/wp\/v2\/posts\/231\/revisions"}],"predecessor-version":[{"id":272,"href":"https:\/\/www.kindsonthegenius.com\/scala\/wp-json\/wp\/v2\/posts\/231\/revisions\/272"}],"wp:attachment":[{"href":"https:\/\/www.kindsonthegenius.com\/scala\/wp-json\/wp\/v2\/media?parent=231"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.kindsonthegenius.com\/scala\/wp-json\/wp\/v2\/categories?post=231"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.kindsonthegenius.com\/scala\/wp-json\/wp\/v2\/tags?post=231"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}