Question

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);
Était-ce utile?

La solution

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

Autres conseils

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!

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top