How to convert json to object in java

How can we convert a JSON string to a JSON object in Java?

The JSON stands for JavaScript Object Notation and it can be used to transfer and storage of data.
The JSONObject can parse text from a String to produce a map-like object. The object provides methods for manipulating its contents, and for producing a JSON compliant object serialization. The JSONArray can parse text from a String to produce a vector-like object. The object provides methods for manipulating its contents, and for producing a JSON compliant array serialization.

In the below two examples, We can convert a JSON string to a JSON object.

Example 1

import org.json.JSONObject; import org.json.JSONArray; public class StringToJSONTest < public static void main(String args[]) < String str = "[,, ]"; JSONArray array = new JSONArray(str); for(int i=0; i < array.length(); i++) < JSONObject object = array.getJSONObject(i); System.out.println(object.getString("No")); System.out.println(object.getString("Name")); >> >

Output

Example 2

import org.json.*; public class StringToJsonObjectTest < public static void main(String[] args) < String str = ""; JSONObject json = new JSONObject(str); System.out.println(json.toString()); String tech = json.getString("technology"); System.out.println(tech); > >

Источник

Convert JSON File to Java Object in Java using Gson

In this Java Gson tutorial we learn how to convert a JSON file into a Java object using the Gson class of the Gson library. By different Java example programs we show you how to convert a JSON file into a HashMap object, a list of Map, an object of custom defined classes or a List of objects.

Читайте также:  What is an object factory in java

How to add Gson to the Java project

To use the Gson library in the Gradle build project, add the following dependency into the build.gradle file.

implementation group: 'com.google.code.gson', name: 'gson', version: '2.8.7'

To use the Gson library in the Maven build project, add the following dependency into the pom.xml file.

  com.google.code.gson gson 2.8.7 

Or you can download the Gson jar file from Maven Central at gson-2.8.7.jar

To have more information about the Gson library you can visit the project repository at github.com/google/gson

How to convert JSON File to HashMap

For example, we have a JSON file at D:\Data\sample1.json with the content as below.

< "firstName": "Simple", "lastName": "Solution", "email": "contact@simplesolution.dev", "website": "https://simplesolution.dev", "address": < "street": "Simple Street", "city": "City Name", "country": "Country Name" > >

In the following Java example program, we show you how to read the JSON file above and convert it to a HashMap object using Java FileReader class and Gson.fromJson() method.

import com.google.gson.Gson; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.HashMap; public class JsonFileToJavaObjectExample1  public static void main(String. args) throws FileNotFoundException  FileReader fileReader = new FileReader("D:\\Data\\sample1.json"); Gson gson = new Gson(); HashMapString, String> result = gson.fromJson(fileReader, HashMap.class); System.out.println("Converted HashMap object: "); System.out.println(result); > >
Converted HashMap object: , email=contact@simplesolution.dev>

How to convert JSON File to List of Map

For example, we have a JSON file at D:\Data\sample2.json with the content to store a list of objects as below.

[ < "firstName": "Simple", "lastName": "Solution", "email": "contact@simplesolution.dev", "website": "https://simplesolution.dev", "address": < "street": "Simple Street", "city": "City Name", "country": "Country Name" > >, < "firstName": "Java", "lastName": "Tutorial", "email": "java@simplesolution.dev", "website": "https://simplesolution.dev", "address": < "street": "Test Street", "city": "City Name", "country": "Country Name" > >, < "firstName": "Gson", "lastName": "Learn", "email": "gson@simplesolution.dev", "website": "https://simplesolution.dev/tag/gson", "address": < "street": "Gson Street", "city": "City Name", "country": "Country Name" > > ]

In the following Java example program, we show you how to read the JSON file above and convert it to a List of Map objects using Java FileReader class and Gson.fromJson() method.

import com.google.gson.Gson; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.List; import java.util.Map; public class JsonFileToJavaObjectExample2  public static void main(String. args) throws FileNotFoundException  FileReader fileReader = new FileReader("D:\\Data\\sample2.json"); Gson gson = new Gson(); ListMap> list = gson.fromJson(fileReader, List.class); System.out.println("Converted List of HashMap: "); for (Map item : list)  System.out.println(item); > > >
Converted List of HashMap: > > >

How to convert JSON File to Java object

In the following Java example program, we show you how to convert the JSON file to an object of a custom defined class.

Firstly we define the Address and Customer class to represent the customer record as the below Java code.

public class Address  private String street; private String city; private String country; public String getStreet()  return street; > public void setStreet(String street)  this.street = street; > public String getCity()  return city; > public void setCity(String city)  this.city = city; > public String getCountry()  return country; > public void setCountry(String country)  this.country = country; > >
public class Customer  private String firstName; private String lastName; private String email; private String website; private Address address; public String getFirstName()  return firstName; > public void setFirstName(String firstName)  this.firstName = firstName; > public String getLastName()  return lastName; > public void setLastName(String lastName)  this.lastName = lastName; > public String getEmail()  return email; > public void setEmail(String email)  this.email = email; > public String getWebsite()  return website; > public void setWebsite(String website)  this.website = website; > public Address getAddress()  return address; > public void setAddress(Address address)  this.address = address; > >

The Java program below converts D:\Data\sample1.json to a Customer object.

import com.google.gson.Gson; import java.io.FileNotFoundException; import java.io.FileReader; public class JsonFileToJavaObjectExample3  public static void main(String. args) throws FileNotFoundException  FileReader fileReader = new FileReader("D:\\Data\\sample1.json"); Gson gson = new Gson(); Customer customer = gson.fromJson(fileReader, Customer.class); System.out.println("First Name: " + customer.getFirstName()); System.out.println("Last Name: " + customer.getLastName()); System.out.println("Email: " + customer.getEmail()); System.out.println("Website: " + customer.getWebsite()); System.out.println("Street: " + customer.getAddress().getStreet()); System.out.println("City: " + customer.getAddress().getCity()); System.out.println("Country: " + customer.getAddress().getCountry()); > >
First Name: Simple Last Name: Solution Email: contact@simplesolution.dev Website: https://simplesolution.dev Street: Simple Street City: City Name Country: Country Name

How to convert JSON File to List of objects

The Java program below converts D:\Data\sample2.json to a List of Customer objects.

import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.io.FileNotFoundException; import java.io.FileReader; import java.lang.reflect.Type; import java.util.List; public class JsonFileToJavaObjectExample4  public static void main(String. args) throws FileNotFoundException  FileReader fileReader = new FileReader("D:\\Data\\sample2.json"); Gson gson = new Gson(); Type type = new TypeTokenListCustomer>>()<>.getType(); ListCustomer> customers = gson.fromJson(fileReader, type); for(Customer customer : customers)  System.out.println("First Name: " + customer.getFirstName()); System.out.println("Last Name: " + customer.getLastName()); System.out.println("Email: " + customer.getEmail()); System.out.println("Website: " + customer.getWebsite()); System.out.println("Street: " + customer.getAddress().getStreet()); System.out.println("City: " + customer.getAddress().getCity()); System.out.println("Country: " + customer.getAddress().getCountry()); System.out.println(); > > >
First Name: Simple Last Name: Solution Email: contact@simplesolution.dev Website: https://simplesolution.dev Street: Simple Street City: City Name Country: Country Name First Name: Java Last Name: Tutorial Email: java@simplesolution.dev Website: https://simplesolution.dev Street: Test Street City: City Name Country: Country Name First Name: Gson Last Name: Learn Email: gson@simplesolution.dev Website: https://simplesolution.dev/tag/gson Street: Gson Street City: City Name Country: Country Name

Источник

How to convert a JSON to Java Object using the Jackson library in Java?

The ObjectMapper class is the most important class in the Jackson library. We can convert a JSON to Java Object using the readValue() method of ObjectMapper class, this method deserializes a JSON content from given JSON content String.

Syntax

public readValue(String content, JavaType valueType) throws IOException, JsonParseException, JsonMappingException

Example

import java.io.*; import java.util.*; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.*; public class JSONToJavaObjectTest < public static void main(String args[]) throws JsonGenerationException, JsonMappingException, IOException < Employee emp1 = new Employee(); emp1.setFirstName("Raja"); emp1.setLastName("Ramesh"); emp1.setId(115); emp1.getTechnologies().add("Java"); emp1.getTechnologies().add("Selenium"); emp1.getTechnologies().add("Spark"); ObjectMapper mapper = new ObjectMapper(); String jsonStr = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(emp1); System.out.println(jsonStr); System.out.println("Deserializing JSON to Object:"); Employee emp2 = mapper.readValue(jsonStr, Employee.class); System.out.println(emp2.getId() + " " + emp2.getFirstName() + " " + emp2.getLastName() + " " + emp2.getTechnologies()); > > // Employee class class Employee < private int id; private String firstName; private String lastName; private List technologies = new ArrayList<>(); public int getId() < return id; >public void setId(int id) < this.id = id; >public String getFirstName() < return firstName; >public void setFirstName(String firstName) < this.firstName = firstName; >public String getLastName() < return lastName; >public void setLastName(String lastName) < this.lastName = lastName; >public List getTechnologies() < return technologies; >public void setTechnologies(List technologies) < this.technologies = technologies; >>

Output

 < "id" : 115, "firstName" : "Raja", "lastName" : "Ramesh", "technologies" : [ "Java", "Selenium", "Spark" ] >Deserializing JSON to Object: 115 Raja Ramesh [Java, Selenium, Spark]

Источник

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