SlideShare a Scribd company logo
quick-json Parser
quick-json is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert
a JSON string to an equivalent Java object. quick-json can work with any arbitrary Java objects.
This parser supports validating/non-validating versions.
Non-Validating parser verifies the standards of json while parsing and will not validate keys/values and will not apply any custom
validations at all.
Validating parser version is a strict parser and it does parsing based upon pre-configured validation rules.
This Parser is a simple and flexible parser for parsing input JSON string and return the corresponding java collection
representation.
e.g.
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
Now Map generated out of the above mentioned JSON String will look like,
A map with one key as 'samplejson' and its value as another map of key/value pairs. i.e. it will be very easy for the developers to
look up for a specific key within json hierarchy.
Value can be looked up by just parsing the above JSON string using parsing API as follows,
JsonParserFactory factory=JsonParserFactory.getInstance();
JsonParser parser=factory.newJsonParser();
Map jsonData=parser.parse(inputJsonString);
String value=(String)jsonData.get("key2");
Simple examples of json,
E.g.1
[{
"key":"value",
"key1":[234234.32,adfasdf],
"key2":[arrayvalue,arrayvalue1,arrayvalue2]
},
{
"key":{
subjsonkey:subjsonvalue
}
},
"Rajesh Putta",
234234.23]
E.g.2
JSON:
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as
DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}
E.g.3
JSON:
{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}
E.g.4
JSON:
{"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
"vOffset": 250,
"alignment": "center"
},
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}}
quick-json features
# Compliant with JSON specification (RFC4627)
# High-Performance JSON parser
# Supports Flexible/Configurable parsing approach
# Configurable validation of key/value pairs of any JSON Heirarchy
# Easy to use # Very Less foot print
# Raises developer friendly and easy to trace exceptions
# Pluggable Custom Validation support - Keys/Values can be validated by configuring custom validators as and when
encountered
# Validating and Non-Validating parser support
# Support for two types of configuration (JSON/XML) for using quick-json validating parser
# Require JDK 1.5 (1.5.0_22_1) # No dependency on external libraries
# Support for Json Generation through object serialization
# Support for collection type selection during parsing process
quick-json Non-Validating parser
Usage
quick-json Non-Validating parser supports parsing of different formats of json strings which are compliant with JSON spec. Parser
throws developer friendly exceptions in case of there is any syntax/semantic issues.
E.g.
samplejson = {
"key1": value1,
"key_2": "value2",
key3: value3,
key4:234234234,
key5:234234.233
}
Value can be looked up by just parsing the above JSON string using parsing API as follows,
JsonParserFactory factory=JsonParserFactory.getInstance();
JsonParser parser=factory.newJsonParser();
Map jsonData=parser.parseJson(inputJsonString);
//lookup the key 'key_2' under Json Block 'samplejson'
String value=jsonData.get("samplejson").get("key_2");
{
"employees": [
{ "firstName":"Rajesh" , "lastName":"Putta" },
{ "firstName":"Rajesh" , "lastName":"P" },
{ "firstName":"first name" , "lastName":"last name" }
]
}
Value can be looked up by just parsing the above JSON string using parsing API as follows,
JsonParserFactory factory=JsonParserFactory.getInstance();
JsonParser parser=factory.newJsonParser();
Map jsonData=parser.parseJson(inputJsonString);
Map rootJson=jsonData.get("root");
List al=rootJson.get("employees");
String fName=((Map)al.get(0)).get("firstName");
String lName=((Map)al.get(0)).get("lastName");
quick-json Validating parser Usage
quick json validating parser can be used whenever json has to be validated at every level to see if the format is expected or not.
Keys/Values, Sub-Json, Array and its elements can be validated.
What/When/Where needs to be validated ? All this information is expected to be passed to the parser during initialization.
Below is the sample way of initializing and working with validating parser.
JsonParserFactory factory=JsonParserFactory.getInstance();
JsonParser parser=factory.newJsonParser();
//initialize parser with the json validation configuration file stream
parser.initialize(xml_stream));
//configure parser for validating
parser.setValidating(true);
//parse input json string with validating parser instance
Map jsonData=parser.parseJson(inputJsonString);
E.g.1
Input JSON String
sample={
"key":"value",
"key1":"value1",
"key2":234234234
}
Validation configuration for the above JSON string would be,
<json-config>
<json-heirarchy path="root">
<KeyValues>
<KeyValue name="ROOT" valueType="JSON"/>
</KeyValues>
</json-heirarchy>
<json-heirarchy path="sample">
<KeyValues>
<KeyValue name="default" valueType="STRING_LITERAL"/>
<KeyValue name="key2" valueType="INTEGER"/>
</KeyValues>
</json-heirarchy>
</json-config>
root configuration is for validating the root level, this is mandatory to validate the root level is JSON/JSON_ARRAY
sample configuration is for the key/value pairs under sample json string. As per the above configuration, default configuration is
applicable for all the key/value pairs whenever there is no specific validation configured for keys. In this case key2 requirement is
to have separate validation configuration. so overriding the default one.
Validation data types
JSON validates for JSON presence
JSON_ARRAY validates for JSON_ARRAY presence
STRING_LITERAL validates for double quoted string presence
STRING Validates for simple string with alphanumeric data
INTEGER Validates for number data, doesnt allow double type of values
DOUBLE Validates for number data, allows double type of values
BOOLEAN Validates for boolean value (true or false)
NULL Validates for null
E.g.2
Input JSON String
sample={
"key":"value",
"key1":["value1",234234.32,adfasdf],
"key2":234234234
}
Validation Configuration for the above json string would be,
<json-config>
<json-heirarchy path="root">
<KeyValues>
<KeyValue name="ROOT" valueType="JSON"/>
</KeyValues>
</json-heirarchy>
<json-heirarchy path="sample">
<KeyValues>
<KeyValue name="default" valueType="STRING_LITERAL"/>
<KeyValue name="key1" valueType="JSON_ARRAY"/>
<KeyValue name="key2" valueType="INTEGER"/>
</KeyValues>
</json-heirarchy>
<json-heirarchy path="sample/key1">
<KeyValues>
<KeyValue name="default" valueType="STRING_LITERAL"/>
<KeyValue index="1" valueType="DOUBLE"/>
<KeyValue index="2" valueType="STRING"/>
</KeyValues>
</json-heirarchy>
</json-config>
quick-json Validating parser Usage -
with JSON based validation
configuration
quick json validating parser can be configure with JSON based validation configuration whenever other json has to be validated at
every level to see if the format is expected or not. Keys/Values, Sub-Json, Array and its elements can be validated.
What/When/Where needs to be validated ? All this information is expected to be passed to the parser during initialization.
Below is the sample way of initializing and working with validating parser with JSON based validation configuration.
JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser(ValidationConfigType.JSON);
parser.initializeWithJson(json_based_validation_config_stream);
parser.setValidating(true);
//parse input json string with validating parser instance
Map jsonData=parser.parseJson(inputJsonString);
E.g.1
[{
"key":"value",
"key1":[234234.32,true ],
"key2":[arrayvalue,arrayvalue1,arrayvalue2]
},
{
"key":{
subjsonkey:subjsonvalue
}
},
"Rajesh Putta",
234234.23]
Below would be the JSON based validation configuration,
{
"root":{
"ROOT":{valueType:"JSON_ARRAY"},
"0":{valueType:"JSON"},
"1":{valueType:"JSON"},
"2":{valueType:"STRING_LITERAL"},
"3":{valueType:"DOUBLE"}
},
"root[0]":{
"key1":{valueType:"JSON_ARRAY"},
"key2":{valueType:"JSON_ARRAY"}
},
"root[1]":{
"key":{valueType:"JSON"}
},
"root[0]/key1":{
"0":{valueType:"DOUBLE"},
"1":{valueType:"BOOLEAN"}
},
"root[0]/key2":{
"default":{valueType:"STRING"}
},
"root[1]/key":{
"default":{valueType:"STRING"}
},
}
Json Generator Usage
JSONGenerator helps in serializing the java objects to JSON format.
- Supports serialization of Classes, Arrays, Map, List, Set, Properties, String, Date, Integer, Float, Double, Boolean, etc types of
data
- Strictly adheres to the JSON spec during serialization process
E.g.
Here is the example data set hierarchy to be serialized to JSON format,
Map data=new HashMap();
Properties prop=new Properties();
prop.setProperty("1", "1");
prop.setProperty("2", "2");
prop.setProperty("3", "3");
data.put("name", "Rajesh Putta");
data.put("age", 28);
data.put("city", new StringBuilder("hyderabad"));
data.put("subdata", prop);
data.put("array", new int[]{234,555,777,888});
data.put("chararray", new char[]{'a','b','c'});
data.put("doublearray", new double[]{234,555,777,888});
data.put("floatarray", new byte[]{1,2,34,35});
Map submap=new HashMap();
submap.put(1, 10);
submap.put(2, 20);
TestPojo tp=new TestPojo();
tp.setAge(28);
tp.setName("Rajesh");
tp.setSs(3223.33);
tp.setData(submap);
Set set=new HashSet();
set.add(234);
set.add(2343);
set.add("asdfasfd");
set.add(tp);
data.put("set-pojo", set);
data.put("objectarray", new Object[]{submap,set,submap,tp});
Here is the implementation for serializing the above data set
JsonGeneratorFactory factory=JsonGeneratorFactory.getInstance();
JSONGenerator generator=factory.newJsonGenerator();
String json=generator.generateJson(data);
Here is the serialized data object,
[{"age":28,"doublearray":[234.0,555.0,777.0,888.0],"floatarray":[1,2,34,35],"set-pojo":["asdfasfd",
{"name":"Rajesh","age":28,"ss":3223.33,"data":{"2":20,"1":10},},2343,234],"subdata":
{"3":"3","2":"2","1":"1"},"objectarray":[{"2":20,"1":10},{"2":20,"1":10},
{"name":"Rajesh","age":28,"ss":3223.33,"data":{"2":20,"1":10},}],"name":"Rajesh Putta","chararray":
[a,b,c],"city":"hyderabad","array":[234,555,777,888]}]

More Related Content

What's hot (20)

PDF
Querydsl fin jug - june 2012
Timo Westkämper
 
PDF
Don’t Get Lost in Translation for Serializing Data Structures
Christopher Brown
 
PDF
Линзы - комбинаторная манипуляция данными Александр Гранин Dev2Dev v2.0 30.05...
Dev2Dev
 
PPTX
Protractor Training in Pune by QuickITDotnet
QuickITDotNet Training and Services
 
PDF
주로사용되는 Xss필터와 이를 공격하는 방법
guestad13b55
 
PDF
Spray Json and MongoDB Queries: Insights and Simple Tricks.
Andrii Lashchenko
 
PPTX
Nancy + rest mow2012
Christian Horsdal
 
PDF
Alternate JVM Languages
Saltmarch Media
 
PPTX
Mythbusting: Understanding How We Measure the Performance of MongoDB
MongoDB
 
PDF
greenDAO
Mu Chun Wang
 
PPT
Php Security By Mugdha And Anish
OSSCube
 
PDF
Spring Framework - Expression Language
Dzmitry Naskou
 
DOCX
WOTC_Import
Luther Quinn
 
PDF
New methods for exploiting ORM injections in Java applications
Mikhail Egorov
 
PDF
Everything About PowerShell
Gaetano Causio
 
PPT
Quebec pdo
Valentine Dianov
 
PDF
Solr's Search Relevancy (Understand Solr's query debug)
Wongnai
 
TXT
Blog skins396734
pantangmrny
 
PDF
Secure .NET programming
Ante Gulam
 
PPTX
Final microsoft cloud summit - windows azure building block services
stratospheres
 
Querydsl fin jug - june 2012
Timo Westkämper
 
Don’t Get Lost in Translation for Serializing Data Structures
Christopher Brown
 
Линзы - комбинаторная манипуляция данными Александр Гранин Dev2Dev v2.0 30.05...
Dev2Dev
 
Protractor Training in Pune by QuickITDotnet
QuickITDotNet Training and Services
 
주로사용되는 Xss필터와 이를 공격하는 방법
guestad13b55
 
Spray Json and MongoDB Queries: Insights and Simple Tricks.
Andrii Lashchenko
 
Nancy + rest mow2012
Christian Horsdal
 
Alternate JVM Languages
Saltmarch Media
 
Mythbusting: Understanding How We Measure the Performance of MongoDB
MongoDB
 
greenDAO
Mu Chun Wang
 
Php Security By Mugdha And Anish
OSSCube
 
Spring Framework - Expression Language
Dzmitry Naskou
 
WOTC_Import
Luther Quinn
 
New methods for exploiting ORM injections in Java applications
Mikhail Egorov
 
Everything About PowerShell
Gaetano Causio
 
Quebec pdo
Valentine Dianov
 
Solr's Search Relevancy (Understand Solr's query debug)
Wongnai
 
Blog skins396734
pantangmrny
 
Secure .NET programming
Ante Gulam
 
Final microsoft cloud summit - windows azure building block services
stratospheres
 

Viewers also liked (9)

PPTX
Facebook
Kaustubh Brid
 
PPTX
Chapter7 130130085559-phpapp01
Einsteinian Kristian Kagahastian Ü
 
PPT
XML
thotasrinath
 
PPT
Xml
Amit Pandey
 
PPTX
Cross contamination
Vince Lacuarta
 
PDF
Xml parsing
Malintha Adikari
 
PPT
Xml parsers
Manav Prasad
 
PDF
Validating Xml
LiquidHub
 
PDF
Parsing XML in J2ME
Rohan Chandane
 
Facebook
Kaustubh Brid
 
Chapter7 130130085559-phpapp01
Einsteinian Kristian Kagahastian Ü
 
Cross contamination
Vince Lacuarta
 
Xml parsing
Malintha Adikari
 
Xml parsers
Manav Prasad
 
Validating Xml
LiquidHub
 
Parsing XML in J2ME
Rohan Chandane
 
Ad

Similar to quick json parser (17)

PPTX
Gson
哲偉 楊
 
PDF
JSON support in Java EE 8
Lukas Jungmann
 
PPTX
JSON Support in Java EE 8
Dmitry Kornilov
 
PDF
Updates to the java api for json processing for java ee 8
Alex Soto
 
PPTX
JSON-(JavaScript Object Notation)
Skillwise Group
 
PDF
Json Processing API (JSR 353) review
Martin Skurla
 
PPTX
JSON Support in Java EE 8
Dmitry Kornilov
 
PPTX
Screaming fast json parsing on Android
Karthik Ramgopal
 
PDF
Hands on JSON
Octavian Nadolu
 
PDF
JParse Fast JSON Parser
Rick Hightower
 
PPTX
Java-JSON-Jackson
Srilatha Kante
 
PPTX
JSON Support in Jakarta EE: Present and Future
Dmitry Kornilov
 
PDF
Simple JSON parser
Dongjun Lee
 
PPTX
Json processing
Ahmed Gamil
 
PDF
JSONModel Lightning Talk
Marin Todorov
 
PDF
How to Fix JSON Parsing Issues - Key Concept You MUSt Know
ZeeshanAcademy1
 
PDF
Json.parse() in JavaScript
Ideas2IT Technologies
 
JSON support in Java EE 8
Lukas Jungmann
 
JSON Support in Java EE 8
Dmitry Kornilov
 
Updates to the java api for json processing for java ee 8
Alex Soto
 
JSON-(JavaScript Object Notation)
Skillwise Group
 
Json Processing API (JSR 353) review
Martin Skurla
 
JSON Support in Java EE 8
Dmitry Kornilov
 
Screaming fast json parsing on Android
Karthik Ramgopal
 
Hands on JSON
Octavian Nadolu
 
JParse Fast JSON Parser
Rick Hightower
 
Java-JSON-Jackson
Srilatha Kante
 
JSON Support in Jakarta EE: Present and Future
Dmitry Kornilov
 
Simple JSON parser
Dongjun Lee
 
Json processing
Ahmed Gamil
 
JSONModel Lightning Talk
Marin Todorov
 
How to Fix JSON Parsing Issues - Key Concept You MUSt Know
ZeeshanAcademy1
 
Json.parse() in JavaScript
Ideas2IT Technologies
 
Ad

Recently uploaded (20)

PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 

quick json parser

  • 1. quick-json Parser quick-json is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. quick-json can work with any arbitrary Java objects. This parser supports validating/non-validating versions. Non-Validating parser verifies the standards of json while parsing and will not validate keys/values and will not apply any custom validations at all. Validating parser version is a strict parser and it does parsing based upon pre-configured validation rules. This Parser is a simple and flexible parser for parsing input JSON string and return the corresponding java collection representation. e.g. { "key1": "value1", "key2": "value2", "key3": "value3" } Now Map generated out of the above mentioned JSON String will look like, A map with one key as 'samplejson' and its value as another map of key/value pairs. i.e. it will be very easy for the developers to look up for a specific key within json hierarchy. Value can be looked up by just parsing the above JSON string using parsing API as follows, JsonParserFactory factory=JsonParserFactory.getInstance(); JsonParser parser=factory.newJsonParser(); Map jsonData=parser.parse(inputJsonString); String value=(String)jsonData.get("key2"); Simple examples of json, E.g.1 [{ "key":"value", "key1":[234234.32,adfasdf], "key2":[arrayvalue,arrayvalue1,arrayvalue2] }, { "key":{ subjsonkey:subjsonvalue } }, "Rajesh Putta", 234234.23]
  • 2. E.g.2 JSON: { "glossary": { "title": "example glossary", "GlossDiv": { "title": "S", "GlossList": { "GlossEntry": { "ID": "SGML", "SortAs": "SGML", "GlossTerm": "Standard Generalized Markup Language", "Acronym": "SGML", "Abbrev": "ISO 8879:1986", "GlossDef": { "para": "A meta-markup language, used to create markup languages such as DocBook.", "GlossSeeAlso": ["GML", "XML"] }, "GlossSee": "markup" } } } } } E.g.3 JSON: {"menu": { "id": "file", "value": "File", "popup": { "menuitem": [ {"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"} ] } }} E.g.4 JSON: {"widget": { "debug": "on", "window": { "title": "Sample Konfabulator Widget", "name": "main_window", "width": 500, "height": 500 }, "image": { "src": "Images/Sun.png", "name": "sun1", "hOffset": 250, "vOffset": 250, "alignment": "center" }, "text": { "data": "Click Here", "size": 36, "style": "bold", "name": "text1", "hOffset": 250,
  • 3. "vOffset": 100, "alignment": "center", "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;" } }} quick-json features # Compliant with JSON specification (RFC4627) # High-Performance JSON parser # Supports Flexible/Configurable parsing approach # Configurable validation of key/value pairs of any JSON Heirarchy # Easy to use # Very Less foot print # Raises developer friendly and easy to trace exceptions # Pluggable Custom Validation support - Keys/Values can be validated by configuring custom validators as and when encountered # Validating and Non-Validating parser support # Support for two types of configuration (JSON/XML) for using quick-json validating parser # Require JDK 1.5 (1.5.0_22_1) # No dependency on external libraries # Support for Json Generation through object serialization # Support for collection type selection during parsing process quick-json Non-Validating parser Usage quick-json Non-Validating parser supports parsing of different formats of json strings which are compliant with JSON spec. Parser throws developer friendly exceptions in case of there is any syntax/semantic issues. E.g. samplejson = { "key1": value1, "key_2": "value2", key3: value3, key4:234234234, key5:234234.233 }
  • 4. Value can be looked up by just parsing the above JSON string using parsing API as follows, JsonParserFactory factory=JsonParserFactory.getInstance(); JsonParser parser=factory.newJsonParser(); Map jsonData=parser.parseJson(inputJsonString); //lookup the key 'key_2' under Json Block 'samplejson' String value=jsonData.get("samplejson").get("key_2"); { "employees": [ { "firstName":"Rajesh" , "lastName":"Putta" }, { "firstName":"Rajesh" , "lastName":"P" }, { "firstName":"first name" , "lastName":"last name" } ] } Value can be looked up by just parsing the above JSON string using parsing API as follows, JsonParserFactory factory=JsonParserFactory.getInstance(); JsonParser parser=factory.newJsonParser(); Map jsonData=parser.parseJson(inputJsonString); Map rootJson=jsonData.get("root"); List al=rootJson.get("employees"); String fName=((Map)al.get(0)).get("firstName"); String lName=((Map)al.get(0)).get("lastName"); quick-json Validating parser Usage quick json validating parser can be used whenever json has to be validated at every level to see if the format is expected or not. Keys/Values, Sub-Json, Array and its elements can be validated. What/When/Where needs to be validated ? All this information is expected to be passed to the parser during initialization. Below is the sample way of initializing and working with validating parser. JsonParserFactory factory=JsonParserFactory.getInstance(); JsonParser parser=factory.newJsonParser(); //initialize parser with the json validation configuration file stream parser.initialize(xml_stream)); //configure parser for validating parser.setValidating(true); //parse input json string with validating parser instance Map jsonData=parser.parseJson(inputJsonString); E.g.1 Input JSON String sample={ "key":"value", "key1":"value1", "key2":234234234 }
  • 5. Validation configuration for the above JSON string would be, <json-config> <json-heirarchy path="root"> <KeyValues> <KeyValue name="ROOT" valueType="JSON"/> </KeyValues> </json-heirarchy> <json-heirarchy path="sample"> <KeyValues> <KeyValue name="default" valueType="STRING_LITERAL"/> <KeyValue name="key2" valueType="INTEGER"/> </KeyValues> </json-heirarchy> </json-config> root configuration is for validating the root level, this is mandatory to validate the root level is JSON/JSON_ARRAY sample configuration is for the key/value pairs under sample json string. As per the above configuration, default configuration is applicable for all the key/value pairs whenever there is no specific validation configured for keys. In this case key2 requirement is to have separate validation configuration. so overriding the default one. Validation data types JSON validates for JSON presence JSON_ARRAY validates for JSON_ARRAY presence STRING_LITERAL validates for double quoted string presence STRING Validates for simple string with alphanumeric data INTEGER Validates for number data, doesnt allow double type of values DOUBLE Validates for number data, allows double type of values BOOLEAN Validates for boolean value (true or false) NULL Validates for null E.g.2 Input JSON String sample={ "key":"value", "key1":["value1",234234.32,adfasdf], "key2":234234234 } Validation Configuration for the above json string would be, <json-config> <json-heirarchy path="root"> <KeyValues> <KeyValue name="ROOT" valueType="JSON"/> </KeyValues> </json-heirarchy> <json-heirarchy path="sample"> <KeyValues> <KeyValue name="default" valueType="STRING_LITERAL"/> <KeyValue name="key1" valueType="JSON_ARRAY"/>
  • 6. <KeyValue name="key2" valueType="INTEGER"/> </KeyValues> </json-heirarchy> <json-heirarchy path="sample/key1"> <KeyValues> <KeyValue name="default" valueType="STRING_LITERAL"/> <KeyValue index="1" valueType="DOUBLE"/> <KeyValue index="2" valueType="STRING"/> </KeyValues> </json-heirarchy> </json-config> quick-json Validating parser Usage - with JSON based validation configuration quick json validating parser can be configure with JSON based validation configuration whenever other json has to be validated at every level to see if the format is expected or not. Keys/Values, Sub-Json, Array and its elements can be validated. What/When/Where needs to be validated ? All this information is expected to be passed to the parser during initialization. Below is the sample way of initializing and working with validating parser with JSON based validation configuration. JsonParserFactory factory=JsonParserFactory.getInstance(); JSONParser parser=factory.newJsonParser(ValidationConfigType.JSON); parser.initializeWithJson(json_based_validation_config_stream); parser.setValidating(true); //parse input json string with validating parser instance Map jsonData=parser.parseJson(inputJsonString); E.g.1 [{ "key":"value", "key1":[234234.32,true ], "key2":[arrayvalue,arrayvalue1,arrayvalue2] }, { "key":{ subjsonkey:subjsonvalue } }, "Rajesh Putta", 234234.23] Below would be the JSON based validation configuration, { "root":{ "ROOT":{valueType:"JSON_ARRAY"}, "0":{valueType:"JSON"}, "1":{valueType:"JSON"},
  • 7. "2":{valueType:"STRING_LITERAL"}, "3":{valueType:"DOUBLE"} }, "root[0]":{ "key1":{valueType:"JSON_ARRAY"}, "key2":{valueType:"JSON_ARRAY"} }, "root[1]":{ "key":{valueType:"JSON"} }, "root[0]/key1":{ "0":{valueType:"DOUBLE"}, "1":{valueType:"BOOLEAN"} }, "root[0]/key2":{ "default":{valueType:"STRING"} }, "root[1]/key":{ "default":{valueType:"STRING"} }, } Json Generator Usage JSONGenerator helps in serializing the java objects to JSON format. - Supports serialization of Classes, Arrays, Map, List, Set, Properties, String, Date, Integer, Float, Double, Boolean, etc types of data - Strictly adheres to the JSON spec during serialization process E.g. Here is the example data set hierarchy to be serialized to JSON format, Map data=new HashMap(); Properties prop=new Properties(); prop.setProperty("1", "1"); prop.setProperty("2", "2"); prop.setProperty("3", "3"); data.put("name", "Rajesh Putta"); data.put("age", 28); data.put("city", new StringBuilder("hyderabad")); data.put("subdata", prop); data.put("array", new int[]{234,555,777,888}); data.put("chararray", new char[]{'a','b','c'}); data.put("doublearray", new double[]{234,555,777,888}); data.put("floatarray", new byte[]{1,2,34,35}); Map submap=new HashMap(); submap.put(1, 10); submap.put(2, 20); TestPojo tp=new TestPojo(); tp.setAge(28); tp.setName("Rajesh"); tp.setSs(3223.33); tp.setData(submap); Set set=new HashSet();
  • 8. set.add(234); set.add(2343); set.add("asdfasfd"); set.add(tp); data.put("set-pojo", set); data.put("objectarray", new Object[]{submap,set,submap,tp}); Here is the implementation for serializing the above data set JsonGeneratorFactory factory=JsonGeneratorFactory.getInstance(); JSONGenerator generator=factory.newJsonGenerator(); String json=generator.generateJson(data); Here is the serialized data object, [{"age":28,"doublearray":[234.0,555.0,777.0,888.0],"floatarray":[1,2,34,35],"set-pojo":["asdfasfd", {"name":"Rajesh","age":28,"ss":3223.33,"data":{"2":20,"1":10},},2343,234],"subdata": {"3":"3","2":"2","1":"1"},"objectarray":[{"2":20,"1":10},{"2":20,"1":10}, {"name":"Rajesh","age":28,"ss":3223.33,"data":{"2":20,"1":10},}],"name":"Rajesh Putta","chararray": [a,b,c],"city":"hyderabad","array":[234,555,777,888]}]