adam bien's blog

Java 16: Converting a JSON array to Java types with Pattern Matching 📎

A JSON array, containing a JSON string and a number, loaded with JSON-P:

import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonNumber;
import javax.json.JsonString;
import javax.json.JsonValue;    

JsonArray load() {
    var jsonArray = """
                    ["hello,duke",42]
                    """;
    return Json.createReader(new StringReader(jsonArray)).readArray();
}

...can be converted to Java data types with the Java 16+ (JEP 394: Pattern Matching for instanceof) without any casting:

Object convert(JsonValue value) {
    if (value instanceof JsonNumber n) {
        return n.intValue();
    }
    if (value instanceof JsonString s) {
        return s.getString();
    }
    return value.toString();
}

The output of the following method:


@Test
public void jsonToJava() {
    var jsonArray = this.load();
    var javaList = jsonArray.stream().map(this::convert).toList();
    System.out.println(javaList);

}

yields: [hello,duke, 42]

See it in action (5 mins):