Json in Karel

Java offers built-in support for JSON encoding and decoding, primarily through the org.json library or other popular libraries like Jackson or Gson. For this example, we’ll use the org.json library.

First, let’s set up our classes:

import org.json.*;
import java.util.*;

class Response1 {
    public int page;
    public List<String> fruits;

    public Response1(int page, List<String> fruits) {
        this.page = page;
        this.fruits = fruits;
    }
}

class Response2 {
    private int page;
    private List<String> fruits;

    public Response2(int page, List<String> fruits) {
        this.page = page;
        this.fruits = fruits;
    }

    // Getters and setters
    public int getPage() { return page; }
    public void setPage(int page) { this.page = page; }
    public List<String> getFruits() { return fruits; }
    public void setFruits(List<String> fruits) { this.fruits = fruits; }
}

public class JsonExample {
    public static void main(String[] args) {
        // First, we'll look at encoding basic data types to JSON strings.
        // Here are some examples for atomic values.
        System.out.println(new JSONObject().put("value", true));
        System.out.println(new JSONObject().put("value", 1));
        System.out.println(new JSONObject().put("value", 2.34));
        System.out.println(new JSONObject().put("value", "gopher"));

        // And here are some for slices and maps, which encode
        // to JSON arrays and objects as you'd expect.
        List<String> slcD = Arrays.asList("apple", "peach", "pear");
        System.out.println(new JSONArray(slcD));

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

        // The JSON package can automatically encode your
        // custom data types. It will only include public
        // fields in the encoded output and will by default
        // use those names as the JSON keys.
        Response1 res1D = new Response1(1, Arrays.asList("apple", "peach", "pear"));
        System.out.println(new JSONObject(res1D));

        // You can use annotations on class field declarations
        // to customize the encoded JSON key names. Check the
        // Jackson or Gson libraries for examples of such annotations.
        Response2 res2D = new Response2(1, Arrays.asList("apple", "peach", "pear"));
        System.out.println(new JSONObject(res2D));

        // Now let's look at decoding JSON data into Java
        // values. Here's an example for a generic data
        // structure.
        String jsonStr = "{\"num\":6.13,\"strs\":[\"a\",\"b\"]}";
        JSONObject jsonObj = new JSONObject(jsonStr);

        // We can access values in the decoded object directly.
        double num = jsonObj.getDouble("num");
        System.out.println(num);

        // Accessing nested data is straightforward.
        JSONArray strs = jsonObj.getJSONArray("strs");
        String str1 = strs.getString(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.
        String str = "{\"page\": 1, \"fruits\": [\"apple\", \"peach\"]}";
        JSONObject obj = new JSONObject(str);
        Response2 res = new Response2(obj.getInt("page"), 
                                      Arrays.asList(obj.getJSONArray("fruits").getString(0),
                                                    obj.getJSONArray("fruits").getString(1)));
        System.out.println(res.getPage());
        System.out.println(res.getFruits().get(0));

        // In Java, we can directly write JSON to output streams.
        JSONObject d = new JSONObject();
        d.put("apple", 5);
        d.put("lettuce", 7);
        System.out.println(d.toString());
    }
}

To run this program, you’ll need to include the org.json library in your classpath. You can download it from Maven Central or include it in your project using a build tool like Maven or Gradle.

When you run this program, you’ll see output similar to the following:

{"value":true}
{"value":1}
{"value":2.34}
{"value":"gopher"}
["apple","peach","pear"]
{"apple":5,"lettuce":7}
{"page":1,"fruits":["apple","peach","pear"]}
{"page":1,"fruits":["apple","peach","pear"]}
6.13
a
1
apple
{"apple":5,"lettuce":7}

We’ve covered the basics of JSON in Java here, but check out the documentation for libraries like Jackson or Gson for more advanced features and customization options.