我想在 GSON 中创建一个自定义序列化器,在对象中插入键/值对,而不是新对象。例如,假设:
class Car {
@Expose
String model;
@Expose
Manufacturer manufacturer;
}
class Manufacturer {
@Expose
String name;
@Expose
String from;
}
我想得到这样的 JSON:
"car":{
"model":"beatle",
"manufacturer":"volkswagen",
"country":"Germany"
}
但无论我如何编码序列化器,它都坚持在“car”内创建一个制造商对象
"manufacturer":{
"name":"volkswagen",
"country":"Germany"
}
如何解决这个问题,只获取键/值对?
PS:我无法对类进行重大更改,因为它们正在映射数据库。这只是一个模拟我的问题的例子。
最佳答案
使用自定义序列化程序应该会有所帮助。
private class ManufacturerSerializer implements JsonSerializer<Manufacturer> {
public JsonElement serialize(Manufacturer src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src.getName()); // or src.name public.
}
}
引用这个:https://sites.google.com/site/gson/gson-user-guide/#TOC-Custom-Serialization-and-Deserialization
关于java - 使用 GSON 序列化嵌入式对(键/值)而不是对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11344872/