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

Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 

Recently uploaded (20)

Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 

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