Json in Cilk

Java provides built-in support for JSON encoding and decoding through libraries like Jackson or Gson. In this example, we’ll use Gson, which is a popular choice for JSON processing in Java.

First, we’ll need to include the Gson library in our project. If you’re using Maven, add this dependency to your pom.xml:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.9</version>
</dependency>

Now, let’s look at the Java code:

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class JsonExample {

    // We'll use these two classes to demonstrate encoding and
    // decoding of custom types below.
    static class Response1 {
        int page;
        String[] fruits;

        public Response1(int page, String[] fruits) {
            this.page = page;
            this.fruits = fruits;
        }
    }

    // In Java, we use annotations to customize the JSON key names
    static class Response2 {
        @SerializedName("page")
        int page;
        @SerializedName("fruits")
        String[] fruits;

        public Response2(int page, String[] fruits) {
            this.page = page;
            this.fruits = fruits;
        }
    }

    public static void main(String[] args) {
        Gson gson = new Gson();

        // First we'll look at encoding basic data types to
        // JSON strings. Here are some examples for atomic values.
        System.out.println(gson.toJson(true));
        System.out.println(gson.toJson(1));
        System.out.println(gson.toJson(2.34));
        System.out.println(gson.toJson("gopher"));

        // And here are some for slices and maps, which encode
        // to JSON arrays and objects as you'd expect.
        String[] slcD = {"apple", "peach", "pear"};
        System.out.println(gson.toJson(slcD));

        Map<String, Integer> mapD = new HashMap<>();
        mapD.put("apple", 5);
        mapD.put("lettuce", 7);
        System.out.println(gson.toJson(mapD));

        // The Gson library can automatically encode your
        // custom data types.
        Response1 res1D = new Response1(1, new String[]{"apple", "peach", "pear"});
        System.out.println(gson.toJson(res1D));

        // You can use annotations on class fields
        // to customize the encoded JSON key names. Check the
        // definition of `Response2` above to see an example
        // of such annotations.
        Response2 res2D = new Response2(1, new String[]{"apple", "peach", "pear"});
        System.out.println(gson.toJson(res2D));

        // Now let's look at decoding JSON data into Java
        // objects. Here's an example for a generic data
        // structure.
        String byt = "{\"num\":6.13,\"strs\":[\"a\",\"b\"]}";

        // We need to provide a Type where Gson
        // can put the decoded data. This
        // Map<String, Object> will hold a map of strings
        // to arbitrary data types.
        Map<String, Object> dat = gson.fromJson(byt, new TypeToken<Map<String, Object>>(){}.getType());
        System.out.println(dat);

        // In order to use the values in the decoded map,
        // we'll need to cast them to their appropriate type.
        // For example here we cast the value in `num` to
        // the expected `Double` type.
        Double num = (Double) dat.get("num");
        System.out.println(num);

        // Accessing nested data requires a series of
        // casts.
        String[] strs = gson.fromJson(gson.toJson(dat.get("strs")), String[].class);
        String str1 = strs[0];
        System.out.println(str1);

        // We can also decode JSON into custom data types.
        // This has the advantages of adding additional
        // type-safety to our programs and eliminating the
        // need for type assertions when accessing the decoded
        // data.
        String str = "{\"page\": 1, \"fruits\": [\"apple\", \"peach\"]}";
        Response2 res = gson.fromJson(str, Response2.class);
        System.out.println(res.page);
        System.out.println(res.fruits[0]);

        // In the examples above we always used strings as
        // intermediates between the data and JSON representation.
        // We can also write JSON encodings directly to any
        // object that implements `java.io.Writer`, like
        // `java.io.FileWriter` or even HTTP response bodies.
        Map<String, Integer> d = new HashMap<>();
        d.put("apple", 5);
        d.put("lettuce", 7);
        gson.toJson(d, System.out);
    }
}

This Java code demonstrates JSON encoding and decoding using the Gson library, which is similar to Go’s built-in encoding/json package. It covers encoding basic data types, custom objects, and decoding JSON into both generic and custom data structures.

To run this program, make sure you have the Gson library in your classpath, compile the Java file, and then run it:

$ javac -cp gson-2.8.9.jar JsonExample.java
$ java -cp .:gson-2.8.9.jar JsonExample

This will output the JSON representations and decoded data, similar to the Go example.

Remember to handle potential exceptions that may occur during JSON processing in a production environment.