Write object to json java

Jackson 2 – Convert Java Object to / from JSON

In this tutorial, we will show you how to use Jackson 2.x to convert Java objects to / from a JSON.

1. Basic

1.1 Convert a Staff object to from JSON.

writeValue(. ) – Java Objects to JSON

 ObjectMapper mapper = new ObjectMapper(); // Java object to JSON file mapper.writeValue(new File("c:\\test\\staff.json"), new Staff()); // Java object to JSON string String jsonString = mapper.writeValueAsString(object); 

readValue(. ) – JSON to Java Objects

 ObjectMapper mapper = new ObjectMapper(); //JSON file to Java object Staff obj = mapper.readValue(new File("c:\\test\\staff.json"), Staff.class); //JSON URL to Java object Staff obj = mapper.readValue(new URL("http://some-domains/api/name.json"), Staff.class); //JSON string to Java Object Staff obj = mapper.readValue("", Staff.class); 

P.S Tested with Jackson 2.9.8

Note
Read this How to parse JSON with Jackson, containing Jackson examples like Object to/from JSON, @JsonView , @JsonProperty , @JsonInclude , @JsonIgnore , and some FAQs.

Читайте также:  visibility

1. Download Jackson

1.1 Declares jackson-databind , it will pull in jackson-annotations and jackson-core

  com.fasterxml.jackson.core jackson-databind 2.9.8  

1.2 Review the Jackson dependencies :

 $ mvn dependency:tree \- com.fasterxml.jackson.core:jackson-databind:jar:2.9.8:compile [INFO] +- com.fasterxml.jackson.core:jackson-annotations:jar:2.9.0:compile [INFO] \- com.fasterxml.jackson.core:jackson-core:jar:2.9.8:compile 

Difference between Jackson 1 and Jackson 2
Most of the APIs still maintains the same method name and signature, just the packaging is different.

2. POJO

A simple Java object for testing.

 public class Staff < private String name; private int age; private String[] position; // Array private Listskills; // List private Map salary; // Map // getters , setters, some boring stuff > 

3. Java Objects to JSON

 package com.mkyong; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; import java.io.IOException; import java.math.BigDecimal; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class JacksonExample1 < public static void main(String[] args) < ObjectMapper mapper = new ObjectMapper(); Staff staff = createStaff(); try < // Java objects to JSON file mapper.writeValue(new File("c:\\test\\staff.json"), staff); // Java objects to JSON string - compact-print String jsonString = mapper.writeValueAsString(staff); System.out.println(jsonString); // Java objects to JSON string - pretty-print String jsonInString2 = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(staff); System.out.println(jsonInString2); >catch (IOException e) < e.printStackTrace(); >> private static Staff createStaff() < Staff staff = new Staff(); staff.setName("mkyong"); staff.setAge(38); staff.setPosition(new String[]); Map salary = new HashMap() >; staff.setSalary(salary); staff.setSkills(Arrays.asList("java", "python", "node", "kotlin")); return staff; > > 

4. JSON to Java Object

 package com.mkyong; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; import java.io.IOException; public class JacksonExample2 < public static void main(String[] args) < ObjectMapper mapper = new ObjectMapper(); try < // JSON file to Java object Staff staff = mapper.readValue(new File("c:\\test\\staff.json"), Staff.class); // JSON string to Java object String jsonInString = ""; Staff staff2 = mapper.readValue(jsonInString, Staff.class); // compact print System.out.println(staff2); // pretty print String prettyStaff1 = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(staff2); System.out.println(prettyStaff1); > catch (IOException e) < e.printStackTrace(); >> > 

References

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Dear Mkyong,hi how can i convert below json string to object
“flightItinerary”: [
“price”: “includesTax”: true,
“currencyCode”: “KWD”,
“amount”: 78.200135,
“pricePerAdult”: 67.4,
“pricePerChild”: 0,
“pricePerPassenger”: 0,
“totalAmount”: 78.200135,
“totalPricePerAdult”: 77.706,
“totalPricePerChild”: 0,
“totalPricePerPassenger”: 0,
“name”: “Promo”
>,
“outboundLeg”: “segments”: [
“flightClass”: “Economy”,
“flightNumber”: “designator”: “SG”,
“number”: ” 14″
>,
“DepartureDateTime”: “2019-12-22T01:55:00”,
“ArrivalDateTime”: “2019-12-22T06:25:00”,
“DepartureAirportCode”: “DXB”,
“ArrivalAirportCode”: “BOM”
>
]
>,
“inboundLeg”: null,
“Leg1”: null,
“Leg2”: null,
“Leg3”: null,
“Leg4”: null,
“Leg5”: null,
“deeplinkURL”: “https://handoff.wego.com/flights/continue?currency=SAR&url_locale=en&site_code=SA&device_type=desktop&app_type=WEB_APP&domain=sa.wego.com&fare_id=96393e5d1ec79e1a-ap-southeast-1:cleartrip.sa:0&placement_type=metasearch&route=JED-CAI&search_id=96393e5d1ec79e1a-ap-southeast-1&trip_id=cJED:cCAI:2019-11-27&pwa=false&api_version=2&integration_code=cleartrip.com&fare_index=2&total_fares=14&awsalb=qInQlA9JzisLpEc7M5K%2BWhzJsjdzLrxjZee0LnA2qTKaNicLxntSz2X0texziNNWD3odDDNDfY%2BtNWIGbnW6suE1YdryrUQ8Knuwu19seeAt2x1i3g%2FiUBUc5UlM&region=ap-southeast-1&currency_code=SAR&wc=2533a53f-f2ea-4520-9a8a-2e30c98cbce2&ws=02145d96-315b-4104-845c-54992dbe2391&sort=price&order=asc”
>,

I found your tutorial very helpful. Sadly, I’ve a problem. At the moment I use the mapper to convert the object into a String, for some reason it adds a extra field called “map” to my JSON:

I’m converting an object of JSONObjects into a JSON.

Источник

How to Convert a Java Object into a JSON String

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?

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 – 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.
  • Context which is surrounded by quotes (single or double), loaded from a text file etc. are called JSON strings.
    e.g.
  • 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

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

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

Keep up with software development’s evolving field

To remain relevant in the constantly changing landscape of software development, it is essential to stay up-to-date with the latest advancements and trends. Keeping abreast of new technologies and practices ensures that you are equipped with the knowledge and skills needed to succeed in this dynamic field. Learn more about how to utilize AI to optimize your software engineering in 2023.

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 dependency for JACKSON and automatically include it in your project’s classpath.

Add the following dependency to the pom file:

  com.fasterxml.jackson.core jackson-databind 2.9.8  

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 wp-block-heading">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 EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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'; 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

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:

  com.google.code.gson gson 2.3.1  

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

/** * 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; >>

Step 3:RUN UseGSONapitoConvertJavaOBJtoJASONstring

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.

  1. Create a new project (Maven is recommended)
  2. Include the JAR filesinto 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 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.

Tabnine

Tabnine is an intelligent, AI-driven code completion tool that can cut your coding time, reduce mistakes, and make best practice suggestions.

The following article is brought to you by Tabnine - an AI-powered tool that uses generative models to improve software development

More from Java Tutorials

Top 10 online Java compilers

A Beginners Guide to Lambda Expressions in Java

5 Java Frameworks to Build Scalable Web Applications

Top 9 Free Java Process Monitoring Tools & How to Choose One

Java is one of the most used programming languages in the world. It allows developers…

Thirty-six years after its inception, C++ is a programming language that remains persistently popular. Partially…

In 2021, Java is still the best programming language to learn. Especially if you want…

Источник

Оцените статью