用Google Gson映射Mongo id字段 [英] Mapping Mongo id field with Google Gson
问题描述
我从MongoDB读取一个包含其唯一标识符的文档:
{
_id: ObjectId(5526888bd3d56a86cea8ea12),
name:user1
}
我想用java类映射它
$ b $ pre $ public class Mapper {
Object _id;
字符串名称;
}
由于执行fromJson的结果:
Mapper m = gson.fromJson(string,Mapper.class);
...存储在_id字段中的值是 {$ oid = 5526888bd3d56a86cea8ea12}
。我想将ID字符串存储在其中。 (例如5526888bd3d56a86cea8ea12
)
Gson可以自动为我做吗?
感谢您可以注册一个自定义适配器来告诉您解析器,您只需要在字符串值中的括号和引号之间获取值(请注意,id现在是 Mapper
类中的字符串)。
class MapperAdapter实现了JsonDeserializer< Mapper> {
private static final Pattern p = Pattern.compile(\\(\([a-zA-Z\\d] +)\\\ ));
$ b $ @Override
public Mapper反序列化(JsonElement json,类型typeOfT,JsonDeserializationContext上下文)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(id应该在括号和引号内。);
}
返回新的映射器(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}
I'm reading a Document from MongoDB which contains its unique identifier:
{
"_id" : ObjectId("5526888bd3d56a86cea8ea12"),
"name" : "user1"
}
I'd like to map that with a java class
public class Mapper {
Object _id;
String name;
}
As a result of my fromJson execution:
Mapper m = gson.fromJson(string, Mapper.class);
...the value stored in the _id field is {$oid=5526888bd3d56a86cea8ea12}
. I'd like to store the id String in it. (e.g. "5526888bd3d56a86cea8ea12"
)
Can Gson do it for me automatically ?
Thanks
You can register a custom adapter to tell the parser that you only want to grab the value between parenthesis and quotes in the string value (note that id is now a String in your Mapper
class). The regex can be changed to match the ids requirements that are generated.
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);
}
}
and you register it in your parser:
Gson gson = new GsonBuilder().registerTypeAdapter(Mapper.class, new MapperAdapter()).create();
Mapper m = gson.fromJson(jsonString, Mapper.class);
This yield the output:
Mapper{id=5526888bd3d56a86cea8ea12, name=user1}
这篇关于用Google Gson映射Mongo id字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!