Friday, June 13, 2014


JSON Parsing and Validation

Step I - JSON Parsing
To parse JSON data we can use  GSON library.
When given the json file as a String to parse method above, it will return the parsed JsonObject as tree.

public static JsonObject parse(String jsonString) {
JsonParser jsonParser = new JsonParser();
JsonElement rxtJsonElement = jsonParser.parse(jsonString);
JsonObject rxtJsonArtifactTypeObject = rxtJsonElement.getAsJsonObject().getAsJsonObject("artifactType");
return rxtJsonArtifactTypeObject;
}

Step II - JSON data format Validation
Develop Shema
JSON Schema is a tool for validating the structure of JSON data. When we consider data format we need to know what does data elements mean and what the valid inputs for these elements are. To ensure we have obtained the required data we write a schema.

I.Manually write Schema for JSON:

There are certain keywords that are used to develop a Schema for any sort of json data.
Most frequently used key words are:
Ø  type
Ø  properties
Ø  items
Ø  required
Ø  maxItems

JSON is built on two structures:
Ø  A collection of name/value pairs commonly realized as “objects”.
Ø  An ordered list of values commonly realized as “ arrays”.
This defines the type keyword in a Schema.
properties are defined to validate the attributes in an object.
Within an array the list of items are defined by items keyword.
Whether a particular object array or property and item is a must for it to validate is defined by required keyword. 
MaxItems defines the maximum number of elements in array type of object type.
Similarly you can find how any of this keyword defines the validity of the JSON data against the Schema we develop.

Example:
JSON data to be validated:
{
"address":{
"streetAddress": "21 2nd Street",
"city":"New York"
},
"phoneNumber":
[
{
"type":"home",
"number":"212 555-1234"
}
]
}

Schema developed:

{
"type":"object",
"required":false,
"properties":{
"address": {
"type":"object",
"required":false,
"properties":{
"city": {
"type":"string",
"required":false
},
"streetAddress": {
"type":"string",
"required":false
}
}
},
"phoneNumber": {
"type":"array",
"required":false,
"items":[
{
"type":"object",
"required":false,
"properties":{
"number": {
"type":"string",
"required":false
},
"type": {
"type":"string",
"required":false
}
}
}
}
}
}
  


II. Directly generates Schema for specific parsed JSON data format:

Step III - Validate functionality.
We can directly validate Schema functionality online.

Note:
To validate JSON content - http://jsonschemalint.com/




No comments:

Post a Comment