Help us improve by sharing
your feedback.
How to Convert a Java Object
into a JSON String
by Susan Bud | Posted on June 27, 2019
When learning how to write Java-based software, one of the first snags
developers hit is how to connect their code with other software. This is
Help us improve by sharing
Help us improve by sharing
usually where JSON comes in. While you might be a wizard with Java,
your feedback.
JSON is another animal. Regardless, this blog post explains all you need
to get the job done.
What is a Java Object?
A Java object is a combination of data and procedures that work on
the available data.
Objects have both states and behaviors. In Java, an object is created
using the keyword “new”.
Objects are created from templates known as classes.
An object is an instance of a class.
For example, our “Cat object” has:States – color, name, breed
the state of an object is stored in fields (variables). Behavior – purring,
eating, sleeping methods (functions) display the object’s behavior.
What is a JSON String?
JSON is an acronym for JavaScript Object Notation.
JSON was designed as a data interchange format and has a syntax
that is a subset of JavaScript.
Help us improve by sharing
Help us improve by sharing
Context which is surrounded by quotes (single or double), loaded
your feedback.
from a text file etc. are called JSON strings.
e.g.
{“id”:1,”name”:”SiAm”,”color”:”Cream”,”eyecolor”:”Blue”,”breed”:”Siam
ese”}
JSON is interoperable meaning that it’s language/platform
independent.
JSON format is used for serializing and transmitting structured data
over a network connection. It is used primarily to transmit data
between a server and mobile/web application, serving as an
alternative to XML.
Common Uses for Converting Java Obj. to JSON String
The example below demonstrates a client server scenario where the
RESTful Web Service accepts data in XML/JSON.
The RESTful web server app is designed using java:
enduser doesn’t understand the xml/json but that’s not an issue
the enduser communicates with a mobile app which might be android
the enduser communicates with a mobile app which might be php
the mobile/web app communicates with the RESTful web service via
XML/JSON
When would you want to convert from Java Obj to JSON
string?
In our example diagram above, our RESTful web service was designed
using Java.
Since Java objects are only understood by Java applications we need to
convert the java object to JSON when creating a web service for the
Help us improve by sharing
Help us improve by sharing
android app. Let’s say the mobile app is a hybrid app where the front end is
your feedback.
handled by android view and the data transactions are sent through its own
web services using JSON. In this instance we need to send/receive
requests from the android app to/from our database using web services/api
using JSON data structure.
JSON is a simple string format data. JSON is readable format. It is
very easy to read and infer information from it.
JSON format is simple to use.
JSON is quite light-weight compared to other formats like XML etc,.
JSON format can be easily converted into Java objects in an
Object oriented manner.
JSON is interoperable: program and platform independent.
Java Object to Json String: Tutorial
Step by step examples of how to convert Java Object to JSON string
The most common way to convert Java Object to JSON string is to
use an API. The most common APIs for this purpose are Jackson and
GSON.
JACKSON API example
This example shows how to use JACKSON API to convert a Java
Object into a JSON String.
We can use the ObjectMapper class provided by the Jackson API for our
conversion.
writeValueAsString() is used to convert java obj to JSON
readValue() is used to convert JSON into java obj
Step 1: Include the JACKSON JAR files into your classpath.
When using MAVEN for dependency management (recommended) you
can include the following dependency to download JAR files, any
Help us improve by sharing
Help us improve by sharing
dependency for JACKSON and automatically include it in your project’s
your feedback.
classpath.
Add the following dependency to the pom file:
1. <dependencies>
2. <dependency>
3. <groupId>com.fasterxml.jackson.core</groupId>
4. <artifactId>jackson-databind</artifactId>
5. <version>2.9.8</version>
6. </dependency>
7. </dependencies>
Step 2: Use the Jackson API ObjectMapper class to convert Java
Object to a JSON string
1. ObjectMapper mapper = new ObjectMapper();
2. try {
3. String json = mapper.writeValueAsString(cat);
4. System.out.println("ResultingJSONstring = " + json);
5. //System.out.println(json);
6. } catch (JsonProcessingException e) {
7. e.printStackTrace();
8. }
This example uses the following code:
class useJACKSONapiToConvertJavaOBJtoJSONstring
1. import com.fasterxml.jackson.core.JsonProcessingException;
2. import com.fasterxml.jackson.databind.ObjectMapper;
3. public class useJACKSONapiToConvertJavaOBJtoJSONstring {
4. public static void main(String[] args) {
5. Cat cat = new Cat();
6. cat.setId(1L);
7. cat.setName("SiAm");
8. cat.setColor("Cream");
9. cat.setEyecolor("Blue");
10. cat.setBreed("Siamese");
11. ObjectMapper mapper = new ObjectMapper();
12. try {
13. String json = mapper.writeValueAsString(cat);
14. System.out.println("ResultingJSONstring = " + json);
15. //System.out.println(json);
16. } catch (JsonProcessingException e) {
17. e.printStackTrace();
18. }
19. class Cat
1. public class Cat {
2. private Long id;
3. private String name;
4. private String color;
5. private String eyecolor;
6. private String breed;
7. public Cat() {
8. public Cat(Long id, String name) {
9. this.id = id;
Help us improve by sharing
Help us improve by sharing
10. this.name = name; your feedback.
11. // Getters & Setters
12. @Override
13. public String toString() {
14. return "Cat{" +
15. "id=" + id +
16. ", name='" + name +
17. '\'' +
18. '}';
19. public Long getId() { return id; }
20. public void setId(Long id) { this.id = id; }
21. public String getName() { return name; }
22. public void setName(String name) { this.name = name; }
23. public String getColor() { return color; }
24. public void setColor(String color) { this.color = color; }
25. public String getEyecolor() { return eyecolor;
26. public void setEyecolor(String eyecolor) { this.eyecolor = eyecolor; }
27. public String getBreed() { return breed; }
28. public void setBreed(String breed) { this.breed = breed; }
29. }
Step 3: RUN useJACKSONapitoConvertJavaOBJtoJSONstring
1. ResultingJSONstring =
{"id":1,"name":"SiAm","color":"Cream","eyecolor":"Blue","breed":"Siamese"}
GSON API example
Find the best examples of Java code snippets using com.google.gson.
The below example shows how to use GSON API to convert a Java Object
into a JSON String.
Step 1: Include the GSON JAR files into your classpath
When using MAVEN for dependency management (recommended) you
can include the following dependency to download JAR files, any
dependency for GSON and automatically include in your project’s
classpath as follows:
Add the following dependency to the pom file:
1. <dependencies>
2. <dependency>
3. <groupId>com.google.code.gson</groupId>
4. <artifactId>gson</artifactId>
5. <version>2.3.1</version>
6. </dependency>
7. </dependencies>
Step 2: Create class UseGSONapitoConvertJavaOBJtoJASONstring
call the GSON API using: Gson gson = new Gson();
Help us improve by sharing
Help us improve by sharing
This example uses the following code: your feedback.
class UseGSONapitoConvertJavaOBJtoJASONstring
1. import com.google.gson.Gson;
2. public class UseGSONapitoConvertJavaOBJtoJASONstring{
3. public static void main(String args[]) {
4. CatDetails user = new CatDetails("SiAm",
5. "Siamese",
6. "[email protected]",
7. 9,
8. 2129991234L,
9. "NewCatadonia",
10. true);
11. Gson gson = new Gson();
12. String json = gson.toJson(user);
13. System.out.println(json);
14. }
Class CatDetails
1. /**
2. * Java Program to map a Java object to JSON String using GSON library.
3. */
4. class CatDetails {
5. private String name;
6. private String breed;
7. private String email;
8. private int catlives;
9. private long phone;
10. private String city;
11. private boolean likesMice;
12.
13. public CatDetails(String name, String breed, String email, int catlives, long
phone,
14. String city, boolean likesMice) {
15. super();
16. this.name = name;
17. this.email = email;
18. this.catlives = catlives;
19. this.phone = phone;
20. this.city = city;
21. this.likesMice = likesMice;
22. this.breed = breed;
23. //getters & setters
24. public String getName() {
25. return name;
26. }
27. public void setName(String name) {
28. this.name = name;
29. }
30. public String getBreed() {
31. return breed;
32. }
33. public void setBreed(String breed) {
34. this.breed = breed;
35. }
36. public String getEmail() {
37. return email;
38. }
39. public void setEmail(String email) {
40. this.email = email;
Help us improve by sharing
Help us improve by sharing
41. } your feedback.
42. public int getCatlives() {
43. return catlives;
44. }
45. public void setCatlives(int catlives) {
46. this.catlives = catlives;
47. }
48. public long getPhone() {
49. return phone;
50. }
51. public void setPhone(long phone) {
52. this.phone = phone;
53. }
54. public String getCity() {
55. return city;
56. }
57.
58. public void setCity(String city) {
59. this.city = city;
60. }
61. public boolean isLikesMice() {
62. return likesMice;
63. }
64. public void setLikesMice(boolean likesMice) {
65. this.likesMice = likesMice;
66. }
67. }
Result:
Step 3:RUN UseGSONapitoConvertJavaOBJtoJASONstring
1. {"name":"SiAm","breed":"Siamese","email":"
[email protected]","catlives":9,"phone":
2129991234,"city":"NewCatadonia","likesMice":true}
Conclusion
Converting a Java Obj to JSON string is simple using JACKSON or GSON
API.
In our examples we provided the code to make it easy for you to reproduce
in your IDE.
All you need to do is:
1. Create a new project (Maven is recommended)
2. Include the JAR files into your classpath by adding
dependencies to the pom file.
3. Create your classes
4. Use the JACKSON API: ObjectMapper mapper class
call writeValueAsString(ObjToConvert) method by passing object we
Help us improve by sharing
Help us improve by sharing
want to convert into JSON your feedback.
or
Use GSON API: class Gson
call toJson(ObjToConvert) method by passing the object we want to
convert into JSON;
Run to convert your Java Obj to JSON string.
Share this:
Share 0 Tweet Share
Java Tutorials java code geeks
About the author
I am a technical content writer at Tabnine
Related Posts
Help us improve by sharing
Help us improve by sharing
your feedback.
February 18, 2019
How to Install Android Studio on Ubuntu (Step by Step Guide)
Help us improve by sharing
Help us improve by sharing
your feedback.
April 11, 2019
Top 9 Free Java Process Monitoring Tools & How to Choose One
June 10, 2019
Kotlin vs Scala: which is right for you?
Search … Search
Integrations
VSCode
Visual Studio
IntelliJ
Pycharm
Sublime
Atom
Eclipse
Vim
PhpStorm
RubyMine
WebStorm
Jupyter Notebook
JupyterLab Help us improve by sharing
JupyterLab Help us improve by sharing
your feedback.
Emacs
GoLand
Clion
Android Studio
Rider
DataGrip
AppCode
How to Convert a Java Object into a JSON String
Top 11 React Chart Libraries
Top 7 Golang IDEs for Go Developers
Top 40 VS Code Extensions
Top 10 Visual Studio Extensions
Top 11 Visual Studio Themes
21 Best IntelliJ Plugins
5 Best IntelliJ Themes
Top 17 Sublime Text Plugins
Run Python On Sublime Text
Top 15 Vim Plugins
Top 17 Plugins for Android Studio
21 Best Atom Packages
14 Best Plugins for Eclipse IDE
Top 25 Plugins for Webstorm
Top 17 PhpStorm Plugins
Top 9 JupyterLab Extensions
Top 12 Jupyter Notebook Extensions
Top 11 GoLand IDE Plugins
Github Copilot vs Tabnine
Kite vs Tabnine
Subscribe to Blog via Email
Enter your email address to subscribe to this blog
and receive notifications of new posts by email.
Help us improve by sharing
Help us improve by sharing
your feedback.
Email Address
Subscribe
Get Tabnine
Tabnine Academy About Terms Of Use
FAQ Contact Us Privacy Policy