Issue
Have a nice day everyone!
I'm trying to understand MongoDB in the JAVA. I'm trying to map the MongoDB Document object to my own java object.
My MongoDB Document structure:
{
"_id" : {
"$oid" : "5f2d37f1cdf2f93d01fd5f9a"
},
"Person_ID" : {
"$numberInt" : "3"
}, "Name" : "John", "Lastname" : "Doe"
}
MyClass.class model:
public class MyClass {
String oid;
int Person_ID;
int numberInt;
String Name, Lastname;
//empty constructor
public MyClass() {}
// Setters and Getters
}
Using JAVA I try:
public static void main(String[] args) {
MongoClientURI uri = new MongoClientURI(
"mongodb+srv://<username>:<password>@cluster.lt8te.mongodb.net/dbProject?
retryWrites=true&w=majority");
MongoClient client = new MongoClient(uri);
MongoDatabase db = client.getDatabase("dbProject");
MongoCollection<Document> coll = db.getCollection("myCollection");
Document doc = (Document) coll.find().first();
System.out.println(doc.toJson());
Gson gson = new Gson();
MongoObject mongoObj = gson.fromJson(doc.toJson(), MyClass.class);
}
I'm getting an error: Caused by: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 10 path $._id
I think my MyClass model not matches the Document mongoDB model. I'm not very sure where I have a mistake. Or what to edit? Thank You.
Solution
At last line you are trying to map a JSON to your MyClass java object. For that to work JSON structure has to match with your java class. Assuming the JSON result from doc.toJson()
will look like your Mongo document that you have shown, implement your class as below. The idea is your JSON documents data type should match with your class, For example Person_ID
in your JSON is an Object which has three attribute in it so in your java class there should be a variable with name Person_ID which will of a another Class type with three attribute.
public class MyClass {
ID _id;
Person Person_ID;
//empty constructor
public MyClass() {}
// Setters and Getters
}
Class ID{
public String oid;
//Getter setter
}
Class Person {
int numberInt;
String Name;
String Lastname;
//Getter setter
}
Answered By - Nawnit Sen