Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize java object with GSON

Tags:

java

json

gson

I would like to serialize this object to JSON String

public class Person {    public String id;    public String name;    public Person parent; } 

and obtain a result like this:

{id: 1, name: "Joe", parent: 2} 

I tried to use

Person p = new Person(1, "Joe", new Person(2, "Mike")); Gson gson = new GsonBuilder()             .registerTypeAdapter(Persona.class, new PersonSerializer()).create(); String str = gson.toJson(p); 

but instead of that, I got:

"1" 

PersonSerializer:

public class PersonSerializer implements JsonSerializer<Person> {     public JsonElement serialize(Person src, Type typeOfSrc, ...) {         return new JsonPrimitive(src.id);     } } 

Please any suggestion is welcome

Thanks, Mario

like image 559
Mario Avatar asked Jun 14 '12 17:06

Mario


People also ask

How do you serialize an object with Gson?

Serialization – Write JSON using Gson Serialization in the context of Gson means converting a Java object to its JSON representation. In order to do the serialization, we need to create the Gson object, which handles the conversion. Next, we need to call the function toJson() and pass the User object.

Does Gson need serializable?

NO. You don't have to make them Serializable while using Gson.

How does Gson work in Java?

Gson can work with arbitrary Java objects including objects for which you do not have the source. For this purpose, Gson provides several built in serializers and deserializers. A serializer allows to convert a Json string to corresponding Java type. A deserializers allows to convert from Java to a JSON representation.

How JSON deserialization works in Java?

Deserialization is transforming the data from a file or stream back into an object to be used in your application. This can be binary data or structured data like JSON and XML. Deserialization is the opposite of serialization, which transforms objects into byte streams or structured text.


1 Answers

In order to get the result you desire, you need to write the serializer like this:

public static class PersonSerializer implements JsonSerializer<Person> {     public JsonElement serialize(final Person person, final Type type, final JsonSerializationContext context) {         JsonObject result = new JsonObject();         result.add("id", new JsonPrimitive(person.getId()));         result.add("name", new JsonPrimitive(person.getName()));         Person parent = person.getParent();         if (parent != null) {             result.add("parent", new JsonPrimitive(parent.getId()));         }         return result;     } } 

The result for

    Person p = new Person(1, "Joe", new Person(2, "Mike"));     com.google.gson.Gson gson = new GsonBuilder().registerTypeAdapter(Person.class, new PersonSerializer())             .create();     System.out.println(gson.toJson(p)); 

will be

{"id":1,"name":"Joe","parent":2} 

Complete code:

import java.lang.reflect.Type;  import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer;  public class GsonSimpleTest {      public static class Person {         public int id;         public String name;         public Person parent;          public Person(final int id, final String name) {             super();             this.id = id;             this.name = name;         }          public Person(final int id, final String name, final Person parent) {             super();             this.id = id;             this.name = name;             this.parent = parent;         }          public int getId() {             return id;         }          public void setId(final int id) {             this.id = id;         }          public String getName() {             return name;         }          public void setName(final String name) {             this.name = name;         }          public Person getParent() {             return parent;         }          public void setParent(final Person parent) {             this.parent = parent;         }      }      public static class PersonSerializer implements JsonSerializer<Person> {         public JsonElement serialize(final Person person, final Type type, final JsonSerializationContext context) {             JsonObject result = new JsonObject();             result.add("id", new JsonPrimitive(person.getId()));             result.add("name", new JsonPrimitive(person.getName()));             Person parent = person.getParent();             if (parent != null) {                 result.add("parent", new JsonPrimitive(parent.getId()));             }             return result;         }     }      public static void main(final String[] args) {         Person p = new Person(1, "Joe", new Person(2, "Mike"));         com.google.gson.Gson gson = new GsonBuilder().registerTypeAdapter(Person.class, new PersonSerializer())                 .create();         System.out.println(gson.toJson(p));     }  } 
like image 165
Francisco Spaeth Avatar answered Oct 11 '22 14:10

Francisco Spaeth