Table of contents
Table of contents
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 usually where JSON comes in. While you might be a wizard with Java, JSON is another animal. Regardless, this blog post explains all you need to get the job done.
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:
The example below demonstrates a client-server scenario where the RESTful Web Service accepts data in XML/JSON:
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 Android app. Let’s say the mobile app is a hybrid app where the frontend is 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.
The most common way to convert a Java Object to a JSON string is to use an API. The most common APIs for this purpose are Jackson and GSON.
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:
When using MAVEN for dependency management (recommended), you can include the following dependency to download JAR files and any dependency for JACKSON and automatically include it in your project’s classpath.
Add the following dependency to the pom file:
<dependencies> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.8</version> </dependency> </dependencies>
ObjectMapper mapper = new ObjectMapper(); try { String json = mapper.writeValueAsString(cat); System.out.println("ResultingJSONstring = " + json); //System.out.println(json); } catch (JsonProcessingException e) { e.printStackTrace(); }
This example uses the following code:
class useJACKSONapiToConvertJavaOBJtoJSONstring
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; public class useJACKSONapiToConvertJavaOBJtoJSONstring { public static void main(String[] args) { Cat cat = new Cat(); cat.setId(1L); cat.setName("SiAm"); cat.setColor("Cream"); cat.setEyecolor("Blue"); cat.setBreed("Siamese"); ObjectMapper mapper = new ObjectMapper(); try { String json = mapper.writeValueAsString(cat); System.out.println("ResultingJSONstring = " + json); //System.out.println(json); } catch (JsonProcessingException e) { e.printStackTrace(); } class Cat
public class Cat { private Long id; private String name; private String color; private String eyecolor; private String breed; public Cat() { public Cat(Long id, String name) { this.id = id; this.name = name; // Getters & Setters @Override public String toString() { return "Cat{" + "id=" + id + ", name='" + name + ''' + '}'; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String getEyecolor() { return eyecolor; public void setEyecolor(String eyecolor) { this.eyecolor = eyecolor; } public String getBreed() { return breed; } public void setBreed(String breed) { this.breed = breed; } }
ResultingJSONstring = {"id":1,"name":"SiAm","color":"Cream","eyecolor":"Blue","breed":"Siamese"}
The below example shows how to use GSON API to convert a Java Object into a JSON String.
When using MAVEN for dependency management (recommended), you can include the following dependency to download JAR files and any dependency for GSON and automatically include it in your project’s classpath.
Add the following dependency to the pom file:
<dependencies> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.3.1</version> </dependency> </dependencies>
Call the GSON API using: Gson gson = new Gson();
This example uses the following code:
class UseGSONapitoConvertJavaOBJtoJASONstring
import com.google.gson.Gson; public class UseGSONapitoConvertJavaOBJtoJASONstring{ public static void main(String args[]) { CatDetails user = new CatDetails("SiAm", "Siamese", "siam.cat@gmail.com", 9, 2129991234L, "NewCatadonia", true); Gson gson = new Gson(); String json = gson.toJson(user); System.out.println(json); }
Class CatDetails
/** * Java Program to map a Java object to JSON String using GSON library. */ class CatDetails { private String name; private String breed; private String email; private int catlives; private long phone; private String city; private boolean likesMice; public CatDetails(String name, String breed, String email, int catlives, long phone, String city, boolean likesMice) { super(); this.name = name; this.email = email; this.catlives = catlives; this.phone = phone; this.city = city; this.likesMice = likesMice; this.breed = breed; //getters & setters public String getName() { return name; } public void setName(String name) { this.name = name; } public String getBreed() { return breed; } public void setBreed(String breed) { this.breed = breed; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getCatlives() { return catlives; } public void setCatlives(int catlives) { this.catlives = catlives; } public long getPhone() { return phone; } public void setPhone(long phone) { this.phone = phone; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public boolean isLikesMice() { return likesMice; } public void setLikesMice(boolean likesMice) { this.likesMice = likesMice; } }
Result
{"name":"SiAm","breed":"Siamese","email":"siam.cat@gmail.com","catlives":9,"phone":2129991234,"city":"NewCatadonia","likesMice":true}
To remain relevant in the constantly changing landscape of software development, it’s essential to stay up-to-date with the latest advancements and trends so you’re equipped with the knowledge and skills to succeed. Learn more about how to utilize AI to optimize your software engineering in 2024.
Converting a Java Obj to a 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:
Run to convert your Java Obj to JSON string.
Tabnine is the AI coding assistant helps development teams of every size use AI to accelerate and simplify the software development process without sacrificing privacy, security, or compliance. Tabnine boosts engineering velocity, code quality, and developer happiness by automating the coding workflow through AI tools customized to your team. Tabnine supports more than one million developers across companies in every industry.
Unlike generic coding assistants, Tabnine is the AI that you control:
It’s private. You choose where and how to deploy Tabnine (SaaS, VPC, or on-premises) to maximize control over your intellectual property. Rest easy knowing that Tabnine never stores or shares your company’s code.
It’s personalized. Tabnine delivers an optimized experience for each development team. It’s context-aware and delivers precise and personalized recommendations for code generation, code explanations, guidance, and for test and documentation generation.
It’s protected. Tabnine is built with enterprise-grade security and compliance at its core. It’s trained exclusively on open source code with permissive licenses, ensuring that customers are never exposed to legal liability.
Tabnine provides accurate and personalized code completions for code snippets, whole lines, and full functions. Tabnine Chat in the IDE allows developers to communicate with a chat agent in natural language and get assistance with various coding tasks, such as:
Try Tabnine for free today or contact us to learn how we can help accelerate your software development.