Serialize java object with GSON

前端 未结 2 1057
陌清茗
陌清茗 2020-12-04 19:45

I would like to serialize this object to JSON String

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


        
相关标签:
2条回答
  • 2020-12-04 20:04

    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));
        }
    
    }
    
    0 讨论(0)
  • 2020-12-04 20:14

    You just got the answer. However, I want to share you another way by using @JsonAdapter annotation.

    Annotated the Person bean like this

    @JsonAdapter(PersonAdatper.class)
    public class Person {
        public int id;
        public String name;
        public Person parent;
    }
    

    Create custom Adapter

    public  class PersonAdatper extends TypeAdapter<Person> {
    
        @Override
        public void write(JsonWriter writer, Person value) throws IOException {
            writer.beginObject();
    
            writer.name("id").value(value.getId());
            writer.name("name").value(value.getName());
            Person parent = value.getParent();
            if (parent != null) {
                writer.name("parent").value(parent.getId());
            }       
            writer.endObject();
        }
    
        @Override
        public Person read(JsonReader in) throws IOException {
            // do something you need
            return null;
        }
    
    }
    

    Serialize object to json string

    Person p = new Person(1, "Joe", new Person(2, "Mike"));
    Gson gson = new Gson();    
    String result = gson.toJson(p);
    

    It produces the output like below:

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

    I found this way from the tutorial GSON Annotations Example using JsonAdapter

    0 讨论(0)
提交回复
热议问题