November 21, 2020

JSON-P in JavaEE 7

JSON-P can be used to parse and stringify JSON data.

        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>8.0</version>
            <scope>provided</scope>
        </dependency>

        <!-- JSON-P Impl -->
        <dependency>
            <groupId>org.glassfish</groupId>
            <artifactId>jakarta.json</artifactId>
            <version>1.1.6</version>
            <scope>test</scope>
        </dependency>
package se.magnuskkarlsson.example.javaee8_p6spy.control;

import java.io.StringReader;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.json.Json;
import javax.json.JsonObject;

import org.junit.Test;

public class JSONPTest {

    public static final String DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";

    @Test
    public void stringify() throws Exception {
        // https://javaee.github.io/jsonp/
        JsonObject json = Json.createObjectBuilder() //
                .add("name", "Falco") //
                // "JSON does not have a built-in type for date/time values. The general consensus is to store the
                // date/time value as a string in ISO 8601 format."
                // https://docs.jsonata.org/date-time#json-and-iso-8601
                .add("created", new SimpleDateFormat(DATETIME_FORMAT).format(new Date())) //
                .add("age", BigDecimal.valueOf(3)) //
                .add("emails", Json.createArrayBuilder() //
                        .add("foo@domain.com") //
                        .add("boo@domain.se")) //
                .add("biteable", Boolean.FALSE) //
                .build();
        String result = json.toString();

        System.out.println(result);
    }

    @Test
    public void parse() throws Exception {
        // https://javaee.github.io/jsonp/getting-started.html
        String json = "{\"name\":\"John Doe\",\"created\":\"2001-07-04T12:08:56.235-0700\",\"age\":28,\"bitable\":true}";
        JsonObject obj = Json.createReader(new StringReader(json)).readObject();
        System.out.println(obj);
        System.out.println(obj.getString("name"));
        System.out.println(obj.getString("created"));
        System.out.println(obj.getInt("age"));
        System.out.println(obj.getBoolean("bitable"));
    }

}

No comments: