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.
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.
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 front end 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 Java Object to 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, 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(); }
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"}
com.google.gson
. 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, any dependency for GSON and automatically include in your project’s classpath as follows:
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();
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}
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:
Run to convert your Java Obj to JSON string.
Thanks for reading ❤
If you liked this post, share it with all of your programming buddies!
Follow us on Facebook | Twitter
#java #json #xml