1

我想在 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"
}

但无论我如何编写序列化程序,它都坚持在“汽车”内部创建一个制造商对象

"manufacturer":{
    "name":"volkswagen",
    "country":"Germany"
}

我该如何解决这个问题,只获取键/值对?

PS:我无法对类进行重大更改,因为它们正在映射数据库。这只是模拟我的问题的一个例子。

提前致谢。

4

3 回答 3

1

使用自定义序列化程序应该会有所帮助。

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

于 2012-07-05T13:07:16.693 回答
0

您应该为该类定义自己的序列化器和Car序列化器,这将避免以简单的方式序列化复合类,但会呈现您需要的内容。

这一点都不难,例如你会定义

class CarSerializer implements JsonSerializer<Car> {
  JsonElement serialize(Car src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject o = new JsonObject();
    o.addProperty("manufacturer", src.manufacturer.name);
    ...
  }
}

请记住,您需要按照文档中的说明注册序列化程序。

于 2012-07-05T13:07:27.863 回答
0

我无法使用 JsonSerializer 制作我想要的东西。从 2.1(TypeAdapter 类)开始,我只能使用 GSON 的新 API 使其正常工作。

public class ManufacturerSerializer extends TypeAdapter<Manufacturer> {
    @Override
    public void write(JsonWriter out, Manufacturer m) throws IOException {
        out.value(m.getName());
        out.name("country");
        out.value(m.getFrom());
    }

    /* I only need Serialization, dont use this */
    @Override
    public Manufacturer read(JsonReader in) throws IOException {
        return null;
    }
}
于 2012-07-13T18:37:36.623 回答