{"id":41,"date":"2021-11-09T14:48:23","date_gmt":"2021-11-09T14:48:23","guid":{"rendered":"https:\/\/blog.kevinyohe.dev\/?p=41"},"modified":"2021-11-09T18:13:49","modified_gmt":"2021-11-09T18:13:49","slug":"jackson-objectmapper","status":"publish","type":"post","link":"https:\/\/blog.kevinyohe.dev\/?p=41","title":{"rendered":"Jackson &#8211; ObjectMapper"},"content":{"rendered":"\n<p>Use this if you want to make json files or read json text strings<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Class:<\/h4>\n\n\n\n<div class=\"wp-block-file\"><a href=\"https:\/\/blog.kevinyohe.dev\/wp-content\/uploads\/2021\/11\/OrderSerializer.java\">OrderSerializer<\/a><a href=\"https:\/\/blog.kevinyohe.dev\/wp-content\/uploads\/2021\/11\/OrderSerializer.java\" class=\"wp-block-file__button\" download>Download<\/a><\/div>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>OrderSerializer<\/strong>\nid\nname\n<\/pre>\n\n\n\n<p>Problem(s):<br>Want to get json out in a file<br>Need to read\/create object from json later<\/p>\n\n\n\n<p>Steps:<br>(Add maven\/grade dependencies)<br>Create pojo to hold the data ie &#8220;OrderSerializer&#8221;, add jackson databind<\/p>\n\n\n\n<p>Create some ObjectMappers that will Map Objects to Json or Json to Objects<br><br><br>Caveats: I needed to add a constructor with super(); in it, not sure why.<\/p>\n\n\n\n<p><strong>OrderSerializerImplemeted.java<\/strong> <\/p>\n\n\n\n<div class=\"wp-block-file\"><a href=\"https:\/\/blog.kevinyohe.dev\/wp-content\/uploads\/2021\/11\/OrderSerializerImplemented.zip\">OrderSerializerImplemented<\/a><a href=\"https:\/\/blog.kevinyohe.dev\/wp-content\/uploads\/2021\/11\/OrderSerializerImplemented.zip\" class=\"wp-block-file__button\" download>Download<\/a><\/div>\n\n\n<div class=\"wp-block-syntaxhighlighter-code alignwide\"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\nimport java.io.File;\nimport java.io.IOException;\n\n\/*\nSome Jackson Object Mapper Code\nhttps:\/\/www.youtube.com\/watch?v=pv1VCFWTP-I&amp;ab_channel=SwatechTalks\n *\/\npublic class OrderSerializerImplemented {\n    public static void main(String&#x5B;] args) {\n        var order1 = new OrderSerializer(&quot;ID123&quot;, &quot;Joey Mc Doughey&quot;);\n        var order2 = new OrderSerializer(&quot;IDID1010&quot;, &quot;Kevin Mc Douchy&quot;);\n\n        ObjectMapper objectMapper = new ObjectMapper();\n\n        try {\n            \/\/ Writing files to files, same them for later.\n            objectMapper.writeValue(new File(&quot;target\/order1.json&quot;), order1);\n            objectMapper.writeValue(new File(&quot;target\/order2.json&quot;), order2);\n        } catch (IOException e) {\n            e.printStackTrace();\n        }\n\n        \/\/ load from a string literal\n        try {\n            ObjectMapper objectMapper1 = new ObjectMapper();\n            String orderJson = &quot;{\\&quot;id\\&quot;:\\&quot;ID123\\&quot;,\\&quot;name\\&quot;:\\&quot;Joey Mc Doughey\\&quot;}&quot;;\n            \/\/ Put the String data in objectMapper using OrderSerializer.class as the Class to use\n            OrderSerializer coolOrder = objectMapper1.readValue(orderJson, OrderSerializer.class);\n            System.out.println(coolOrder.getId());\n        } catch (final Exception e){\n            e.printStackTrace();\n        } finally {\n            System.out.printf(&quot;done with reading object from file&quot;);\n        }\n\n        \/\/ Using JsonNode to map string as an json object\n        String orderJson = &quot;{\\&quot;id\\&quot;:\\&quot;ID123\\&quot;,\\&quot;name\\&quot;:\\&quot;Blaze Mc Weedy\\&quot;}&quot;;\n        ObjectMapper objectMapper2 = new ObjectMapper();\n        JsonNode jsonNode = null;\n        try {\n            jsonNode = objectMapper2.readTree(orderJson);\n        } catch (JsonProcessingException e) {\n            e.printStackTrace();\n        }\n        System.out.println(&quot;jsonNode.get(\\&quot;name\\&quot;).asText() = &quot; + jsonNode.get(&quot;name&quot;).asText());\n        System.out.println(&quot;jsonNode.get(\\&quot;id\\&quot;).asText() = &quot; + jsonNode.get(&quot;id&quot;).asText());\n        \/\/ now lets write it all out as a string through objectMapper\n        ObjectMapper objectMapper3 = new ObjectMapper();\n        try {\n            System.out.println(&quot;Here's the whole Json String or an error: &quot;);\n            System.out.println(objectMapper3.writeValueAsString(jsonNode));\n            System.out.println(&quot;Here's the same data, just nicer to look at.&quot;);\n            System.out.println(jsonNode.toPrettyString());\n        } catch (JsonProcessingException e) {\n            e.printStackTrace();\n        }\n    }\n}\n\n\n<\/pre><\/div>\n\n\n<p><strong>Here&#8217;s the console output:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code alignwide\"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nID123\ndone with reading object from filejsonNode.get(&quot;name&quot;).asText() = Blaze Mc Weedy\njsonNode.get(&quot;id&quot;).asText() = ID123\nHere's the whole Json String or an error: \n{&quot;id&quot;:&quot;ID123&quot;,&quot;name&quot;:&quot;Blaze Mc Weedy&quot;}\nHere's the same data, just nicer to look at.\n{\n  &quot;id&quot; : &quot;ID123&quot;,\n  &quot;name&quot; : &quot;Blaze Mc Weedy&quot;\n}\n\nProcess finished with exit code 0\n<\/pre><\/div>\n\n\n<figure class=\"wp-block-embed alignwide is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\"><div class=\"wp-block-embed__wrapper\">\n<iframe loading=\"lazy\" title=\"Convert Java to JSON &amp; JSON to Java Object | Parse JSON in Java | ObjectMapper in Jackson API\" width=\"750\" height=\"422\" src=\"https:\/\/www.youtube.com\/embed\/pv1VCFWTP-I?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe>\n<\/div><\/figure>\n","protected":false},"excerpt":{"rendered":"<p>Use this if you want to make json files or read json text strings Class: OrderSerializer id name Problem(s):Want to get json out in a fileNeed to read\/create object from json later Steps:(Add maven\/grade dependencies)Create pojo to hold the data ie &#8220;OrderSerializer&#8221;, add jackson databind Create some ObjectMappers that will Map Objects to Json or&hellip; <a class=\"more-link\" href=\"https:\/\/blog.kevinyohe.dev\/?p=41\">Continue reading <span class=\"screen-reader-text\">Jackson &#8211; ObjectMapper<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-41","post","type-post","status-publish","format-standard","hentry","category-uncategorized","entry"],"_links":{"self":[{"href":"https:\/\/blog.kevinyohe.dev\/index.php?rest_route=\/wp\/v2\/posts\/41","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.kevinyohe.dev\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.kevinyohe.dev\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.kevinyohe.dev\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.kevinyohe.dev\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=41"}],"version-history":[{"count":13,"href":"https:\/\/blog.kevinyohe.dev\/index.php?rest_route=\/wp\/v2\/posts\/41\/revisions"}],"predecessor-version":[{"id":60,"href":"https:\/\/blog.kevinyohe.dev\/index.php?rest_route=\/wp\/v2\/posts\/41\/revisions\/60"}],"wp:attachment":[{"href":"https:\/\/blog.kevinyohe.dev\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=41"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.kevinyohe.dev\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=41"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.kevinyohe.dev\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=41"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}