使用Google Gson映射Mongo id字段

时间:2015-04-09 14:32:27

标签: java gson

我正在阅读MongoDB中包含其唯一标识符的文档:

{
    "_id" : ObjectId("5526888bd3d56a86cea8ea12"),
    "name" : "user1"
}

我想用java类映射它

public class Mapper {
    Object _id;
    String name;
}

由于我的fromJson执行:

Mapper m = gson.fromJson(string, Mapper.class);

... _id字段中存储的值为{$oid=5526888bd3d56a86cea8ea12}。我想将id String存储在其中。 (例如"5526888bd3d56a86cea8ea12"

Gson可以自动为我做吗?

由于

1 个答案:

答案 0 :(得分:2)

您可以注册一个自定义适配器,告诉解析器您只想获取字符串值中括号和引号之间的值(请注意,id现在是Mapper类中的String)。可以更改正则表达式以匹配生成的ID要求。

class MapperAdapter implements JsonDeserializer<Mapper> {

    private static final Pattern p = Pattern.compile("\\(\"([a-zA-Z\\d]+)\"\\)");

    @Override
    public Mapper deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        JsonObject jObj = json.getAsJsonObject();
        String id = jObj.get("_id").getAsString();
        String name = jObj.get("name").getAsString();

        Matcher m = p.matcher(id);
        if(!m.find()) {
            throw new IllegalArgumentException("The id should be within parenthesis and quotes.");
        }
        return new Mapper(m.group(1), name);
    }
}

并在解析器中注册:

Gson gson = new GsonBuilder().registerTypeAdapter(Mapper.class, new MapperAdapter()).create();
Mapper m = gson.fromJson(jsonString, Mapper.class);

这产生了输出:

Mapper{id=5526888bd3d56a86cea8ea12, name=user1}