未调用列表的Gson自定义类型适配器

时间:2018-03-04 08:52:07

标签: java json gson

我是使用Gson的新手。我正在尝试为我的班级创建一个特定的typeadapter。这是:

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

这是我尝试序列化/反序列化资产列表的方式:

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

问题是我的重写方法没有在这段代码中调用,因此Gson将其标准序列化器用于数组。

1 个答案:

答案 0 :(得分:0)

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