解决MongoDB读数据报异常readEndDocument can only be called when State is END_OF_DOCUMENT

本文探讨了在使用MongoDB时遇到的org.bson.BsonInvalidOperationException异常,详细分析了错误发生的原因及可能的解决策略。通过一个具体的SmsContentEntity解码示例,展示了如何正确处理文档读取过程中的状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

org.bson.BsonInvalidOperationException: readEndDocument can only be called when State is END_OF_DOCUMENT, not when State is NAME.
    at org.bson.AbstractBsonReader.throwInvalidState(AbstractBsonReader.java:671)
    at org.bson.AbstractBsonReader.readEndDocument(AbstractBsonReader.java:357)
    at com.jianmi.cloud.mongo.content.SmsContentCodec.decode(SmsContentCodec.java:42)
    at com.jianmi.cloud.mongo.content.SmsContentCodec.decode(SmsContentCodec.java:16)
    at com.mongodb.operation.CommandResultArrayCodec.decode(CommandResultArrayCodec.java:52)
    at com.mongodb.operation.CommandResultDocumentCodec.readValue(CommandResultDocumentCodec.java:53)
    at org.bson.codecs.BsonDocumentCodec.decode(BsonDocumentCodec.java:84)
    at org.bson.codecs.BsonDocumentCodec.decode(BsonDocumentCodec.java:41)
    public SmsContentEntity decode(BsonReader reader, DecoderContext decoderContext) {
        SmsContentEntity user = new SmsContentEntity();
        reader.readStartDocument();
        user.setId(reader.readObjectId("_id").toString());
        user.setAccount(reader.readString("account"));    //用户名 
        user.setContent(reader.readString("content"));    //内容 


        //因为多了一些字段不读取,这里都跳过一下
        while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) {
            System.out.println("reader.readName:"+reader.readName());
            reader.skipValue();
        }

        reader.readEndDocument();
        return user;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值