将BSON MongoDB文档映射到MyClass.class对象?

huangapple go评论79阅读模式
英文:

Mapping a BSON MongoDB document to a MyClass.class object?

问题

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 does not match the Document MongoDB model. I'm not very sure where I have a mistake. Or what to edit? Thank You.

英文:

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:

{
    &quot;_id&quot; : {
	    &quot;$oid&quot; : &quot;5f2d37f1cdf2f93d01fd5f9a&quot;
    },
    &quot;Person_ID&quot; : {
	    &quot;$numberInt&quot; : &quot;3&quot;
    }, &quot;Name&quot; : &quot;John&quot;, &quot;Lastname&quot; : &quot;Doe&quot;
}

>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(
        &quot;mongodb+srv://&lt;username&gt;:&lt;password&gt;@cluster.lt8te.mongodb.net/dbProject? 
          retryWrites=true&amp;w=majority&quot;); 
   
    MongoClient client = new MongoClient(uri);            
    MongoDatabase db = client.getDatabase(&quot;dbProject&quot;);
    MongoCollection&lt;Document&gt; coll = db.getCollection(&quot;myCollection&quot;);
    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.

答案1

得分: 3

以下是翻译好的内容:

所以在几个小时的学习后,并在StackOverFlow的帮助下,我可以在这里提供一个可以帮助他人的解决方案。让我们掌握BSON文档的结构,我在这里提供了一个示例。

这里:

{
   "_id" : {
       "$oid" : "5f2d37f1cdf2f93d01fd5f9a"
   },
   "Person_ID" : {
       "$numberInt" : "3"
   }, "Name" : "John", "Lastname" : "Doe"
}

MongoDB要求对所有文档都有一个'_id'字段。如果您没有提供一个,驱动程序将分配一个具有生成值的ObjectId。

现在您需要创建这个JSON的对象模型。
像这样:(保持字段的顺序很重要。)

import org.bson.types.ObjectId;

public class ModelMongo 
{
    ObjectId _id;
    int Person_ID;
    String Name;
    String Lastname;

    public ModelMongo(ObjectId id, int Person_ID, String Name, String Lastname) 
    {
        this._id = id;
        this.Person_ID = Person_ID;
        this.Name = Name;
        this.Lastname = Lastname;
    }

    // Setter and Getter ...      
}

假设您的文档结构与上面的示例相同,并且您想将Mongo域文档映射到自己的Java类:

public static void main(String[] args)
{
    MongoClient client = new MongoClient(uri);            
    MongoDatabase db = client.getDatabase("dbProject");
    MongoCollection<org.bson.Document> coll = db.getCollection("myCollection");
    Document doc = (Document) coll.find().first();

    Gson gson = new Gson();
    ModelMongo model = gson.fromJson(doc.toJson(), ModelMongo.class);  

    /**
    * 现在在变量model中有来自MongoDB的文档 *
    * 通过其Getter方法访问该对象的变量。 *
    */
}

依赖:

<!-- https://mvnrepository.com/artifact/org.mongodb/bson -->
<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>bson</artifactId>
    <version>4.0.4</version>
</dependency>

请注意,代码部分未翻译,仅提供了翻译好的文本。

英文:

So after a few hours of studying. And with the help of StackOverFlow, I can present a solution here that can help others. Let's grasp the structure of the BSON Document, which I gave here as an example.
>Here:

{
   &quot;_id&quot; : {
       &quot;$oid&quot; : &quot;5f2d37f1cdf2f93d01fd5f9a&quot;
   },
   &quot;Person_ID&quot; : {
       &quot;$numberInt&quot; : &quot;3&quot;
   }, &quot;Name&quot; : &quot;John&quot;, &quot;Lastname&quot; : &quot;Doe&quot;

}

> MongoDB requires that you have an '_id' field for all documents. If you don't provide one the driver will assign a ObjectId with a generated value.

Now you need to create an object model of this JSON.
Like this: (It is important to maintain the order of the fields.)

import org.bson.types.ObjectId;

public class ModelMongo 
{
    ObjectId _id;
    int Person_ID;
    String Name;
    String Lastname;

    public ModelMongo(ObjectId id, int Person_ID, String Name, String Lastname) 
    }
        this._id = id;
        this.Person_ID = Person_ID;
        this.Name = Name;
        this.Lastname = Lastname;
    {

      // Setter and Getter ...      
}

Assuming you have the same document structure as in the example above and you want to map a domain mongo document to your own java class:

public static void main(String[] args)
}
    MongoClient client = new MongoClient(uri);            
    MongoDatabase db = client.getDatabase(&quot;dbProject&quot;);
    MongoCollection&lt;org.bson.Document&gt; coll = db.getCollection(&quot;myCollection&quot;);
    Document doc = (Document) coll.find().first();

    Gson gson = new Gson();
    ModelMongo model = gson.fromJson(doc.toJson(), ModelMongo.class);  

    /***                                                ****
    * Now in the variable model is a Document from MongoDB *
    * Access to variables of that Object possible through  *
    * its Getter methods.                              ****/
{

> Dependency:

&lt;!-- https://mvnrepository.com/artifact/org.mongodb/bson --&gt;
&lt;dependency&gt;
    &lt;groupId&gt;org.mongodb&lt;/groupId&gt;
    &lt;artifactId&gt;bson&lt;/artifactId&gt;
    &lt;version&gt;4.0.4&lt;/version&gt;
&lt;/dependency&gt;

答案2

得分: 1

在最后一行,您正在尝试将JSON映射到您的MyClass Java对象。为了使此操作生效,JSON结构必须与您的Java类匹配。假设从doc.toJson()返回的JSON结果将与您所示的Mongo文档相似,那么可以按照以下方式实现您的类。关键点是,您的JSON文档数据类型应与您的类匹配,例如,您的JSON中的Person_ID是一个对象,其中包含三个属性,因此在您的Java类中应该有一个名为Person_ID的变量,它将是另一个具有三个属性的类的类型。

public class MyClass {
    ID _id;
    Person Person_ID;

    // 空构造函数
    public MyClass() {}

    // 设置器和获取器
}

class ID {
    public String oid;

    // 获取器和设置器
}

class Person {
    int numberInt;
    String Name;
    String Lastname;

    // 获取器和设置器
}
英文:

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
}

huangapple
  • 本文由 发表于 2020年8月8日 02:41:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/63307545.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定