MongoDB存储String[]抛出异常org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class [Ljava.lang.String;.

在存储String[] 到MongoDB的时候抛出了以下异常,最开始以为是传错了对象,后来才发现,是MongoDB的解码器不支持解析String数组导致的,必须将字符串数组转成List才可以。

org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class [Ljava.lang.String;.
    at org.bson.codecs.configuration.CodecCache.getOrThrow(CodecCache.java:46)
    at org.bson.codecs.configuration.ProvidersCodecRegistry.get(ProvidersCodecRegistry.java:63)
    at org.bson.codecs.configuration.ChildCodecRegistry.get(ChildCodecRegistry.java:51)
    at org.bson.codecs.DocumentCodec.writeValue(DocumentCodec.java:174)
    at org.bson.codecs.DocumentCodec.writeMap(DocumentCodec.java:189)
    at org.bson.codecs.DocumentCodec.writeValue(DocumentCodec.java:172)
    at org.bson.codecs.DocumentCodec.writeMap(DocumentCodec.java:189)
    at org.bson.codecs.DocumentCodec.writeValue(DocumentCodec.java:172)
    at org.bson.codecs.DocumentCodec.writeMap(DocumentCodec.java:189)
    at org.bson.codecs.DocumentCodec.encode(DocumentCodec.java:131)
    at org.bson.codecs.DocumentCodec.encode(DocumentCodec.java:45)
    at org.bson.BsonDocumentWrapper.getUnwrapped(BsonDocumentWrapper.java:189)
    at org.bson.BsonDocumentWrapper.get(BsonDocumentWrapper.java:129)
    at com.mongodb.AggregateIterableImpl.execute(AggregateIterableImpl.java:118)
    at com.mongodb.AggregateIterableImpl.forEach(AggregateIterableImpl.java:107)
    at undefined.AggregationTest.main(AggregationTest.java:27)

将字符串数组String[]转成List可以使用Arrays.asList()方法(位于java.util包下):

Arrays.asList("hello#gogogo#123".split("#"))

参考:
https://samebug.io/exceptions/2485483/org.bson.codecs.configuration.CodecConfigurationException/cant-find-a-codec-for-class-ljavalangstring?soft=false

    原文作者:柠檬信息技术有限公司
    原文地址: https://www.jianshu.com/p/104b409cb477
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞