我想将这个对象序列化为JSON字符串

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

并得到如下结果:

{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);
    }
}

欢迎提出任何建议

Thanks, Mario

推荐答案

为了获得您想要的结果,您需要像这样编写序列化程序:

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;
    }
}

结果是

    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));

{"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));
    }

}

Json相关问答推荐

基于两个条件替换扁平化的SON中的值

Jolt需要将缺少的值设置为空并保持相同的位置

将数组中的值作为键连接到另一个数组中的值(Jolt)

PowerShell脚本未按预期生成预期的JSON输出

通过在织女星简化图上裁剪来显示文本

将部分数据字节解组到自定义 struct 中

将 REST API - json 输出转换为表 Power BI

go 语言中的 JSON 到 XML

如何强制仅有一个元素的数组在JSON中生成方括号

匹配来自不同数组的值

为什么根据其他工具,来自 aws rds 的 JSON 在 Docker 中格式错误运行?

JOLT 转换 - 删除 JSON 数组中的空 node

如何在生产环境中更改 Flutter 应用程序中的数据模型?

如何使用 gson 调用默认反序列化

解析包含换行符的 JSON

在 Apache Spark 中读取多行 JSON

反序列化大型 json 对象的 JsonMaxLength 异常

了解 JSON Schema 草稿版本 4 中的additionalProperties关键字

使用 Codable 序列化为 JSON 时的 Swift 字符串转义

带有 Jackson 的不可变 Lombok 注释类