Our first program will demonstrate JSON encoding and decoding in Java. Here’s the full source code:
This program demonstrates JSON encoding and decoding using the Jackson library, which is a popular JSON library for Java.
First, we define two classes Response1 and Response2 to demonstrate encoding and decoding of custom types.
In the main method, we create an ObjectMapper instance, which is the main class for JSON processing in Jackson.
We then demonstrate encoding of basic data types (boolean, integer, float, string) to JSON strings using writeValueAsString().
Next, we show how to encode lists and maps to JSON arrays and objects.
We then encode custom objects (Response1 and Response2) to JSON.
For decoding, we first demonstrate how to decode a JSON string into a Map<String, Object>, which is similar to decoding into a generic data structure.
We also show how to access nested data in the decoded map.
Finally, we demonstrate decoding JSON directly into a custom Java class (Response2).
To run this program, you’ll need to include the Jackson library in your project. You can do this by adding the following dependency to your Maven pom.xml file:
Or if you’re using Gradle, add this to your build.gradle file:
After setting up the project with the Jackson library, you can compile and run the program:
This will output the JSON encodings and decodings demonstrated in the program.