Convert Java object to JSON

This tutorial shows 2 ways for converting Java objects to JSON.

This kind of conversion is normally done via third-party libraries as it’s not supported by the JDK itself and requires a hard work to do it manually.

1- Gson

The most popular library used for converting Java objects to JSON is the Google Gson library.

Using Gson, you can get a JSON String out of an object through one line as the following:

All you have to do is to include gson jar in the classpath.

P.S: It’s worth to mention that toJson() method accepts also Hashmap, ArrayList and Arrays. 

2- Jackson

Another popular library is Jackson.

In order to convert Java objects to JSON using Jackson, you have to include 3 libraries: jackson-annotations, jackson-core and jackson-databind.

Here is the way:

P.S: writeValueAsString() method accepts also Hashmap, ArrayList and Arrays. 

Hussein Terek

Founder of programmergate.com, I have a passion in software engineering and everything related to java environment.

You may also like...

8
Leave a Reply

avatar
8 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
6 Comment authors
BrandonLutBobbyPsyncDavidhorDavidhorLelandsmaky Recent comment authors
newest oldest most voted
KennethQuoro
Guest
KennethQuoro

intestinal gas remedy studiomerliniortodonzia.it/cgi-bin/bentelan.htm mucus natural remedies

Lelandsmaky
Guest
Lelandsmaky

home wrinkle remedies https://deadline.dk/sovepiller-nettet.html homeopathic teething remedies

Davidhor
Guest
Davidhor

remedy ondemand open.edu/openlearn/profiles/zw369337 herbalive

Davidhor
Guest
Davidhor

negligence remedies open.edu/openlearn/profiles/zw369022 aromatherapy herbal pillows

Davidhor
Guest
Davidhor

herbal buy open.edu/openlearn/profiles/zw369385 lemon herbal tea

BobbyPsync
Guest
BobbyPsync

dry skin remedy open.edu/openlearn/profiles/zw369385 herbal hookah

BrandonLut
Guest
BrandonLut

herbal bath salts phentermine.html florida online pharmacy

BrandonLut
Guest
BrandonLut

natural sleep remedy tramadol.cdhost.com actos drug warning