Exception in thread “main” java.lang.IllegalArgume

2019-08-13 10:11发布

问题:

I am really facing challenge in changing String object to ObjectId using BSON API. The error I am facing:

Exception in thread "main" java.lang.IllegalArgumentException: invalid ObjectId [7887978]
    at org.bson.types.ObjectId.<init>(ObjectId.java:130)
    at org.bson.types.ObjectId.<init>(ObjectId.java:124)
    at com.sample.common.Main.main(Main.java:8)

The simple code below for reference:

import org.bson.types.ObjectId;

public class Main {
    public static void main(String[] args) {
        String number = "7887978";
        ObjectId id = new ObjectId(number);
        System.out.println(id);
    }
}

How we can solve this error. Any pointers ?

Edit: Maven dependency that I used:

<dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>bson</artifactId>
            <version>2.3</version>
        </dependency>

回答1:

From the Bson API doc it is clear that ObjectId(String hexString) Constructs a new instance from a valid 24-byte hexadecimal string representation.

Point here is the string has to be a valid 24-byte hexadecimal value. The value 7887978 is invalid. You could either modify the code as below:

String id = "666f6f2d6261722d71757578";
        if (ObjectId.isValid(id)) {
            ObjectId objectId = new ObjectId(id);
            System.out.println(objectId);
        } else {
            System.out.println("Invalid id");
        }

or use the in build static API get() to create a new object id..

ObjectId objectId = ObjectId.get();

Hope it helps you!



回答2:

docs say :

IllegalArgumentException - if the string is not a valid id

so perhaps "7887978" is not a valid id



标签: java bson