How to convert a Java object into a JSON string

Posted on June 27th, 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 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.

What is a Java object? 

A Java object is a combination of data and procedures that work on the available data.

cat stores behaviours

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, like color, name, and breed. The state of an object is stored in fields (variables). 
  • Behavior, like purring, eating, and 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.
  • Context that is surrounded by quotes (single or double), loaded from a text file etc., are called JSON strings. For example:
    {“id”:1,”name”:”SiAm”,”color”:”Cream”,”eyecolor”:”Blue”,”breed”:”Siamese”}
  • 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’s 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. 
  • The enduser doesn’t understand the XML / JSON, but that’s not an issue.
  • The enduser communicates with a mobile app that might be Android.
  • The enduser communicates with a mobile app that might be php.
  • The mobile/web app communicates with the RESTful web service via XML / JSON.
●	The RESTful web server app is designed using java:

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. 

json to 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.

  • JSON is a simple string format data. JSON is readable format and it’s very easy to read and infer information from it.
  • JSON format is simple to use.
  • JSON is quite lightweight compared to other formats like XML.
  • JSON format can be easily converted into Java objects in an Object-oriented manner.
  • JSON is interoperable (program and platform independent).

Convert a Java Object to JSON String: Step-by-step tutorial

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.

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 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>

Step 2: Use the Jackson API ObjectMapper class to convert Java Object to a JSON string

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; }
 }  

Step 3: RUN useJACKSONapitoConvertJavaOBJtoJSONstring 

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 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>

Step 2: Create class UseGSONapitoConvertJavaOBJtoJASONstring

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

Step 3: RUN UseGSONapitoConvertJavaOBJtoJASONstring

{"name":"SiAm","breed":"Siamese","email":"siam.cat@gmail.com","catlives":9,"phone":2129991234,"city":"NewCatadonia","likesMice":true}

Keep up with the evolution of software development

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 2023.

Conclusion

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:

  1. Create a new project (Maven is recommended).
  2. Include the JAR files in 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 the object we want to convert into JSON
    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.

 

About Tabnine

Tabnine is the AI coding assistant that accelerates and simplifies software development while keeping your code private, secure, and compliant.

Try Tabnine Pro free for 90 days!

[cta_btn url=”https://www.tabnine.com/pricing/landing” label=”Start a free trial”]

Kotlin vs. Scala: Which is right for you?

Posted on June 10th, 2019

Kotlin or Scala? Scala or Kotlin? The two contenders for the crown of the JVM Kingdoms and the title of “Better Java” each bring something unique to the fight. But which should be the next ruler of your code?

Java is old. Not that there’s anything wrong with being old. Sometimes it can be a good thing. Math is old and we still use it. As the saying goes – if it ain’t broke don’t fix it. But that doesn’t mean we shouldn’t find ways to improve upon it. Java that is.

That is exactly what both Scala and Kotlin aim to be – a better, newer Java. It’s safe to say both have been successful in their aim, but each adds and expands on the capabilities of Java in its own way.

Before we discuss the use-cases and criteria upon which to select Kotlin or Scala for your next project, let’s get acquainted with the history, and the major strengths and weaknesses of each.

Scala

scala logo

Introduced to the world over 15 years ago in 2004, Scala was designed to address the flaws and common development issues of Java. Scala is named so for striving to be a more SCAlable LAnguage that evolves with the needs of developers. It dubs itself as a general-purpose programming language providing support for functional programming and a strong static type system.

As it was developed in the academia, Scala didn’t only serve as a proof-of-concept for a major static language on the JVM (which was pretty major at the time), but also offered a playground for different paradigms and ideas on functional programming.

Strengths

Bigger Community

Being around for 15 years made Scala a familiar face in the JVM landscape. Many developers either work with it or have worked with it, either on their own apps or those of others. This means more resources, more tutorials, and more (useful) answers on StackOverflow and Reddit.

Pattern Matching & Big Math

Calling itself “Java’s switch on steroids”, Scala’s match statement lets you match any type of data, including your own types. It also offers full support for macros and higher-kinded types, making Scala ideal for big data processing tasks.

Flexible Syntax

Scala was designed to successfully marry functional and OOP paradigms, and it does so fairly well. Delivering on the promise of “write once, run anywhere” of JVM, and combining it with a functional style of coding, Scala lets you make the best of both worlds in your code.

scala meme

Weaknesses

Slow Compilation Speed

“Scala has the right features, but its most obvious deficiency is very slow compilation.” These words were said by no other than the lead developer of Kotlin. And he’s not the only one. When it comes to complex enterprise-grade programs, it can take Scala long minutes to compile what Java and Kotlin can handle in mere seconds.

Inferior Java Compatibility

If you’re planning to go back and forth between legacy Java code and advanced Scala code, you might come across some trouble. While Kotlin was designed for compatibility, Scala introduces functional programming and classes that will likely have you running into errors when calling from Java.

Null Safety Management Inefficiency

One of the main arguments in favor of JVM languages as alternatives to Java is the way they handle the hated NPEs. When compared to Kotlin, many find Scala’s approach inefficient and clunky. To deal with NPEs, Scala replaces null values with Option, which adds some complexity to the code as it needs to be explicitly used.

Kotlin

kotlin logo

Developed by JetBrains and released to the world as open source in 2012, Kotlin quickly became one of the fastest growing languages on GitHub. Drawing heavily from Scala and aiming to solve practical problems, Kotlin brought great compilation times and perfect interoperability with Java.

Kotlin quickly attracted many tech giants who encorporated Kotlin into their stack including Google, Square, Pinterest, and Atlassian. The popularity of the young language soared when it was announced by Google as an officially adopted language for Android development.

Strengths

Corporate Backing

Say what you will about the power of collaboration in academia, it can’t compare to the strength of corporate support. With Google and JetBrains (who brought you Intellij IDE) supporting the Kotlin ecosystem, there are undeniable advantages.

Superior Java Interoperability

As I’ve mentioned in the introduction, one of the main strengths of Kotlin is its perfect compatibility with Java code. You can call Kotlin code from Java and vice versa with no errors or issues.

Concise Coding

One of the pain points of Java that Kotlin addresses is boilerplate code. In Kotlin there’s simply less of it. With less code lines, there is less room for bugs and also makes the code written easier to read.

Weaknesses

Inferior Pattern Matching

Pattern matching is not fully supported in Kotlin, and is clearly inferior to Scala in that respect. While it is possible to achieve similar results with smart application of the when clause, Scala’s matching capabilities and ease of use are far ahead.

Smaller Community

While it is growing quickly, the Kotlin community still has some catching up to do with Scala. Though Google’s support of Kotlin as an official language for Android significantly boosted its popularity, a newer community may mean less tutorials, tools and experts to lend a hand when needed.

Limited Usability

Kotlin is king when it comes to Android development. Its whole ecosystem is geared toward Android apps. But what about other applications? Not as great. Outside the Android world, Kotlin is still not as useful or applicable as Scala.

Use Cases

What most impacts your choice, at the end of the day, is the intended use of the language in the specific project (or projects) you’ll be using it for. Given the strengths and weaknesses of each, there are specific cases in which one shines over the other.

Scala for Big Data & Mixed Coding Paradigms

If you’re looking to work with big data and big math, Scala is your obvious choice. With features neither Java nor Kotlin possess (like pattern matching, macros, and higher-kinded types), and perfect compatibility with Apache Spark, Scala is the language for data science and complex mathematical modeling.

In addition, Scala lets you mix OOP and FP paradigms in your code. If your project demands this unique approach, Scala may serve you better than Kotlin or Java.

Kotlin for Android

If your project is on Android, then there’s really no question here: Kotlin is your language. Not only because it’s officially endorsed by Google, but also because it has all the tools needed for development and debugging of Android applications. In addition, Kotlin is built into Android Studio (as of version 3.0), so there isn’t even any additional installation or configuration needed before you can start coding in Kotlin.

scala in the front kotlin in the back meme

Good old Java is still both – good and old. The new kids on the block each offer improvements and expansions upon it, dealing differently with familiar issues and pain points of Java development. As always, the trick is in finding the right tool for the job – a language that is equally comfortable for you, and compatible with the goals of the project. Which is yours?