Mongo插入Json数据报错:Can't find a codec for class java.math.BigDecimal.

首先吐槽一下百度啊,百度了好久,还是找不到问题所在。幸好公司有外网,我抱着尝试的态度谷歌了一下,看了老外的博客才解决了这个问题。

需求:我希望将Json插入到MongDB。

1.方法一:我选择FastJson得到json数据,使用Document类包装,插入到mongdb中。

        //将数据转换为json类
        JSONObject jsonObject = JSONObject.parseObject(filter(json);
        //Mongo 上下文配置,我自己写的工具类,自行百度
        MongoTest mongodb = new MongoTest("mycol");
        MongoCollection<Document> collection =mongodb.getCollection("myjson");
        //包装json类
        Document document=new Document(jsonObject);
        //插入json
       insertMany(getListDocument(document), collection);

此方法会报错如下

Exception in thread "main" org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class java.math.BigDecimal.
    at org.bson.codecs.configuration.CodecCache.getOrThrow(CodecCache.java:46)

2.问题解析

查阅资料显示,我的mongodb-driver的版本为3.4.2,并不支持再BigDecimal了,最终我的解决方案为不使用Document插入数据,而是使用DBObject插入Mongo中。

3.解决方法代码

//工具类
public MongoCollection<DBObject> getDBCollection(String collectionName) throws IOException{
        return mongoDatabase.getCollection(collectionName,DBObject.class);
}
 private static void insertMongo(MongoCollection<DBObject> collection,DBObject object)
    {
        List <DBObject> list=new ArrayList<>();
        list.add(object);
        collection.insertMany(list);
    }
        //获取DBObject
        DBObject jsOB=(DBObject)com.mongodb.util.JSON.parse(filter(json));
        //Mongo 上下文配置,我自己写的工具类,自行百度
        MongoTest mongodb = new MongoTest("mycol");
        MongoCollection<Document> collection =mongodb.getDBCollection("myjson");
        //插入数据
        insertMongo(collection,dbObject);

3.总结:通过更改Document插入数据更改为DBObject插入数据,这样就可以解决问题了。大家加油!!

猜你喜欢

转载自blog.csdn.net/weixin_39216383/article/details/81003296
今日推荐