Json
Json
JSON PARSER
Jackson JSON
TUTORIAL
Small Codes
Programming Simplified
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or
transmitted in any form or by any means, without the prior written permission of the
publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the
information presented. However, the information contained in this book is sold without
warranty, either express or implied. Neither the author, SmlCodes.com, nor its dealers or
distributors will be held liable for any damages caused or alleged to be caused directly or
indirectly by this book.
Smlcodes.com has endeavored to provide trademark information about all the companies
and products mentioned in this book by the appropriate use of capitals. However,
SmlCodes.com Publishing cannot guarantee the accuracy of this information.
If you discover any errors on our website or in this tutorial, please notify us at
[email protected] or [email protected]
Author Credits
Name : Satya Kaveti
Email : [email protected]
Digital Partners
2|P A G E
......................................................................................................................................................................................... 1
JSON PARSER TUTORIAL ............................................................................................................................................................ 1
JACKSON JSON TUTORIAL ................................................................................................................................................................ 1
3|P A G E
Jackson Json Tutorial
Jackson is a very popular and efficient Java-based library to serialize or map Java objects to JSON and vice
versa. We have following other JSON Parsers in java like
Jackson
GSON
Boon
JSON.org
JSONP
To use Jackson JSON Java API in our project, we can add it to the project build path or if you are using
maven, we can add below dependency. Or you can download directly from here.
1. Data Binding It reads and writes JSON content as discrete events. JsonParser reads the data,
whereas JsonGenerator writes the data.
2. Tree Model It prepares an in-memory tree representation of the JSON document. ObjectMapper
build tree of JsonNode nodes. It is most flexible approach. It is analogous to DOM parser for XML.
3. Streaming API It converts JSON to and from Plain Old Java Object (POJO) using property accessor or
using annotations. ObjectMapper reads/writes JSON for both types of data bindings. Data binding is
analogous to JAXB parser for XML
4|P A G E
Example : convert Java object to JSON
It will do 3 things here
1. Read JSON File location
2. Convert Java Object to JSON String
3. Convert JSON String to JSON data & Save in .json file
import java.util.List;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.codehaus.jackson.map.ObjectMapper;
try{
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("D:\\JavaToJSON.json"), studentBo);
5|P A G E
String jsonInString = mapper.writeValueAsString(studentBo);
System.out.println("Converted object to JSON string \n"+jsonInString);
3. After Running the programe we get following Output. & file will store in given location
Converted object to JSON string
{"id":101,"name":"Satya Kaveti","address":["D.No:3-100","NEAR RAMALAYAM","VIJAYAWADA","PINCODE:520007"]}
JSON :
{
"id" : 101,
"name" : "Satya Kaveti",
"address" : [ "D.No:3-100", "NEAR RAMALAYAM", "VIJAYAWADA", "PINCODE:520007" ]
}
JAVA TO JSON COMPLETED !!
package databinding;
import java.io.File;
import org.codehaus.jackson.map.ObjectMapper;
try {
// Convert JSON string from file to Object
StudentBo StudentBo = mapper.readValue(new
File("C:\\Users\\kaveti_s\\Desktop\\JSONFIles\\JavaToJSON.json"),
StudentBo.class);
System.out.println(StudentBo.getId());
System.out.println(StudentBo.getName());
System.out.println(StudentBo.getAddress());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output
101
Satya Kaveti
[D.No:3-100, NEAR RAMALAYAM, VIJAYAWADA, PINCODE:520007]
6|P A G E
2. Tree Model Way
We can use Tree Model to represent JSON, and perform the read and write operations via JsonNode,
it is similar to an XML DOM tree.
Using Jackson TreeModel (JsonNode) to parse and traversal above JSON file
package treemodel;
import java.io.File;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
long id;
String firstName = "";
String middleName = "";
String lastName = "";
// Get id
id = root.path("id").asLong();
System.out.println("id : " + id);
// Get Name
JsonNode nameNode = root.path("name");
if (nameNode.isMissingNode()) {
// if "name" node is missing
} else {
firstName = nameNode.path("first").asText();
// missing node, just return empty string
middleName = nameNode.path("middle").asText();
lastName = nameNode.path("last").asText();
// Get Contact
JsonNode contactNode = root.path("contact");
if (contactNode.isArray()) {
7|P A G E
// If this node an Arrray?
}
} catch (Exception e) {
e.printStackTrace();
}
}
Output
id : 1
firstName : Satya
middleName :
lastName : Kaveti
type : phone/home
ref : 040-2581859
type : phone/work
ref : 7893640870
3. Streaming API
Jackson supports read and write JSON via high-performance Jackson Streaming APIs, or incremental
mode. Read this Jackson Streaming APIs document for detail explanation on the benefit of using
streaming API.
Jacksons streaming processing is high-performance, fast and convenient, but its also difficult to use,
because you need to handle each and every detail of JSON data.
In this tutorial, we show you how to use following Jackson streaming APIs to read and write JSON data.
1. JsonGenerator Example
In this example, you use JsonGenerator to write JSON field name, values and array of values
into a file name skill.json. See code comments for self-explanatory.
package streamingapi;
import java.io.File;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
jGenerator.writeFieldName("skills"); // "skills" :
jGenerator.writeStartArray(); // [
jGenerator.writeString("JAVA"); // "JAVA"
jGenerator.writeString("Struts"); // "Struts"
jGenerator.writeString("Springs"); // "Springs"
jGenerator.writeEndArray(); // ]
jGenerator.writeEndObject(); // }
jGenerator.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
2. JsonParser Example
JsonParser is used to parse or read above file skill.json, and display each of the values.
In streaming mode, every JSON string is consider as a single token, and each tokens will be processed
incremental, that why we call it incremental mode. For example,
{
"name":"Satya"
}
1. Token 1 = {
2. Token 2 = name
3. Token 3 = mkyong
4. Token 4 = }
9|P A G E
package streamingapi;
import java.io.File;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
try {
if ("age".equals(fieldname)) {
if ("messages".equals(fieldname)) {
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output
Satya
27
10 | P A G E