Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.zybnet.so;
- import java.math.BigDecimal;
- import com.google.gson.Gson;
- import com.google.gson.GsonBuilder;
- import com.google.gson.JsonElement;
- import com.google.gson.JsonSyntaxException;
- public class GsonDeserialization {
- public static void main(String[] args) throws JsonSyntaxException, ClassNotFoundException {
- // Create the order
- Order order = new Order(new Customer("John", City.NEW_YORK), new BigDecimal("9.99"));
- // Create the envelope
- Gson gson = new GsonBuilder().setPrettyPrinting().create();
- Envelope<Order> envelope = new Envelope<Order>(order);
- String serialized = gson.toJson(envelope);
- System.out.println(serialized);
- // Read the envelope
- Envelope<?> receivedEnvelope = gson.fromJson(serialized, Envelope.class);
- Object result = gson.fromJson(receivedEnvelope.contents, Class.forName(receivedEnvelope.clazz));
- System.out.println("Result: " + result);
- assert result.getClass().equals(Order.class);
- }
- public static class Envelope<T> {
- public String clazz;
- public JsonElement contents;
- public Envelope (T contents) {
- this.clazz = contents.getClass().getName();
- this.contents = new Gson().toJsonTree(contents, contents.getClass());
- }
- }
- public static enum City {
- NEW_YORK("New York City", "00100"),
- SAN_FRANCISCO("San Francisco", "00200");
- public String name, zip;
- City(String name, String zip) {
- this.name = name;
- this.zip = zip;
- }
- public String toString() {
- return String.format("%s, zip code: %s", name, zip);
- }
- }
- public static class Customer {
- public Customer(String name, City city) {
- this.name = name;
- this.city = city;
- }
- String name;
- City city;
- public String toString() {
- return String.format("%s from %s", name, city);
- }
- }
- public static class Order {
- public Order(Customer customer, BigDecimal total) {
- this.customer = customer;
- this.total = total;
- id = 123456789L;
- }
- Long id;
- Customer customer;
- BigDecimal total;
- public String toString(){
- return String.format("Order by %s, total $%s", customer, total);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement