adam bien's blog

From javax.json.JsonObject To byte[] And Back 📎

Enjoy self-explanatory, Java EE 7 code :-):


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.json.JsonWriter;

//...
   JsonObject deserialize(byte[] content) throws IOException {
        try (ByteArrayInputStream bais = new ByteArrayInputStream(content);
             JsonReader reader = Json.createReader(bais)) {
            return reader.readObject();
        }
    }

  byte[] serialize(JsonObject object) throws IOException {
        try (ByteArrayOutputStream oos = new ByteArrayOutputStream(); 
		     JsonWriter writer = Json.createWriter(oos)) {
            writer.writeObject(object);
            writer.close();
            oos.flush();
            return oos.toByteArray();
        }
    }


//...

    @Test
    public void reserialize() throws IOException {
        JsonObject expected = Json.createObjectBuilder().
                add("name", "duke").
                build();
        byte[] serialized = serialize(expected);
        JsonObject actual = deserialize(serialized);
        assertNotSame(actual, expected);
        assertThat(actual, is(expected));
    }

See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting