0
Bank structure:
>db.produtos.find().pretty();
{
"_id" : ObjectId("58879057e53276e2f7bf43be"),
"descricao" : "Bisnaguinha",
"preco" : 4.8
}
{
"_id" : ObjectId("58879067e53276e2f7bf43bf"),
"descicao" : "Nutella",
"preco" : 12.4
}
DTO:
package com.simple.dto;
public class ProdutoDTO {
public Object _id;
public String descricao;
public double preco;
public Object get_id() { return _id;}
public void set_id(Object _id) { this._id = _id;}
public String getDescricao() { return descricao;}
public void setDescricao(String descricao) { this.descricao = descricao;}
public double getPreco() { return preco;}
public void setPreco(double preco) { this.preco = preco;}
}
Class that consults:
package com.simple.dao;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
public class MongoConection {
public void mongoTeste(){
MongoClient mongo = new MongoClient( "localhost" , 27017 );
MongoDatabase database = mongo.getDatabase("test");
MongoCollection produtos = database.getCollection("produtos");
FindIterable<Document> resultadoDaBusca = produtos.find();
for (Document document : resultadoDaBusca) {
System.out.println(document.toJson());
}
}
}
Log that comes out:
{ "_id" : { "$oid" : "58879057e53276e2f7bf43be" }, "descricao" : "Bisnaguinha", "preco" : 4.8 }
{ "_id" : { "$oid" : "58879067e53276e2f7bf43bf" }, "descicao" : "Nutella", "preco" : 12.4 }
You need some library to parse for you like Jackson Databind or GSON, and do for example:
ProdutoDTO produtoDto = new ObjectMapper().readValue(document.toJson(), ProdutoDTO.class);
Here are more examples... [https://www.mkyong.com/java/how-to-convert-java-object-to-json-jackson/]– Erick Maia
Thank you very much. It worked perfectly.
– Jonathan Code