Reputation: 359
I am quite new to MongoDb. i use a find and get the result in JSON format.
{"Name": "Harshil", "Age":20}
so what i need is parse this in java and get values in the variables.
String name should contain Harshil
int age should contain 20
is there a way to store these details in JAVA object?
Upvotes: 0
Views: 28485
Reputation: 61
Try Using this function to convert JSON returned by mongodb to your custom java object list.
MongoClient mongodb = new MongoClient("localhost", 27017);
DB db = mongodb.getDB("customData-database");
DBCursor customDataCollection = db.getCollection("customDataList").find();
List<CustomJavaObject> myCustomDataList = null; // this list will hold your custom data
JSON json = new JSON();
ObjectMapper objectMapper = new ObjectMapper();
try {
//this is where deserialiazation(conversion) takes place
myCustomDataList = objectMapper.readValue(json.serialize(customDataCollection),
new TypeReference<List<Restaurant>>() {
});
} catch (IOException e) {
e.printStackTrace();
}
CustomJavaObject:
public class CustomJavaObject{
//your json fields go here
String field1, field2;
int num;
ArrayList<String> attributes;
//....write relevantgetter and setter methods
}
sample json:
{
"field1": "Hsr Layout",
"field2": "www.google.com",
"num": 20,
"attributes": [
"Benagaluru",
"Residential"
]
},
{
"field1": "BTM Layout",
"field2": "www.youtube.com",
"num": 10,
"attributes": [
"Bangalore",
"Industrial"
]
}
Upvotes: 0
Reputation: 21
As we don't want to use the deprecated methods so, you can use the following code to do so:
MongoClient mongo = new MongoClient( "localhost" , 27017 );
MongoDatabase database = mongo.getDatabase("your_db_name");
MongoCollection<Document> collection = database.getCollection("your_collection_name");
FindIterable<Document> iterDoc = collection.find();
MongoCursor<Document> dbc = iterDoc.iterator();
while(dbc.hasNext()){
try {
JsonParser jsonParser = new JsonFactory().createParser(dbc.next().toJson());
ObjectMapper mapper = new ObjectMapper();
Person person = mapper.readValue(jsonParser, Person.class);
String name = person.get("Name");
String age = person.get("Age");
} catch (Exception e){
e.printStackTrace();
}
JsonFactory, JsonParser,etc. are being used from Jackson to de-serialize the Document to the related Entity object.
Upvotes: 1
Reputation: 654
Since the original answer was posted the DBObject
and corresponding method client.getDB
have been deprecated. For anyone who may be looking for a solution since the new update I have done my best to translate.
MongoClient client = new MongoClient("localhost",27017); //Location by Default
MongoDatabase database = client.getDatabase("YOUR_DATABASE_NAME");
MongoCollection<Document> collection = database.getCollection("YOUR_COLLECTION_NAME");
Once connected to the document there are numerous familiar methods of getting data as a Java Object. Assuming you plan to have multiple documents that contain a persons name
and their age
I suggest collecting all the documents (which you can visualize as rows containing a name and age) in an ArrayList then you can simply pick through the documents in the ArrayList
to convert them to java objects as so:
List<Document> documents = (List<Document>) collection.find().into(new ArrayList<Document>());
for (Document document : documents) {
Document person = documents.get(document);
String name = person.get("Name");
String age = person.get("Age");
}
Honestly the for
loop is not a pretty way of doing it but I wanted to help the community struggling with deprecation.
Upvotes: 0
Reputation: 669
I would prefer using the new Mongodb Java API. It's very clean and clear.
public MyEntity findMyEntityById(long entityId) {
List<Bson> queryFilters = new ArrayList<>();
queryFilters.add(Filters.eq("_id", entityId));
Bson searchFilter = Filters.and(queryFilters);
List<Bson> returnFilters = new ArrayList<>();
returnFilters.add(Filters.eq("name", 1));
Bson returnFilter = Filters.and(returnFilters);
Document doc = getMongoCollection().find(searchFilter).projection(returnFilter).first();
JsonParser jsonParser = new JsonFactory().createParser(doc.toJson());
ObjectMapper mapper = new ObjectMapper();
MyEntity myEntity = mapper.readValue(jsonParser, MyEntity.class);
return myEntity;
}
Details at http://ashutosh-srivastav-mongodb.blogspot.in/2017/09/mongodb-fetch-operation-using-java-api.html
Upvotes: 0
Reputation: 44881
There are many ways and tools, one of which is gson
class Person {
private String name;
private int age;
public Person() {
// no-args constructor
}
}
Gson gson = new Gson();
Person person = gson.fromJson(json, Person.class);
And I'd feel lax if I didn't add this link too.
Upvotes: 3
Reputation: 2438
Here is how to connect to the your MongoDB:
MongoClient client = new MongoClient("localhost",27017); //with default server and port adress
DB db = client.getDB( "your_db_name" );
DBCollection collection = db.getCollection("Your_Collection_Name");
After the connecting you can pull your data from the server.Below, i assume that your document has Name and Age field :
DBObject dbo = collection.findOne();
String name = dbo.get("Name");
int age = dbo.get("Age");
Upvotes: 6
Reputation: 8281
You can just do it with the Java driver :
DBObject dbo = ...
String s = dbo.getString("Name")
int i = dbo.getInt("Age")
Using another framework on top of the Java driver should be considered I you have multiple objects to manage.
Upvotes: 1
Reputation: 16526
Have you considere Morphia?
@Entity
class Person{
@Property("Name") Date name;
@Property("Age") Date age;
}
Upvotes: 0
Reputation: 2579
Take a look at GSON library. It converts JSON to Java objects and vice-versa.
Upvotes: 4