JSON schema validator library in Java - 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

Related

How to parse xml into json with jackson

Can someone point me to the correct way to convert xml into json with jackson?
I have one service that accepts a post request with an xml body, I want to take that xml and send it to another service as a json.
I've seen some examples where people use an ObjectMapper, but ideally, I would have an interface ModelJsonView and then use the setMixInAnnotation() method to bind it to the corresponding model class.
Try this:
String xml = "<testName>Tester</testName><testValue>100</testValue>"
JSONObject xmlToJsonObject = XML.toJSONObject(xml);
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
Object json = mapper.readValue(xmlToJsonObject.toString(), Object.class);
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json));
Include org.json and jackson jars.

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.

Is there a dynamic data structure that can be automatically serialized to XML or JSON?

I'm developing a restful web-service that should be able to return JSON or XML responses upon request. Of course, the JSON response should be identical to the XML response when the data is compared.
The thing is that I can't use a Java pojo because the returned data fields are dynamic, they are unpredictable.
For example, a specific user may have the following response:
{
"propertyA": "propertyA-Value",
"propertyB": "propertyB-Value",
}
...another user may have:
{
"propertyA": "propertyA-Value",
"propertyB": "propertyB-Value",
"propertyC": "propertyC-Value",
}
...or the XML representation would be
<results>
<propertyA>propertyA-Value</propertyA>
<propertyB>propertyB-Value</propertyB>
<propertyC>propertyC-Value</propertyC>
</results>
Is there a way to automatically serialize the structure holding the previously mentioned data, to JSON or XML. By "automatically", I mean using an API that would work with whatever fields provided.
I can't use an array\list of feature-name\feature-value structures as the service consumer needs to receive the response as mentioned.
use codehaus fasterxml object mapper. A sample app can be seen from below link
https://github.com/abhishek24509/JsonMapper
ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
the above code will help to hold dyamic response. Your pojo can have all possible field. But during mapping it will ignore unknown

MongoDB document as a JsonNode (Jackson library)

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

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