繁体   English   中英

未调用Gson自定义序列化程序

[英]Gson Custom Serializer Not Called

我有一个无法使用Gson正确序列化的类(该类只是名称和HashMap),所以我编写了一个自定义序列化程序以从HashMap打印名称和键值对。

public JsonElement serialize(SpecificationGroupList sgl, Type typeofT,
    JsonSerializationContext context) {
System.out.println("here");
JsonObject ret = new JsonObject();
ret.addProperty("GroupName", sgl.getGroupName());

JsonArray jsonArray = new JsonArray();
ret.add("SpecificationPartList", jsonArray);
for (Entry<String, String> entry : sgl.getSpecificationPairList().entrySet()) {
    JsonObject temp = new JsonObject();
    temp.addProperty(entry.getKey(), entry.getValue());
    jsonArray.add(temp);
}

return ret;
}

为了使其能够正确打印,我已经注册了自定义序列化程序,但是当我打印该类时,它实际上并没有使用序列化程序。 我可以告诉您,因为我让序列化程序在“此处”打印,并且从不打印。

private void printProducts() {
Gson gson = new GsonBuilder().setPrettyPrinting()
    .registerTypeAdapter(SpecificationGroupList.class, new SpecGroupListSerializer())
    .create();
System.out.println(gson.getAdapter(SpecificationGroupList.class).toString());
for (Item i : items) {
    System.out.println(gson.toJson(i));
    System.out.println("sgl" + gson.toJson(i.getSpecificationGroupList()));
}
}

此外,这实际上是打印的内容,并且序列化整个对象不起作用,正如我期望的那样,也不尝试直接打印对象。

{
  "ItemNumber": "22-148-842",
  "NeweggItemNumber": "N82E16822148842",
  "Title": "Seagate Savvio 15K.3 ST9300653SS 300GB 15000 RPM 2.5\" SAS 6Gb/s Internal Enterprise Hard Drive -Bare Drive",
  "specificationGroupList": []
}
sgl[]

任何帮助将不胜感激。

当然,我已经摆脱了代码,所以不能直接复制代码,虽然还没有达到开始版本控制的地步,但实际上是:

ArrayList<Item> items = new ArrayList<Item>();
Gson gson = new Gson

for (Item i : items){
    i.setId(something);
}

for (Item i : items){
    //...
    //send query and get response here
    //...

    i = gson.fromJson(in, Item.class);

}

i设置为返回的Item并没有真正起作用,因此,当我尝试序列化时,对象中的HashMap没有如@Perception所指出的那样正确设置。 我通过创建一个字符串列表来容纳something来“解决”它,然后将返回的Item添加到ArrayList中,而不是尝试将其分配给现有Item

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM