java - gson 自定义特定的序列化的方式
本文介绍了java - gson 自定义特定的序列化的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
有一个 Student
类,包含了 id 和 name 两个属性,使用 SpringMVC 和 gson 整合,默认 gson 将该实体会序列化为:
{
"id" : 1,
"name" : "StuName"
}
目前希望将 Student
序列化为:
{
"Type" : "Student",
"Property": {
"id" : 1,
"name" : "StuName"
}
}
请问大家该如何做呢?(gson 版本为 2.8.0,使用 TypeAdapter
我一直得不到想要的效果。使用 Jackson 的时候,可以直接定义一个 JsonSerializer
并将其使用 @JsonSerialize(using = xxx.class)
注解来自定义序列化的格式,不知道在 gson 中有没有提供的方式)
解决方案
用:JsonSerializer/JsonDeserializer
public static class StudentJsonSerializer implements JsonSerializer<Student> {
@Override
public JsonElement serialize(Student src, Type typeOfSrc, JsonSerializationContext context) {
final JsonObject propEle = new JsonObject();
propEle.addProperty("id", src.getId());
propEle.addProperty("name", src.getName());
final JsonObject root = new JsonObject();
root.addProperty("Type", "Student");
root.add("Property", propEle);
return root;
}
}
public static class StudentJsonDeserializer implements JsonDeserializer<Student> {
public Student deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
final JsonObject root = json.getAsJsonObject();
JsonObject propEle = root.getAsJsonObject("Property");
Student student = new Student();
student.setId(propEle.get("id").getAsInt());
student.setName(propEle.get("name").getAsString());
return student;
}
}
@Test
public void test_1010000010436869() {
Gson gson = new GsonBuilder().registerTypeAdapter(Student.class, new StudentJsonSerializer())
.registerTypeAdapter(Student.class, new StudentJsonDeserializer()).create();
Student student = new Student();
student.setId(1);
student.setName("StuName");
String json = gson.toJson(student);
System.out.println(json);
Student student2 = gson.fromJson(json, Student.class);
System.out.println(student2);
}
这篇关于java - gson 自定义特定的序列化的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文