mongodb中记录的数据为
{
"_id" : ObjectId("5d3e6a82c7cf3e3a50fa635b"),
"uid" : NumberInt(1),
"name" : "张三",
"createTime" : NumberLong(1564371586096),
"_class" : "cn.wangjie.mongodb.model.UserModel"
}
使用MongoTemplate查询数据
Document document = new Document();
document.put("uid",1);
FindIterable<Document> findIterable =mongoTemplate.getCollection("user").find(document);
document = findIterable.first();
UserModel model = null;
if (iterator.hasNext()){
String json = iterator.next().toJson();
System.out.println(json);
model = (BaseUserPopupInfoModel)JSON.parseObject(json,type.classType);
}
使用fastjson反序列化失败,打印出的输json数据为
{
"_id": {
"$oid": "5d3e6a82c7cf3e3a50fa635b"
},
"uid": 1,
"name": "张三",
"createTime": {
"$numberLong": "1564371586096"
},
"_class": "cn.wangjie.mongodb.model.UserModel"
}
报错为
可以看到createTime字段对应的并不是时间戳,而是一个类。此时需要自定义反序列化工具提取数据。
由于使用的是fastjson的反序列化所以需要自定义fastjson的反序列化器。
import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import com.youxiake.utils.StringUtil;
import java.lang.reflect.Type;
public class MongoLongConverter implements ObjectDeserializer {
@Override
public Long deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
String longStr = parser.parseObject().getString("$numberLong");
if (StringUtil.isNotEmptyOrNull(longStr)){
return Long.parseLong(longStr);
}
return 0L;
}
@Override
public int getFastMatchToken() {
return 0;
}
}
在需要使用的字段上指明使用该反序列化器即可
/**
* 创建时间
*/
@JSONField(deserializeUsing =MongoLongConverter.class )
private Long createTime;
后来打断点执行发现得到的document结构其实是正常的,只是在toJson的时候才被加上了类型说明$numberLong
toJson()方法使用了mongo自己的一系列转化器
其实MongoTemplate提供了将document转换为目标类型的方法,代码为:
Document document = new Document();
document.put("uid",1);
FindIterable<Document> findIterable =mongoTemplate.getCollection("user").find(document);
document = findIterable.first();
UserModel model = mongoTemplate.getConverter().read(UserModel.class,document);
System.out.println(model);
```java