Create a gist now

Instantly share code, notes, and snippets.

anonymous /Main.java
Created Oct 22, 2016

What would you like to do?
Serialization and Deserialization JSON in JAVA with GSON
package com.blogspot.ducnguyen.dev.json.example;
import com.google.gson.Gson;
import java.awt.Point;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* @author ducnguyen
*/
public class Main {
private static Gson gson = new Gson();
public static void main(String[] args) {
System.out.println("Serialization and Deserialization an OBJECT");
Point p1 = new Point(2, 1);
String json1 = gson.toJson(p1);
System.out.println("p1 -> json1 : " + json1);
Point p2 = gson.fromJson(json1, Point.class);
System.out.println("json1 -> p2 : " + p2.toString());
System.out.println("Serialization and Deserialization a LIST");
List<Point> l1 = Arrays.asList(new Point(2, 1), new Point(3, 4));
String json2 = gson.toJson(l1);
System.out.println("l1 -> json2 : " + json1);
List<Point> l2 = gson.fromJson(json2, List.class);
System.out.println("json2 -> l2 : " + l2.toString());
System.out.println("Create object fields with MAP");
Map<String, Object> jsonObject = new HashMap<>();
jsonObject.put("integer", 100);
jsonObject.put("string", "hello world");
jsonObject.put("boolean", Boolean.TRUE);
String json3 = gson.toJson(jsonObject);
System.out.println("jsonObject -> json3 : " + json3);
System.out.println("Deserialization MAP");
Map<String, Object> jsonObject2 = gson.fromJson(json3, Map.class);
System.out.println("json3 -> jsonObject2 : "+ jsonObject2.toString());
}
}
<?xml version="1.0" encoding="UTF-8"?>
<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.blogspot.ducnguyen.dev.json</groupId>
<artifactId>json-example</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3.1</version>
</dependency>
</dependencies>
</project>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment