简体   繁体   中英

Gson Custom TypeAdapter for List Not Called

I am new to using Gson. I am trying to create a specific typeadapter for my class. Here it is:

public class AssetSerializer extends TypeAdapter<List<Asset>> {

@Override
public void write(JsonWriter out, List<Asset> value) throws IOException {
    out.beginArray();
    for (Asset asset : value) {
        out.beginObject();
        out.name("name").value(asset.getName());
        out.name("code").value(asset.getCode());
        out.endObject();
    }
    out.endArray();
}

@Override
public List<Asset> read(JsonReader in) throws IOException {

    String temp_name = "";
    String temp_code = "";
    List<Asset> list = new LinkedList<>();
    in.beginArray();
    while (in.hasNext()) {
        switch (in.peek()) {
            case BEGIN_OBJECT:
                in.beginObject();
                while (in.hasNext()) {
                    switch (in.nextName()) {
                        case "name":
                            temp_name = in.nextString();
                            continue;
                        case "code":
                            temp_code = in.nextString();
                            continue;
                    }
                }
                in.endObject();
                Asset temp_asset = new Asset(temp_name, temp_code);
                list.add(temp_asset);
                continue;
        }
    }
    in.endArray();
    return list;
}

This is the way I am trying to serialize/deserialize a list of Assets:

    Asset asset1 = new Asset("Asset1", "code_1");
    Asset asset2 = new Asset("Asset2", "code_2");
    LinkedList<Asset> temp_list = new LinkedList<Asset>();
    temp_list.add(asset1);
    temp_list.add(asset2);
    Type assetsType = new TypeToken<List<Asset>>(){}.getType();

    Gson gson = new GsonBuilder()
            .setPrettyPrinting()
            .registerTypeAdapter(assetsType, new AssetSerializer())
            .create();
    String json = gson.toJson(temp_list);

The problem is that my overridden methods are not called in this code, so Gson uses its standard serializer for arrays.

您需要向GsonBuilder注册您的自定义适配器才能解决该问题。

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