From Java Object to JSON-P Type with "Pattern Matching for instanceof"

JEP 305: Pattern Matching for instanceof allows a more concise type conversion; the method javaToJson tests the type of the Java object and converts it to the corresponding JSON-P without casting:

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.List;
import jakarta.json.Json;
import jakarta.json.JsonValue;
import jakarta.json.JsonValue.ValueType;

public class PatternMatchingTest {

    JsonValue javaToJson(Object javaType){
        if (javaType instanceof String string) {
            return Json.createValue(string);
        } else if (javaType instanceof Integer integer) {
            return Json.createValue(integer);
        } else if (javaType instanceof Boolean bool) {
            return bool? JsonValue.TRUE : JsonValue.FALSE;
        return Json.createValue(javaType.toString());


Now a List of various Java types can be converted to the corresponding JSON-P (Jakarta JSON Processing) values:

public void instanceOfWithoutCasting() {
    var mix = List.of("duke",42,true);

    assertEquals(ValueType.STRING, javaToJson(mix.get(0)).getValueType());
    assertEquals(ValueType.NUMBER, javaToJson(mix.get(1)).getValueType());
    assertEquals(ValueType.TRUE, javaToJson(mix.get(2)).getValueType());


Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments