SlideShare a Scribd company logo
1 of 8
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

Querydsl fin jug - june 2012
Querydsl   fin jug - june 2012Querydsl   fin jug - june 2012
Querydsl fin jug - june 2012Timo Westkämper
 
Don’t Get Lost in Translation for Serializing Data Structures
Don’t Get Lost in Translation for Serializing Data StructuresDon’t Get Lost in Translation for Serializing Data Structures
Don’t Get Lost in Translation for Serializing Data StructuresChristopher Brown
 
Линзы - комбинаторная манипуляция данными Александр Гранин Dev2Dev v2.0 30.05...
Линзы - комбинаторная манипуляция данными Александр Гранин Dev2Dev v2.0 30.05...Линзы - комбинаторная манипуляция данными Александр Гранин Dev2Dev v2.0 30.05...
Линзы - комбинаторная манипуляция данными Александр Гранин Dev2Dev v2.0 30.05...Dev2Dev
 
주로사용되는 Xss필터와 이를 공격하는 방법
주로사용되는 Xss필터와 이를 공격하는 방법주로사용되는 Xss필터와 이를 공격하는 방법
주로사용되는 Xss필터와 이를 공격하는 방법guestad13b55
 
Spray Json and MongoDB Queries: Insights and Simple Tricks.
Spray Json and MongoDB Queries: Insights and Simple Tricks.Spray Json and MongoDB Queries: Insights and Simple Tricks.
Spray Json and MongoDB Queries: Insights and Simple Tricks.Andrii Lashchenko
 
Mythbusting: Understanding How We Measure the Performance of MongoDB
Mythbusting: Understanding How We Measure the Performance of MongoDBMythbusting: Understanding How We Measure the Performance of MongoDB
Mythbusting: Understanding How We Measure the Performance of MongoDBMongoDB
 
Php Security By Mugdha And Anish
Php Security By Mugdha And AnishPhp Security By Mugdha And Anish
Php Security By Mugdha And AnishOSSCube
 
Spring Framework - Expression Language
Spring Framework - Expression LanguageSpring Framework - Expression Language
Spring Framework - Expression LanguageDzmitry Naskou
 
New methods for exploiting ORM injections in Java applications
New methods for exploiting ORM injections in Java applicationsNew methods for exploiting ORM injections in Java applications
New methods for exploiting ORM injections in Java applicationsMikhail Egorov
 
Everything About PowerShell
Everything About PowerShellEverything About PowerShell
Everything About PowerShellGaetano Causio
 
Solr's Search Relevancy (Understand Solr's query debug)
Solr's Search Relevancy (Understand Solr's query debug)Solr's Search Relevancy (Understand Solr's query debug)
Solr's Search Relevancy (Understand Solr's query debug)Wongnai
 
Blog skins396734
Blog skins396734Blog skins396734
Blog skins396734pantangmrny
 
Secure .NET programming
Secure .NET programmingSecure .NET programming
Secure .NET programmingAnte Gulam
 
Final microsoft cloud summit - windows azure building block services
Final   microsoft cloud summit - windows azure building block servicesFinal   microsoft cloud summit - windows azure building block services
Final microsoft cloud summit - windows azure building block servicesstratospheres
 

What's hot (20)

Querydsl fin jug - june 2012
Querydsl   fin jug - june 2012Querydsl   fin jug - june 2012
Querydsl fin jug - june 2012
 
Don’t Get Lost in Translation for Serializing Data Structures
Don’t Get Lost in Translation for Serializing Data StructuresDon’t Get Lost in Translation for Serializing Data Structures
Don’t Get Lost in Translation for Serializing Data Structures
 
Линзы - комбинаторная манипуляция данными Александр Гранин Dev2Dev v2.0 30.05...
Линзы - комбинаторная манипуляция данными Александр Гранин Dev2Dev v2.0 30.05...Линзы - комбинаторная манипуляция данными Александр Гранин Dev2Dev v2.0 30.05...
Линзы - комбинаторная манипуляция данными Александр Гранин Dev2Dev v2.0 30.05...
 
Protractor Training in Pune by QuickITDotnet
Protractor Training in Pune by QuickITDotnet Protractor Training in Pune by QuickITDotnet
Protractor Training in Pune by QuickITDotnet
 
주로사용되는 Xss필터와 이를 공격하는 방법
주로사용되는 Xss필터와 이를 공격하는 방법주로사용되는 Xss필터와 이를 공격하는 방법
주로사용되는 Xss필터와 이를 공격하는 방법
 
Spray Json and MongoDB Queries: Insights and Simple Tricks.
Spray Json and MongoDB Queries: Insights and Simple Tricks.Spray Json and MongoDB Queries: Insights and Simple Tricks.
Spray Json and MongoDB Queries: Insights and Simple Tricks.
 
Nancy + rest mow2012
Nancy + rest   mow2012Nancy + rest   mow2012
Nancy + rest mow2012
 
Alternate JVM Languages
Alternate JVM LanguagesAlternate JVM Languages
Alternate JVM Languages
 
Mythbusting: Understanding How We Measure the Performance of MongoDB
Mythbusting: Understanding How We Measure the Performance of MongoDBMythbusting: Understanding How We Measure the Performance of MongoDB
Mythbusting: Understanding How We Measure the Performance of MongoDB
 
greenDAO
greenDAOgreenDAO
greenDAO
 
Php Security By Mugdha And Anish
Php Security By Mugdha And AnishPhp Security By Mugdha And Anish
Php Security By Mugdha And Anish
 
Spring Framework - Expression Language
Spring Framework - Expression LanguageSpring Framework - Expression Language
Spring Framework - Expression Language
 
WOTC_Import
WOTC_ImportWOTC_Import
WOTC_Import
 
New methods for exploiting ORM injections in Java applications
New methods for exploiting ORM injections in Java applicationsNew methods for exploiting ORM injections in Java applications
New methods for exploiting ORM injections in Java applications
 
Everything About PowerShell
Everything About PowerShellEverything About PowerShell
Everything About PowerShell
 
Quebec pdo
Quebec pdoQuebec pdo
Quebec pdo
 
Solr's Search Relevancy (Understand Solr's query debug)
Solr's Search Relevancy (Understand Solr's query debug)Solr's Search Relevancy (Understand Solr's query debug)
Solr's Search Relevancy (Understand Solr's query debug)
 
Blog skins396734
Blog skins396734Blog skins396734
Blog skins396734
 
Secure .NET programming
Secure .NET programmingSecure .NET programming
Secure .NET programming
 
Final microsoft cloud summit - windows azure building block services
Final   microsoft cloud summit - windows azure building block servicesFinal   microsoft cloud summit - windows azure building block services
Final microsoft cloud summit - windows azure building block services
 

Viewers also liked (9)

Facebook
Facebook Facebook
Facebook
 
Chapter7 130130085559-phpapp01
Chapter7 130130085559-phpapp01Chapter7 130130085559-phpapp01
Chapter7 130130085559-phpapp01
 
XML
XMLXML
XML
 
Xml
XmlXml
Xml
 
Cross contamination
Cross contaminationCross contamination
Cross contamination
 
Xml parsing
Xml parsingXml parsing
Xml parsing
 
Xml parsers
Xml parsersXml parsers
Xml parsers
 
Validating Xml
Validating XmlValidating Xml
Validating Xml
 
Parsing XML in J2ME
Parsing XML in J2MEParsing XML in J2ME
Parsing XML in J2ME
 

Similar to quick json parser

d3sparql.js demo at SWAT4LS 2014 in Berlin
d3sparql.js demo at SWAT4LS 2014 in Berlind3sparql.js demo at SWAT4LS 2014 in Berlin
d3sparql.js demo at SWAT4LS 2014 in BerlinToshiaki Katayama
 
Starting with JSON Path Expressions in Oracle 12.1.0.2
Starting with JSON Path Expressions in Oracle 12.1.0.2Starting with JSON Path Expressions in Oracle 12.1.0.2
Starting with JSON Path Expressions in Oracle 12.1.0.2Marco Gralike
 
Validating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentationValidating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentationDave Stokes
 
Oracle Database - JSON and the In-Memory Database
Oracle Database - JSON and the In-Memory DatabaseOracle Database - JSON and the In-Memory Database
Oracle Database - JSON and the In-Memory DatabaseMarco Gralike
 
Open Source Search: An Analysis
Open Source Search: An AnalysisOpen Source Search: An Analysis
Open Source Search: An AnalysisJustin Finkelstein
 
JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)Skillwise Group
 
Security Challenges in Node.js
Security Challenges in Node.jsSecurity Challenges in Node.js
Security Challenges in Node.jsWebsecurify
 
Nodejs functional programming and schema validation lightning talk
Nodejs   functional programming and schema validation lightning talkNodejs   functional programming and schema validation lightning talk
Nodejs functional programming and schema validation lightning talkDeepank Gupta
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on AndroidSven Haiges
 
UKOUG Tech14 - Getting Started With JSON in the Database
UKOUG Tech14 - Getting Started With JSON in the DatabaseUKOUG Tech14 - Getting Started With JSON in the Database
UKOUG Tech14 - Getting Started With JSON in the DatabaseMarco Gralike
 
Store non-structured data in JSON column types and enhancements of JSON
Store non-structured data in JSON column types and enhancements of JSONStore non-structured data in JSON column types and enhancements of JSON
Store non-structured data in JSON column types and enhancements of JSONAlireza Kamrani
 
Basics of JSON (JavaScript Object Notation) with examples
Basics of JSON (JavaScript Object Notation) with examplesBasics of JSON (JavaScript Object Notation) with examples
Basics of JSON (JavaScript Object Notation) with examplesSanjeev Kumar Jaiswal
 

Similar to quick json parser (20)

Advanced Json
Advanced JsonAdvanced Json
Advanced Json
 
Json the-x-in-ajax1588
Json the-x-in-ajax1588Json the-x-in-ajax1588
Json the-x-in-ajax1588
 
d3sparql.js demo at SWAT4LS 2014 in Berlin
d3sparql.js demo at SWAT4LS 2014 in Berlind3sparql.js demo at SWAT4LS 2014 in Berlin
d3sparql.js demo at SWAT4LS 2014 in Berlin
 
Starting with JSON Path Expressions in Oracle 12.1.0.2
Starting with JSON Path Expressions in Oracle 12.1.0.2Starting with JSON Path Expressions in Oracle 12.1.0.2
Starting with JSON Path Expressions in Oracle 12.1.0.2
 
Json at work overview and ecosystem-v2.0
Json at work   overview and ecosystem-v2.0Json at work   overview and ecosystem-v2.0
Json at work overview and ecosystem-v2.0
 
Validating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentationValidating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentation
 
Oracle Database - JSON and the In-Memory Database
Oracle Database - JSON and the In-Memory DatabaseOracle Database - JSON and the In-Memory Database
Oracle Database - JSON and the In-Memory Database
 
Open Source Search: An Analysis
Open Source Search: An AnalysisOpen Source Search: An Analysis
Open Source Search: An Analysis
 
Text processing by Rj
Text processing by RjText processing by Rj
Text processing by Rj
 
JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)
 
Spock and Geb
Spock and GebSpock and Geb
Spock and Geb
 
Oh, that ubiquitous JSON !
Oh, that ubiquitous JSON !Oh, that ubiquitous JSON !
Oh, that ubiquitous JSON !
 
Security Challenges in Node.js
Security Challenges in Node.jsSecurity Challenges in Node.js
Security Challenges in Node.js
 
Nodejs functional programming and schema validation lightning talk
Nodejs   functional programming and schema validation lightning talkNodejs   functional programming and schema validation lightning talk
Nodejs functional programming and schema validation lightning talk
 
Json
JsonJson
Json
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
 
Json
JsonJson
Json
 
UKOUG Tech14 - Getting Started With JSON in the Database
UKOUG Tech14 - Getting Started With JSON in the DatabaseUKOUG Tech14 - Getting Started With JSON in the Database
UKOUG Tech14 - Getting Started With JSON in the Database
 
Store non-structured data in JSON column types and enhancements of JSON
Store non-structured data in JSON column types and enhancements of JSONStore non-structured data in JSON column types and enhancements of JSON
Store non-structured data in JSON column types and enhancements of JSON
 
Basics of JSON (JavaScript Object Notation) with examples
Basics of JSON (JavaScript Object Notation) with examplesBasics of JSON (JavaScript Object Notation) with examples
Basics of JSON (JavaScript Object Notation) with examples
 

Recently uploaded

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 

Recently uploaded (20)

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 

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]}]