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

Java 未调用Gson自定义序列化程序,java,json,serialization,gson,Java,Json,Serialization,Gson,我有一个类不能用Gson正确序列化(类只是名称和HashMap),所以我编写了一个自定义序列化程序来打印HashMap中的名称和键、值对 public JsonElement serialize(SpecificationGroupList sgl, Type typeofT, JsonSerializationContext context) { System.out.println("here"); JsonObject ret = new JsonObject(); ret.add

我有一个类不能用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;
}
另外,这就是实际打印和序列化整个对象的原因,这与我预期的效果不符,也不可能直接打印对象

{
  "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);

}
ArrayList items=new ArrayList();
Gson Gson=新Gson
用于(项目i:项目){
i、 setId(某物);
}
用于(项目i:项目){
//...
//在此处发送查询并获取响应
//...
i=gson.fromJson(in,Item.class);
}

i
设置为返回的
实际上不起作用,因此当我尝试序列化时,我的对象中的
HashMap
没有按照@Perception所述正确设置。我通过创建一个字符串列表来保存
某物
,然后将返回的
添加到ArrayList中,而不是试图将其分配给现有的
,从而“解决”了这个问题

当然,我不能直接复制代码,因为我已经摆脱了它,我还没有开始版本控制,但本质上:

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

}
ArrayList items=new ArrayList();
Gson Gson=新Gson
用于(项目i:项目){
i、 setId(某物);
}
用于(项目i:项目){
//...
//在此处发送查询并获取响应
//...
i=gson.fromJson(in,Item.class);
}

i
设置为返回的
实际上不起作用,因此当我尝试序列化时,我的对象中的
HashMap
没有按照@Perception所述正确设置。我通过创建一个字符串列表来保存
某物
,然后将返回的
添加到ArrayList中,而不是试图将其分配给现有的
,从而“解决”了这个问题

您可能需要验证您的规范数组在您正在打印的每个项目中是否为空。您可能需要验证您的规范数组在您正在打印的每个项目中是否为空。