Snipt.net is closing on December 31st, 2016

For more information, please visit this blog post.

snipt

Ctrl+h for KB shortcuts

Java

Write arbitrary object as JSON

1
2
3
4
5
6
7
String json = "";
try {
    ObjectWriter ow = new ObjectMapper().writer();
    json = ow.writeValueAsString(myArbitraryObject);
} catch (Exception e) {
    LOGGER.error(e.getMessage(), e);
}
https://snipt.net/embed/02ba9ad31c1a57eab7a3374f854c2242/
https://snipt.net/raw/02ba9ad31c1a57eab7a3374f854c2242/
02ba9ad31c1a57eab7a3374f854c2242
java
Java
7
2016-12-05T18:24:25
True
False
False
/api/public/snipt/137714/
write-arbitrary-object-as-json-982a6d99
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre><a href="#L-1">1</a> <a href="#L-2">2</a> <a href="#L-3">3</a> <a href="#L-4">4</a> <a href="#L-5">5</a> <a href="#L-6">6</a> <a href="#L-7">7</a></pre></div></td><td class="code"><div class="highlight"><pre><span></span><span id="L-1"><a name="L-1"></a><span class="n">String</span> <span class="n">json</span> <span class="o">=</span> <span class="s">&quot;&quot;</span><span class="o">;</span> </span><span id="L-2"><a name="L-2"></a><span class="k">try</span> <span class="o">{</span> </span><span id="L-3"><a name="L-3"></a> <span class="n">ObjectWriter</span> <span class="n">ow</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ObjectMapper</span><span class="o">().</span><span class="na">writer</span><span class="o">();</span> </span><span id="L-4"><a name="L-4"></a> <span class="n">json</span> <span class="o">=</span> <span class="n">ow</span><span class="o">.</span><span class="na">writeValueAsString</span><span class="o">(</span><span class="n">myArbitraryObject</span><span class="o">);</span> </span><span id="L-5"><a name="L-5"></a><span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">Exception</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span> </span><span id="L-6"><a name="L-6"></a> <span class="n">LOGGER</span><span class="o">.</span><span class="na">error</span><span class="o">(</span><span class="n">e</span><span class="o">.</span><span class="na">getMessage</span><span class="o">(),</span> <span class="n">e</span><span class="o">);</span> </span><span id="L-7"><a name="L-7"></a><span class="o">}</span> </span></pre></div> </td></tr></table>
JSON, Jackson, Java, JavaScript, object2json
Copyrighted, illegal, or inappropriate content? Email [email protected].