Gson Tutorial | Create a Java application with GSON library using Maven

Gson Tutorial - Create a Java application with GSON library using Maven



Create a normal Java application with maven and add the following dependencies in the pom.xml

add gson dependency.

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.javainspires</groupId>
 <artifactId>gsontutorial</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <name>Java Inspires Gson</name>


 <dependencies>
  <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
  <dependency>
   <groupId>com.google.code.gson</groupId>
   <artifactId>gson</artifactId>
   <version>2.8.5</version>
  </dependency>

 </dependencies>
</project>


Then create a simple java class with main method.

GsonMain.java
package com.javainspires.gsontutorial;

import com.google.gson.Gson;

public class GsonMain {

 //lets have main method
 
 public static void main(String[] args) {
  
  // create a Gson instance
  Gson gson = new Gson();
  
  //take a string and convert that into json using gson object
  
  String s1 = "Welcome to Java Inspires";
  
  //This method serializes the specified object into its equivalent Json representation.
  String jsonString = gson.toJson(s1);
  
  //print the json string
  
  System.out.println(">>>>> "+jsonString);
  
 }
}




Post a Comment

Previous Post Next Post