栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用GSON序列化Java对象

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用GSON序列化Java对象

为了获得所需的结果,您需要像这样编写串行器:

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}

完整的代码:

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/616788.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号