MongoDB document as a JsonNode (Jackson library) - java

I have the following use case -
Store a JSON schema (dynamic, changes over time) in mongodb.
Read JSON objects from a file and validate them against the schema
(in #1)
I am using this JSON Validator.
I need to read the schema from mongo db and convert it to JsonNode
(Jackson library).
I am using Java..
Can anyone let me know how to convert a mongodb document to JsonNode.. I need this because the validator I am using (mentioned in #3 above) needs a JsonNode to construct the schema object.
EDIT: Is it fine performance wise to convert DBObject to JSON string and then convert it to JsonNode?

Why not go straight from DBObject to JsonNode? iirc, JsonNode is just a map like DBObject is. Converting from one to the other (and back) should be pretty straightforward.

You could use the ObjectReader class (com.fasterxml.jackson.databind.ObjectReader):
ObjectMapper mapper = new ObjectMapper();
ObjectReader reader = mapper.reader(JsonNode.class);
JsonNode node = reader.readValue(document.toJson());
Here you can find some performance best practices for Jackson: http://wiki.fasterxml.com/JacksonBestPracticesPerformance

Related

ObjectMapper default value of if some fields cannot be cast to object

I'm new to Java, so apologies if this question is not to the desired standard: I'm loading data from a flat mongodb table and would like to write all the documents into a Pojo, I'm calling it DataClass. My issue is that in some cases the type of the field is not correct. In the below code I'm using mapper.readValue to read the Json and cast it to the object. If one of the fields is wrong, the whole loop fails. Is there a way to do it element-wise and just ignore cases where there is a failure or set a default value?
List<DataClass> result = new ArrayList<>();
FindIterable<Document> documents = getCollection().find();
for (Document doc : documents) {
result.add(mapper.readValue(doc.toJson(), DataClass.class));
Any suggestions would be greatly appreciated.
I guess you are looking for,
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
This will not fail the serialization if the passed json has unknown properties.
Moreover, as per the docs,
JsonMappingException if the input JSON structure does not match structure
expected for result type (or has other mismatch issues)
You can catch JsonMappingException if you are looking in that direction.

How to avoid any exceptions while converting a java object to JSON

I'm trying to generate a JSON string from a complex java object (using Jackson API). While parsing a field I see ClassCastException. The Java objects are not owned by my project so cannot change and fix the issue. Is there any easy way to fix this?
Please note, my code deals with any kind of Java object and doesn't this Java object in particular so I'm looking for something generic where if a field is not parsed successful, just ignore and move to the next one.
ObjectMapper mapper = new ObjectMapper();
CustomModule module = new CustomModule();
mapper.registerModule(module);
ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
ow.writeValueAsString(value)
You can globally disable checking for instance :
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
By default Jackson throws an exception, if it encounters a JSON property that it can not bind to object property.

De-serialize Array of objects to JSON in MongoDB

I am using Morphia (ver 0.99) for my JSON to Pojo mapping to my MongoDB (ver 2.0). Streaming data between web-clients and my server works fine. But now I have a use-case where I don't know what pattern that is most appropriate. Can I use Morphia or MongoDB Java driver to achieve my requirements or do I need to use Jackson and JPA 2.2 notation.
Here is my use-case;
Invoke Morphia query on selected collection (MongoDB)
The use the resulting ArrayList of Pojos for business logic and presentation (Primefaces)
Also convert the resulting ArrayList of Pojo's to JSON array of objects, but remove Pojo properties in the conversions that is not needed in the web-client
Push the converted JSON to the web-client for presentation
Converting one Pojo is straight forward with Morphia, but how do I convert an array?
return morph.toDBObject(obj).toString();
Is there a notation like #JsonIgnore in Morphia to ignore conversions to and from JSON ?
How can I most efficiently (without using more libraries if possible) to solve step three in in my use-case. Convert ArrayList to JSON and ignore conversion of some of the Pojo properties?
I've come up with a solution to my problem. It's maybe not the most elegant but it works the way I want and I don't have to include other libraries (like Gson and Jackson) to de-serialize my array list of Pojo's to Json, I only used classes from the MongoDB Java driver and the Morphia API. I also added a simple parameter list to strip away unnecessary property value to be pushed to the client.
public static String deserializeToJSON(List<?> objList, String... removeAttributes) {
List<DBObject> dbObjList = new ArrayList<>(objList.size());
DBObject dbObj;
for(Object obj :objList){
dbObj = morph.toDBObject(obj);
for(int i=0; i < removeAttributes.length; i++){
debug("Removed DBObject filed: " +dbObj.removeField(removeAttributes[i]));
}
dbObjList.add(dbObj);
}
String json = JSON.serialize(dbObjList);
return json;
}

JSON schema validator library in Java

I have a restful web service(JAVA) which has to accept JSON requests. I have to first validate this JSON against a JSON schema that I have.
I'm not sure what is the best JAVA library to validate JSON again JSON schemas.
I have used json-schema-validator-2.1.7 library but it has not been very helpful. Even thought my JSON is not a valid JSON I do not get any errors.
Here is the code I use for json-schema-validator-2.1.7
InputStream jsonSchemaInputStream = Assessment.class.getClassLoader().getResourceAsStream("Schemas/AssessmentMetrics.json");
ObjectMapper mapper = new ObjectMapper();
// Allows to retrieve a JSONSchema object on various sources
// supported by the ObjectMapper provided
JSONSchemaProvider schemaProvider = new JacksonSchemaProvider(mapper);
// Retrieves a JSON Schema object based on a file
JSONSchema schema = schemaProvider.getSchema(jsonSchemaInputStream);
// Validates a JSON Instance object stored in a file
List<String> errors = schema.validate(contents);
Projects worth exploring:
https://github.com/java-json-tools/json-schema-validator
https://github.com/everit-org/json-schema
https://github.com/networknt/json-schema-validator
Here is a nice list.
Here is an online sandbox.
I'm biased with jackson for all things JSON.
https://github.com/FasterXML/jackson-module-jsonSchema

Creating json object from POJO object in restful web service

I am developing a web application. I have database used by the web service. I want to send the same data to the web pages which are calling web service.
I get the data i.e. single row from the database by using hibernate and POJO classes(getColumn). Now I have object(POJO class) of the Table which represent single row of the database. For sending it back to the web pages (html, jsp), I need to convert it to the json object as my web service returns the json object.
How can I make Json object from POJO classes. There are many other ways to generate Json String but i want json object.
How can do this?
Thank you
You can use GSon to convert json object to java object
Link
to refer example.
Gson gson = new Gson();
//to get json object use toJson
String json = gson.toJson(obj);
//to get java object use fromJson
MyClass obj = gson.fromJson(jsonObj, MyClass.class);
or
jackson is also pretty fast and easy to use
private ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.convertValue(YOUR POJO CLASS, JsonNode.class);
You can use Jackson and achieve this as above. GSON also does the job.
The way I use is with Google's Gson library. Very simple and powerful
Spring and Jackson as it is so simple. You can find a very basic example below Jackson/spring JSON example

Categories

Resources