Converting JSON to entities and storing in mongoDB using morphia - java

I have a JSON string being sent from a client (browser ).I want to save it to my mongoDB database which already has some collections defined by the user.I was able to successfully save objects using Morphia.But How can I do the same if I already have the JSON string being returned from client I want to put in the "bands" collection.
Mongo mongo = new Mongo("localhost");
Datastore datastore = new Morphia().createDatastore(mongo,
"bandmanager");
Band band = new Band();
band.setName("Punjabi band");
band.getMembers().add("Lucky1");
band.getMembers().add("Lucky2");
band.getMembers().add("Lucky3");
band.getMembers().add("Lucky4");
band.getMembers().add("Lucky5");
band.getMembers().add("Lucky6");
band.setGenre("Punjabi");
datastore.save(band);

Did you annotate Band with #Entity("bands")? I'm not sure what you're asking... Are you asking how to convert that json string in to a Band object? If so, look in to jackson

If you already have a JSON object, you don't really need Morphia. You can simply do the following with the Java driver:
DBObject dbObject = (DBObject) JSON.parse(yourJsonString);
For a full blog post on this see http://www.mkyong.com/mongodb/java-mongodb-convert-json-data-to-dbobject/
PS: Do not forget to sanitize the JSON you get from the client!

Related

Mongodb java driver get result as string not bson object

Is there a way to do a query where only the string is returned and not converted to bson object?
I want to use jsoniter to do the deserialization, but don't know if this can be done using java driver.
You can take the bson object and call toJson() on it to get a String that contains the query result in json format. That should allow you to use Jsoniter or Gson to deserialize your query's result.
Example:
Document result = collection.find(eq("birthYear", 1990)).first(); // Made up query
String resultJsonString = result.toJson();
You can read more about the toJson() method in the MongoDB documentation for the Java DB Driver.

Get the object id after inserting the mongodb document in java

I am using mongodb 3.4 and I want to get the last inserted document id. I have searched all and I found out below code can be used if I used a BasicDBObject.
BasicDBObject docs = new BasicDBObject(doc);
collection.insertOne(docs);
ID = (ObjectId)doc.get( "_id" );
But the problem is am using Document type not BasicDBObject so I tried to get it as like this, doc.getObjectId();. But it asks a parameter which I actually I want, So does anyone know how to get it?
EDIT
This is the I am inserting it to mongo db.
Document doc = new Document("jarFileName", jarDataObj.getJarFileName())
.append("directory", jarDataObj.getPathData())
.append("version", jarDataObj.getVersion())
.append("artifactID", jarDataObj.getArtifactId())
.append("groupID", jarDataObj.getGroupId());
If I use doc.toJson() it shows me whole document. is there a way to extract only _id?
This gives me only the value i want it like the objectkey, So I can use it as reference key.
collection.insertOne(doc);
jarID = doc.get( "_id" );
System.out.println(jarID); //59a4db1a6812d7430c3ef2a5
Based on ObjectId Javadoc, you can simply instantiate an ObjectId from a 24 byte Hex string, which is what 59a4db1a6812d7430c3ef2a5 is if you use UTF-8 encoding. Why don't you just do new ObjectId("59a4db1a6812d7430c3ef2a5"), or new ObjectId("59a4db1a6812d7430c3ef2a5".getBytes(StandardCharsets.UTF_8))? Although, I'd say that exposing ObjectId outside the layer that integrates with Mongo is a design flaw.

MongoDB Java Driver

Given some JSON value and a query in MongoDB format, I want to filter the same way that MongoDB does, the json entities I want without going to the MongoDB.
For example, I have:
JSON Value: [{qty: 10}, {qty: 30}, {qty: 50}]
Query in MongoDB format: { qty: { $gt: 20 } }
Result: [{qty: 50}]
I want that without going to Mongo database, for example calling some method that recives JSON Value and JSON Query String in Mongo format, inside some JAR.
Thanks!
I want that without going to Mongo database
Parse JSON using Jackson and create a Query Object and a Collection containing the target objects.
Use a collections framework such as Guava or GS-Collections and filter.
'Jackson' library offers JSON parsing & generation in Java. Once you've parsed, you can filter values/ data structure using Java code to your heart's content.
Java obviously has no direct implementation of Mongo query language.. you can implement Java code yourself as desired.
See:
http://jackson.codehaus.org/

How to save the JSON data to the database

I am trying to save the JSON response of a website to the database. Latter I am accessing this JSON string for processing the data. But I am not able to parse it as JSON object. On analyzing I realize that the characters of strings needs to be escaped. Since I am saving the data as a string the data results which am getting back as a JSON data are not escaped in the database. Is there a way out how I can save the JSON data to the database.
Example:
{"RULE":[{"replace":{"value":"","type":"text"},"match":{"value":"<a [^>]*><img src="[^"]*WindowsLiveWriter/IconsfordifferentSocialBookmarkingSites[^>]*>\s*</a>","type":"text"}},{"replace":{"value":"","type":"text"},"match":{"value":"<a [^>]*><img src="[^"]*WindowsLiveWriter/IconsfordifferentSocialBookmarkingSites[^>]*>\s*</a>","type":"text"}}]}
Want to save in database as (also getting the response as) i.e. the " and \ are escaped
{"RULE":[{"replace":{"value":"","type":"text"},"match":{"value":"<a [^>]*><img src=\"[^\"]*WindowsLiveWriter/IconsfordifferentSocialBookmarkingSites[^>]*>\\s*</a>","type":"text"}},{"replace":{"value":"","type":"text"},"match":{"value":"<a [^>]*><img src=\"[^\"]*WindowsLiveWriter/IconsfordifferentSocialBookmarkingSites[^>]*>\\s*</a>","type":"text"}}]}
Here is the code I have used to save the data in the database
// here the raw_data is the data from the website
JSONObject jo = new JSONObject(raw_data);
// Get the JSONObject value associated with the search result key.
jo = jo.getJSONObject("pipe");
jo = jo.getJSONObject("definition");
String def=jo.toString();
JSONArray jo1=jo.getJSONArray("modules");
JSONArray jo2=jo.getJSONArray("wires");
/*
* Write the contents in the data base
*
*
*/
def =def.replaceAll( "[']", "\\\\\'" ); //creates problem for strings with '
def =def.replaceAll( "&", "%26" );
String tablename="PipesTable2";
System.out.println(def);
database d=new database();
I suggest you to create an class having properties mapped to json. You can convert object to json or json to object using third party tool.you can use Gson.
Now what you can do when you get the josn you can convert this json to object and save that object's properties to database. when you retrieve the value, set these value to object's properties and then convert this object to json.
You can find Gson here -
http://code.google.com/p/google-gson/
This is easy to use.
Have you considered using a library like Jackson ( http://wiki.fasterxml.com/JacksonHome ) to translate between Json objects and Java objects? Then you can use standard Java persistence tools and libraries to save it out to/read it in from your database, and it will handle all your escaping automatically.
Jackson has two main ways that it translates between Json and Java objects. If you're planning on using direct JDBC calls for your persistence and you don't want to do much other processing, then you can get away with "Simple Data Binding". This just translates between Json and Java's built-in types (List, Map, String, Boolean, Number).
If you're planning on doing Java processing on the data, or you want to use a persistence framework like Hibernate, you'll need "Full Data Binding". This uses POJOs and annotations to provide a more complex structure to your objects.
There is a good, very concise tutorial covering both options here:
http://wiki.fasterxml.com/JacksonInFiveMinutes

MongoDB - Merging two DBObjects

I am writing a model factory, for which I use JSON to load up a MongoDB DBObject like this:
import com.mongodb.util.JSON;
DBObject dbObject = (DBObject) JSON.parse("{'name':'jack', 'age':30}");
Now, I am trying to break up my JSON files such that I can load up a DBObject with one JSON file, and if needed I can augment the DBObject with another JSON file.
Although it sounds weird, imagine having a set of different type of users. Like, BasicUser, AdvancedUser etc. I can have a JSON file to load up BasicUser, and put the other non-overlapping details of an AdvancedUser in another JSON file. I can make AdvancedUser extend BasicUser, and so I can just combine the contents of the two JSON files to create an AdvancedUser model.
How could I achieve something like this?
I believe putAll is what you want.
DBObject obj1 = (DBObject) JSON.parse("{'name':'jack', 'age':30}");
DBObject obj2 = (DBObject) JSON.parse("{'role':'admin'}");
obj1.putAll(obj2);
System.out.println(obj1.toString()); //{ "name" : "jack" , "age" : 30 , "role" : "admin"}
I decided to roll out my own function to do this by recursively traversing one DBObject and transferring the contents to another.

Categories