Over

120,000

Worldwide

Saturday - Sunday CLOSED

Mon - Fri 8.00 - 18.00

Call us

 

Java JSON

Java JSON

JSON Java libraries / Jackson library

JSON stands for JavaScript Object Notation, which is easy to read and supports object, string, array, number and values. This is used for client-server communication and is language-independent.

The JSON Java library is also known as org.json, this provides us classed with which we parse and manipulate the JSON in Java. Some of them are:

JSONObject

JSONArray

JSONTokener

CDL (Comma Delimited List)

Cookie

HTTP

JSONException

JSONObject is a collection of key and value pairs, where the keys are unique Strings that cannot be null and values can be anything from Boolean, Number or even JSONObject.NULL object. By the JSONArray we can add and get elements using the put() and get() methods. JSONTokener gets the JSON as a String to its constructor and gets from there the characters and tokens. This is used by this package’s classes for parsing JSON Strings. It has a more() method to have an access to it as an iterator for checking there for remaining elements and next() method for accessing the next element.

With the CDL, which is Comma Delimited List, we convert comma delimited text into a JSONArray and vice versa.

Cookie is related with browser’s cookies and has methods for converting the cookies into a JSONObject and vice versa.

HTTP contains some static methods which are used for converting HTTP headers to JSONObject and vice versa.

JSONException is the standard exception that can be thrown by this package, when we have an error. This exception mainly has a message about its description.

Another library for Java JSON is the Jackson library. That is a Java JSON API and it has several ways to work with JSON. It is an efficient and popular library for serializing and mapping java objects to JSON and vice versa.

Jackson has two JSON parsers:

1. Jackson Object Mapper,

2. Jackson JSONParser.

And it has two JSON generators:

1. Jackson ObjectMapper,

2. Jackson JsonGenerator.

An example of Java Jackson ObjectMapper is below:

public class JacksonExample1 {

public static void main(String[] args) {

ObjectMapper objectMapper = new ObjectMapper();

String animalJson = “{ \”type\” : \”cat\”, \”age\” : 6 }”;

try {

Animal animal = objectMapper.readValue(foodJson, Animal.class);

System.out.println(“Animal type = ” + food.getType());

System.out.println(“Animal age = ” + food.getAge());

} catch (IOException e) {

e.printStackTrace();

}

}

}

class Animal {

private String type = null;

private int age = 0;

public String getType() {

return this.type;

}

public void setType(String type) {

this.type = type;

}

public int getAge() {

return this.age;

}

public void setAge(int age) {

this.age = age;

}

}

The readValue() method has two parameters: the source of the Json and the second is parsed the Animal class that we have.

A more complex example is given below:

public class JacksonExample2 {

public static void main(String[] args) {

String json = “{ \”name\”:\”Ann\”, \”position\”:\”BACKEND_DEVELOPER\”, \”skills\”:[ \”Java\”, \”Python\”, \”JavaScript\” ], \”address\”:{ \”street\”:\”MyStreet\”, \”streetNumber\”:\”32\” } }”; ObjectMapper objectMapper = new ObjectMapper();

Employee employee = objectMapper.readValue(json, Employee.class);

System.out.println(employee);

}

}

class Employee {

String name;

POSITION position;

List<String> skills;

Address address;

}

enum POSITION {

TEAM_LEAD, BACKEND_DEVELOPER, FRONTEND_DEVELOPER, QA_TESTER }

class Address {

String street;

String streetNo;

}

The employee we get will be:

Employee{name=’Ann’, position=BACKEND_DEVELOPER, skills=[Java, Python, JavaScript], address=Address{street=’MyStreet’, streetNo=’32’}}

As we see, in this example we have and object, which in its turn includes an Enum, a List and another object.

The ObjectMapper gives a functionality for reading and writing JSON, to and from basic Java objects or to and from general-purpose JSON Tree Model..

With using the Jackson, it will match properly to read the Java objects from JSON.

You can read and write JsonNode to JSON, for which we again need the Jackson, by calling readTree() on the ObjectMapper instance and passing the JSON source as a parameter. An example is given below:

String json = “{ \”fieldOne\” : \”valueOne\” } “;

ObjectMapper objectMapper = new ObjectMapper();

JsonNode jsonNode = objectMapper.readTree(json);

System.out.println(jsonNode.get(“fieldOne”).asText());

Another a more complex json string example is given below:

public class JacksonExample3 {

public static void main(String[] args) {

String jsonString = “{ \”name\” : \”Alice\”, \”age\” : 25,” +

\”skills\” : [\”Java\”, \”Go\”, \”Python\”],” +

\”nestedObject\” : { \”field\” : \”value\” } }”;

ObjectMapper objectMapper = new ObjectMapper();

try {

JsonNode node = objectMapper.readValue(jsonString, JsonNode.class); JsonNode nameNode = node.get(“name”);

String name = nameNode.asText();

System.out.println(name);

JsonNode ageNode = node.get(“age”);

int age = ageNode.asInt();

System.out.println(age);

JsonNode array = node.get(“skills”);

JsonNode jsonNode = array.get(1);

String techStr = jsonNode.asText();

System.out.println(techStr);

JsonNode child = node.get(“nestedObject”);

JsonNode insideField = child.get(“field”);

String field = insideField.asText();

System.out.println(field);

} catch (IOException e) {

e.printStackTrace();

}

}

}

The result for this will be:

Alice

25

Go

value

And for writing we can bring this simple example:

ObjectMapper objectMapper = new ObjectMapper();

JsonNode jsonNode = readJsonIntoJsonNode();

String json = objectMapper.writeValueAsString(jsonNode);

Another a more complex example for writing can be this:

public class JacksonExample3 {

ObjectMapper objectMapper = new ObjectMapper();

String carJson = “{ \”brand\” : \”BMW\”, \”doors\” : 4}”;

JsonNode carJsonNode = objectMapper.readTree(carJson);

Car car = objectMapper.treeToValue(carJsonNode);

}

class Car {

String brand;

int doors;

}

The Jackson JsonNode class has many methods that can convert a field value to another data type. For example, converting a String field value to long, or so on.

You can also use JsonParse for parsing the JSON. It is breaking JSON into sequence of tokens in which you can iterate.

Here you can see a simple example that iterates through the JSON tokens and prints them. Still if the parser is not closed, then it has a result and should print the tokens.

String animalJson = “{ \”type\” : \”cat\”, \”age\” : 6 }”;

JsonFactory factory = new JsonFactory();

JsonParser parser = factory.createParser(animalJson);

while (!parser.isClosed()) {

JsonToken jsonToken = parser.nextToken();

System.out.println(“JSON token – ” + jsonToken);

}

As a result we will get the tokens of the JsonParser and with JsonToken will inspect the token. In the JsonToken class the types are written as constants, by using which you know what type od token this JsonToken is. For this you should use equals() method of these constants.

String animalJson = “{ \”type\” : \”cat\”, \”age\” : 6 }”;

JsonFactory factory = new JsonFactory();

JsonParser parser = factory.createParser(carJson);

Animal animal = new Animal();

while (!parser.isClosed()) {

JsonToken jsonToken = parser.nextToken();

if (JsonToken.FIELD_NAME.equals(jsonToken)) {

String fieldName = parser.getCurrentName();

System.out.println(fieldName);

jsonToken = parser.nextToken();

if (“type”.equals(fieldName)) {

animal.getType() = parser.getValueAsString();

} else if (“age”.equals(fieldName)) {

animal.getAge() = parser.getValueAsInt();

}

}

}

System.out.println(“animal.type = ” + animal.type);

System.out.println(“animal.age = ” + animal.age);

We get the current fields name from the JsonParser’s method, get the current token value as a string and the current token value as an int. So, with JsonParser we can return many types of current token values.

The JsonFactory is the main factory class of Jackson package, which is used for configuring and  constructing reader and writer instances. Factory instances are thread-safe and they are reusable after any configuration.

Another Java Json API is GSON from Google, and from there the G comes for this. This is flexible but not so fast like Jackson. It has three Java JSON parsers:

1. GSON class

2. GSON JsonReader

3. GSON JsonParser

Boon is another Java JSON API and this is probably faster than those mentioned above. This is like Jackson and this is easier to use.

Previous

Leave a Reply

Your email address will not be published. Required fields are marked *

Working Hours

  • Monday 9am - 6pm
  • Tuesday 9am - 6pm
  • Wednesday 9am - 6pm
  • Thursday 9am - 6pm
  • Friday 9am - 6pm
  • Saturday Closed
  • Sunday Closed