我正在从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字符串存储在其中。 (例如"5526888bd3d56a86cea8ea12"

Gson可以自动为我做吗?

谢谢

最佳答案

您可以注册一个自定义适配器,以告诉解析器您只想获取括号和字符串值中的引号之间的值(请注意,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}

10-07 17:31