简体   繁体   中英

Gson Custom Serializer Not Called

I have a class that doesn't serialize properly with Gson (class is just name and HashMap) so I wrote a custom serializer to print the name and the key, value pair from the 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;
}

To get it to print appropriately, I've registered the custom serializer but when I go to print the class, it doesn't actually use the serializer. I can tell because I have the serializer printing "here" and it never prints.

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

Also, this is what actually prints and serializing the entire object doesn't work as I would expect nor does trying just to print the object directly.

{
  "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[]

Any help would be greatly appreciated.

Of course, I can't directly copy the code in as I've gotten rid of it and I wasn't yet to the point where I'd start versioning but essentially:

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

}

Setting i to the returned Item didn't really work and so then when I tried to serialize, the HashMap in my objects wasn't set properly as @Perception noted. I "solved" it by creating a List of strings to hold something and then added the returned Item s to the ArrayList instead of trying to assign it to the existing Item .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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