Table of contents
1.
Introduction
2.
Mapping Java objects to JSON
3.
Handling a JSON request
4.
Serving a JSON response
5.
Frequently Asked Questions
5.1.
What is JSON used for in Java?
5.2.
How is JSON different from JavaScript?
5.3.
Why do we need JSON?
6.
Conclusion
Last Updated: Mar 27, 2024

Java developers- Working with JSON

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

JSON (JavaScript Object Notation) is a lightweight, text-based, language-independent data exchange format that is easy for machines and humans to write and read. JSON can represent two structured types: arrays and objects. An object is an unordered collection of zero or more values/name pairs. An array is an ordered sequence of zero or more values. The values can be numbers, strings, booleans, null, and these two structured types.

We can use the Jackson JSON library in Java to convert objects to and from JSON. Actions work with the JsonNode type, and the framework gives utility methods for conversion in the play.libs.Json API.

JSON AND JavaScript

JSON AND JavaScript

Mapping Java objects to JSON

Jackson helps you to easily convert Java objects to JSON by looking at getters, setters, and field names. As an, e.g., we will use the following simple Java object:

// Note: can use getters/setters as well; here we just use public fields directly.
// if using getters/setters, you can keep the fields `protected` or `private`
public static class Person {
  public String firstName;
  public String lastName;
  public int age;
}
You can also try this code with Online Java Compiler
Run Code

We can parse the JSON representation of the object to create a new Person:

Person person = new Person();
person.firstName = "Foo";
person.lastName = "Bar";
person.age = 30;
JsonNode personJson = Json.toJson(person); // {"firstName": "Foo", "lastName": "Bar", "age": 30}
Similarly, we can write the Person object to a JsonNode:
// parse the JSON as a JsonNode
JsonNode json = Json.parse("{\"firstName\":\"Foo\", \"lastName\":\"Bar\", \"age\":13}");
// read the JsonNode as a Person
Person person = Json.fromJson(json, Person.class);
You can also try this code with Online Java Compiler
Run Code

Handling a JSON request

A JSON request is an HTTP request with the help of a valid JSON payload as request body. Its Content-Type header must specify the json/text or application/json MIME type.

By default, an action uses any content body parser, which you can utilize to get the body as JSON :

public Result sayHello(Http.Request request) {
  JsonNode json = request.body().asJson();
  if (json == null) {
    return badRequest("Expecting Json data");
  } else {
    String name = json.findPath("name").textValue();
    if (name == null) {
      return badRequest("Missing parameter [name]");
    } else {
      return ok("Hello " + name);
    }
  }
}
public Result sayHello(Http.Request request) {
  Optional<Person> person = request.body().parseJson(Person.class);
  return person.map(p -> ok("Hello, " + p.firstName)).orElse(badRequest("Expecting Json data"));
}
You can also try this code with Online Java Compiler
Run Code

Of course, it is a  way simpler and better to specify our BodyParser to request Play to parse the content body directly as JSON:

@BodyParser.Of(BodyParser.Json.class)
public Result sayHello(Http.Request request) {
  JsonNode json = request.body().asJson();
  String name = json.findPath("name").textValue();
  if (name == null) {
    return badRequest("Missing parameter [name]");
  } else {
    return ok("Hello " + name);
  }
}
You can also try this code with Online Java Compiler
Run Code

You can test it with the help of curl from a CLI:

curl
  --header "Content-type: application/json"
  --request POST
  --data '{"name": "Guillaume"}'
  http://localhost:9000/sayHello
You can also try this code with Online Java Compiler
Run Code

It replies with:

HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Content-Length: 15


Hello Guillaume
You can also try this code with Online Java Compiler
Run Code

Serving a JSON response

We handled a JSON request in the previous example but replied with a plain/text response. Let us change that to send back a valid JSON HTTP response:

public Result sayHello() {
  ObjectNode result = Json.newObject();
  result.put("exampleField1", "foobar");
  result.put("exampleField2", "Hello world!");
  return ok(result);
}
You can also try this code with Online Java Compiler
Run Code

Now it replies with:

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8


{"exampleField1":"foobar","exampleField2":"Hello world!"}
You can also try this code with Online Java Compiler
Run Code

You can also return a Java object and have it automatically serialized to JSON by the Jackson library:

public Result getPeople() {
  List<Person> people = personDao.findAll();
  return ok(Json.toJson(people));
}
You can also try this code with Online Java Compiler
Run Code

Must Read Array of Objects in Java

Frequently Asked Questions

What is JSON used for in Java?

JSON (JavaScript Object Notation) is a  text-based, lightweight, language-independent data exchange format that is easy for machines and humans to read and write. JSON can represent two structured types: arrays and objects.

How is JSON different from JavaScript?

The last significant difference between JSON and JavaScript objects is their presentation. JSON is presented in a string. These are referred to as JSON strings. JavaScript objects can contain strings, but they are, as their name suggests, objects instead of strings.

Why do we need JSON?

The JSON format transmits and serializes structured data over network connections. It is primarily utilized to transmit data between a server and web applications. Web services and APIs use JSON format to provide public data. We can use it with modern programming languages.

Conclusion

I hope this article gave you insights into working with JSON for java developers.

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, System Design, Javascript, etc. Enroll in our courses, refer to the mock test and problems available, interview puzzles, and look at the interview bundle and interview experiences for placement preparations.

We hope this blog has helped you increase your knowledge regarding AWS Step functions, and if you liked this blog, check other links. Do upvote our blog to help other ninjas grow. Happy Coding!"

Live masterclass