javax.json.bind.JsonbBuilder Java Examples
The following examples show how to use
javax.json.bind.JsonbBuilder.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JmsMessageReader.java From blog-tutorials with MIT License | 6 votes |
@Override public void onMessage(Message message) { TextMessage textMessage = (TextMessage) message; try { String incomingText = textMessage.getText(); System.out.println("-- a new message arrived: " + incomingText); Jsonb jsonb = JsonbBuilder.create(); CustomMessage parsedMessage = jsonb.fromJson(incomingText, CustomMessage.class); entityManager.persist(parsedMessage); } catch (JMSException e) { System.err.println(e.getMessage()); } }
Example #2
Source File: JsonComponentsTest.java From camel-quarkus with Apache License 2.0 | 6 votes |
@Test void jacksonXml() { final String xml = "<PojoA>\n <name>Joe</name>\n</PojoA>\n"; final String json = JsonbBuilder.create().toJson(new PojoA("Joe")); RestAssured.given() .contentType(ContentType.JSON) .body(json) .post("/dataformats-json/jacksonxml/marshal") .then() .statusCode(200) .body(equalTo(xml)); RestAssured.given() .contentType("text/xml") .body(xml) .post("/dataformats-json/jacksonxml/unmarshal") .then() .statusCode(200) .body(equalTo(json)); }
Example #3
Source File: JsonbUnitTest.java From tutorials with MIT License | 6 votes |
@Test public void givenPersonObject_whenWithPropertyOrderStrategy_thenGetReversePersonJson() { JsonbConfig config = new JsonbConfig().withPropertyOrderStrategy(PropertyOrderStrategy.REVERSE); Jsonb jsonb = JsonbBuilder.create(config); Person person = new Person(1, "Jhon", "[email protected]", 20, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000)); String jsonPerson = jsonb.toJson(person); // @formatter:off String jsonExpected = "{\"salary\":\"1000.0\","+ "\"registeredDate\":\"07-09-2019\"," + "\"person-name\":\"Jhon\"," + "\"id\":1," + "\"email\":\"[email protected]\"}"; // @formatter:on assertTrue(jsonExpected.equals(jsonPerson)); }
Example #4
Source File: JoinInputFactory.java From component-runtime with Apache License 2.0 | 6 votes |
private Object map(final Object next) { if (next == null || Record.class.isInstance(next)) { // directly ok return next; } if (String.class.isInstance(next) || next.getClass().isPrimitive()) { // primitives return next; } if (jsonb == null) { synchronized (this) { if (jsonb == null) { jsonb = JsonbBuilder.create(new JsonbConfig().setProperty("johnzon.cdi.activated", false)); registry = new RecordConverters.MappingMetaRegistry(); } } } return new RecordConverters() .toRecord(registry, next, () -> jsonb, () -> ComponentManager.instance().getRecordBuilderFactoryProvider().apply(null)); }
Example #5
Source File: DefaultServiceProvider.java From component-runtime with Apache License 2.0 | 6 votes |
private JsonbBuilder createPojoJsonbBuilder(final String id, final Supplier<Jsonb> jsonb) { final JsonbBuilder jsonbBuilder = JsonbBuilder .newBuilder() .withProvider(new PreComputedJsonpProvider(id, jsonpProvider, jsonpParserFactory, jsonpWriterFactory, jsonpBuilderFactory, new RecordJsonGenerator.Factory(Lazy.lazy(() -> recordBuilderFactoryProvider.apply(id)), jsonb, emptyMap()), jsonpReaderFactory)) .withConfig(jsonbConfig); try { // to passthrough the writer, otherwise RecoderJsonGenerator is broken final Field mapper = jsonbBuilder.getClass().getDeclaredField("builder"); if (!mapper.isAccessible()) { mapper.setAccessible(true); } MapperBuilder.class.cast(mapper.get(jsonbBuilder)).setDoCloseOnStreams(true); } catch (final Exception e) { throw new IllegalStateException(e); } return jsonbBuilder; }
Example #6
Source File: RecordConvertersTest.java From component-runtime with Apache License 2.0 | 6 votes |
@Test void convertListObject(final JsonBuilderFactory jsonBuilderFactory, final JsonProvider jsonProvider, final RecordBuilderFactory recordBuilderFactory, final RecordConverters converter) throws Exception { try (final Jsonb jsonb = JsonbBuilder.create()) { final Record record = converter .toRecord(new RecordConverters.MappingMetaRegistry(), Json .createObjectBuilder() .add("list", Json .createArrayBuilder() .add(Json.createObjectBuilder().add("name", "a").build()) .add(Json.createObjectBuilder().add("name", "b").build()) .build()) .build(), () -> jsonb, () -> new RecordBuilderFactoryImpl("test")); final Collection<Record> list = record.getArray(Record.class, "list"); assertEquals(asList("a", "b"), list.stream().map(it -> it.getString("name")).collect(toList())); } }
Example #7
Source File: JsonbUnitTest.java From tutorials with MIT License | 6 votes |
@Test public void givenPersonObject_whenNamingStrategy_thenGetCustomPersonJson() { JsonbConfig config = new JsonbConfig().withPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CASE_WITH_UNDERSCORES); Jsonb jsonb = JsonbBuilder.create(config); Person person = new Person(1, "Jhon", "[email protected]", 20, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000)); String jsonPerson = jsonb.toJson(person); // @formatter:off String jsonExpected = "{\"email\":\"[email protected]\"," + "\"id\":1," + "\"person-name\":\"Jhon\"," + "\"registered_date\":\"07-09-2019\"," + "\"salary\":\"1000.0\"}"; // @formatter:on assertTrue(jsonExpected.equals(jsonPerson)); }
Example #8
Source File: PluralRecordExtension.java From component-runtime with Apache License 2.0 | 6 votes |
private Jsonb createPojoJsonb() { final JsonbBuilder jsonbBuilder = JsonbBuilder.newBuilder().withProvider(new JsonProviderImpl() { @Override public JsonGeneratorFactory createGeneratorFactory(final Map<String, ?> config) { return new RecordJsonGenerator.Factory(() -> new RecordBuilderFactoryImpl("test"), () -> getJsonb(createPojoJsonb()), config); } }); try { // to passthrough the writer, otherwise RecoderJsonGenerator is broken final Field mapper = jsonbBuilder.getClass().getDeclaredField("builder"); if (!mapper.isAccessible()) { mapper.setAccessible(true); } MapperBuilder.class.cast(mapper.get(jsonbBuilder)).setDoCloseOnStreams(true); } catch (final Exception e) { throw new IllegalStateException(e); } return jsonbBuilder.build(); }
Example #9
Source File: SysConfigBean.java From javaee8-cookbook with Apache License 2.0 | 6 votes |
public String getSysConfig() throws SQLException, NamingException, Exception { String sql = "SELECT variable, value FROM sys_config"; try (Connection conn = ConnectionPool.getConnection(); PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery(); Jsonb jsonb = JsonbBuilder.create()) { List<SysConfig> list = new ArrayList<>(); while (rs.next()) { list.add(new SysConfig(rs.getString("variable"), rs.getString("value"))); } String json = jsonb.toJson(list); return json; } }
Example #10
Source File: RecordConvertersTest.java From component-runtime with Apache License 2.0 | 6 votes |
@Test void stringRoundTrip(final JsonBuilderFactory jsonBuilderFactory, final JsonProvider jsonProvider, final RecordBuilderFactory recordBuilderFactory, final RecordConverters converter) throws Exception { final Record record = recordBuilderFactory.newRecordBuilder().withString("value", "yes").build(); try (final Jsonb jsonb = JsonbBuilder.create()) { final JsonObject json = JsonObject.class .cast(converter .toType(new RecordConverters.MappingMetaRegistry(), record, JsonObject.class, () -> jsonBuilderFactory, () -> jsonProvider, () -> jsonb, () -> recordBuilderFactory)); assertEquals("yes", json.getString("value")); final Record toRecord = converter .toRecord(new RecordConverters.MappingMetaRegistry(), json, () -> jsonb, () -> recordBuilderFactory); assertEquals("yes", toRecord.getString("value")); } }
Example #11
Source File: ExampleResource.java From example-health-jee-openshift with Apache License 2.0 | 6 votes |
@GET @Path("/v1/appointments/list/{patId}") @Produces(MediaType.APPLICATION_JSON) public Response appointments(@PathParam("patId") String patId) { List<AppointmentList> results = entityManager.createNamedQuery("Appointment.getAppointments", AppointmentList.class) .setParameter("pid", patId) .getResultList(); Jsonb jsonb = JsonbBuilder.create(); String appointmentBlob = "{\"ResultSet Output\": " + jsonb.toJson(results) + ", \"StatusCode\": 200, \n \"StatusDescription\": \"Execution Successful\"}"; int returnCode = 0; if (results.size() == 0) { returnCode=1; } logger.info("Appointment blob: " + appointmentBlob); JsonReader jsonReader = Json.createReader(new StringReader(appointmentBlob)); JsonObject jresponse = jsonReader.readObject(); jsonReader.close(); return Response.ok(jresponse).build(); }
Example #12
Source File: JavaxJsonbTest.java From thorntail with Apache License 2.0 | 6 votes |
@Test @RunAsClient public void testJavaxJsonb() throws IOException { Dog dog = new Dog(); dog.name = "Falco"; dog.age = 4; dog.bitable = false; Jsonb jsonb = JsonbBuilder.create(); String json = jsonb.toJson(dog); String response = Request.Post("http://localhost:8080/").body(new StringEntity(json)) .execute().returnContent().asString().trim(); Dog dog2 = jsonb.fromJson(response, Dog.class); assertThat(dog2.name).isEqualTo(dog.name); assertThat(dog2.age).isEqualTo(dog.age); assertThat(dog2.bitable).isTrue(); }
Example #13
Source File: PropertiesConverterTest.java From component-runtime with Apache License 2.0 | 6 votes |
@Test void datalistDefault() throws Exception { final Map<String, Object> values = new HashMap<>(); try (final Jsonb jsonb = JsonbBuilder.create()) { new PropertiesConverter(jsonb, values, emptyList()) .convert(completedFuture(new PropertyContext<>(new SimplePropertyDefinition("configuration.foo.bar", "bar", "Bar", "STRING", "def", new PropertyValidation(), singletonMap("action::suggestionS", "yes"), null, new LinkedHashMap<>()), null, new PropertyContext.Configuration()))) .toCompletableFuture() .get(); } assertEquals(2, values.size()); assertEquals("def", values.get("bar")); assertEquals("def", values.get("$bar_name")); }
Example #14
Source File: MagazineSerializerTest.java From Java-EE-8-Sampler with MIT License | 6 votes |
@Test public void givenSerialize_shouldSerialiseMagazine() { Magazine magazine = new Magazine(); magazine.setId("1234-QWERT"); magazine.setTitle("Fun with Java"); magazine.setAuthor(new Author("Alex","Theedom")); String expectedJson = "{\"name\":{\"firstName\":\"Alex\",\"lastName\":\"Theedom\"}}"; JsonbConfig config = new JsonbConfig().withSerializers(new MagazineSerializer()); Jsonb jsonb = JsonbBuilder.newBuilder().withConfig(config).build(); String actualJson = jsonb.toJson(magazine); assertThat(actualJson).isEqualTo(expectedJson); }
Example #15
Source File: CustomiseJsonbNillableTest.java From Java-EE-8-Sampler with MIT License | 5 votes |
@Test public void givenJsonbNillableAtClass_shouldPreserveNullsOnDeserialisation() { String json = "{\"author\":null,\"id\":\"ABC-123-XYZ\",\"title\":\"Fun with JSON-B\"}"; Book actualBook = JsonbBuilder.create().fromJson(json, Book.class); assertThat(actualBook.getAuthor()).isNull(); assertThat(actualBook.getId()).isEqualTo("ABC-123-XYZ"); assertThat(actualBook.getTitle()).isEqualTo("Fun with JSON-B"); }
Example #16
Source File: JsonbUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void givenPersonJson_whenDeserializeWithAdapter_thenGetPersonObject() { JsonbConfig config = new JsonbConfig().withAdapters(new PersonAdapter()); Jsonb jsonb = JsonbBuilder.create(config); Person person = new Person(1, "Jhon", "[email protected]", 0, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000.0));// new Person(1, "Jhon"); // @formatter:off String jsonPerson = "{\"id\":1," + "\"name\":\"Jhon\"}"; // @formatter:on assertTrue(jsonb.fromJson(jsonPerson, Person.class) .equals(person)); }
Example #17
Source File: RecordConvertersTest.java From component-runtime with Apache License 2.0 | 5 votes |
@Test void studioTypes(final JsonBuilderFactory jsonBuilderFactory, final JsonProvider jsonProvider, final RecordBuilderFactory recordBuilderFactory, final RecordConverters converter) throws Exception { final SimpleRowStruct record = new SimpleRowStruct(); record.character = 'a'; record.character2 = 'a'; record.notLong = 100; record.notLong2 = 100; record.binary = 100; record.binary2 = 100; record.bd = BigDecimal.TEN; record.today = new Date(0); try (final Jsonb jsonb = JsonbBuilder .create(new JsonbConfig().withPropertyOrderStrategy(PropertyOrderStrategy.LEXICOGRAPHICAL))) { final Record recordModel = Record.class .cast(converter .toType(new RecordConverters.MappingMetaRegistry(), record, Record.class, () -> jsonBuilderFactory, () -> jsonProvider, () -> jsonb, () -> recordBuilderFactory)); assertEquals( "{\"bd\":10.0,\"binary\":100.0,\"binary2\":100.0," + "\"character\":\"a\",\"character2\":\"a\"," + "\"notLong\":100.0,\"notLong2\":100.0," + "\"today\":\"1970-01-01T00:00:00Z[UTC]\"}", recordModel.toString()); final SimpleRowStruct deserialized = SimpleRowStruct.class .cast(converter .toType(new RecordConverters.MappingMetaRegistry(), recordModel, SimpleRowStruct.class, () -> jsonBuilderFactory, () -> jsonProvider, () -> jsonb, () -> recordBuilderFactory)); if (record.bd.doubleValue() == deserialized.bd.doubleValue()) { // equals fails on this one deserialized.bd = record.bd; } assertEquals(record, deserialized); } }
Example #18
Source File: HealthCheckServlet.java From hammock with Apache License 2.0 | 5 votes |
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Jsonb jsonb = JsonbBuilder.newBuilder().build(); HealthCheckModel healthCheckModel = healthCheckManager.performHealthChecks(); if (healthCheckModel.getOutcome().equalsIgnoreCase(HealthCheckResponse.State.UP.name())) { resp.setStatus(200); } else { resp.setStatus(503); } jsonb.toJson(healthCheckModel, resp.getOutputStream()); }
Example #19
Source File: CustomiseJsonbNillableTest.java From Java-EE-8-Sampler with MIT License | 5 votes |
@Test public void givenJsonbPropertyNillableIdTrue_shouldPreserveNullsOnDeserialisation() { String json = "{\"authorName\":null,\"title\":\"Fun with JSON binding\"}"; Magazine actualMagazine = JsonbBuilder.create().fromJson(json, Magazine.class); assertThat(actualMagazine.getAuthorName()).isNull(); assertThat(actualMagazine.getAlternativeTitle()).isNull(); assertThat(actualMagazine.getTitle()).isEqualTo("Fun with JSON binding"); }
Example #20
Source File: JsonbTest.java From dsl-json with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test public void checkSimple() { SimpleClass sc = new SimpleClass(); sc.x = 12; sc.setY("abc"); Jsonb jsonb = JsonbBuilder.create(); String json = jsonb.toJson(sc); SimpleClass sc2 = jsonb.fromJson(json, SimpleClass.class); Assert.assertEquals(sc.x, sc2.x); Assert.assertEquals(sc.getY(), sc2.getY()); }
Example #21
Source File: WebsocketEndpoint.java From Hands-On-Cloud-Native-Applications-with-Java-and-Quarkus with MIT License | 5 votes |
@OnMessage public List<Customer> addCustomer(String message, Session session) { Jsonb jsonb = JsonbBuilder.create(); Customer customer = jsonb.fromJson(message, Customer.class); customerRepository.createCustomer(customer); return customerRepository.findAll(); }
Example #22
Source File: JsonbServlet.java From thorntail with Apache License 2.0 | 5 votes |
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Jsonb jsonb = JsonbBuilder.create(); Dog dog = jsonb.fromJson(req.getInputStream(), Dog.class); if (!dog.bitable) { dog.bitable = true; } resp.getWriter().print(jsonb.toJson(dog)); }
Example #23
Source File: JsonbProducer.java From quarkus with Apache License 2.0 | 5 votes |
static Jsonb get() { Jsonb jsonb = null; ArcContainer container = Arc.container(); if (container != null) { jsonb = container.instance(Jsonb.class).get(); } return jsonb != null ? jsonb : JsonbBuilder.create(); }
Example #24
Source File: PanacheFunctionalityTest.java From quarkus with Apache License 2.0 | 5 votes |
/** * This test is disabled in native mode as there is no interaction with the quarkus integration test endpoint. */ @DisabledOnNativeImage @Test public void jsonbDeserializationHasAllFields() throws JsonProcessingException { // set Up Person person = new Person(); person.name = "max"; // do Jsonb jsonb = JsonbBuilder.create(); String json = jsonb.toJson(person); assertEquals( "{\"dogs\":[],\"name\":\"max\",\"serialisationTrick\":1}", json); }
Example #25
Source File: CustomCreatorTest.java From Java-EE-8-Sampler with MIT License | 5 votes |
@Test public void givenCustomCreatorFactoryMethod_shouldUseCustomCreator() { String json = "{\"author\":\"Alex Theedom\",\"title\":\"Fun with JSON-B\",\"id\":\"ABC-123-XYZ\"}"; Book book = JsonbBuilder.create().fromJson(json, Book.class); assertThat(book.getId()).isEqualTo("ABC-123-XYZ"); assertThat(book.getTitle()).isEqualTo("Fun with JSON-B"); assertThat(book.getAuthor()).isEqualTo("Alex Theedom"); }
Example #26
Source File: CustomisePropertyOrderStrategyTest.java From Java-EE-8-Sampler with MIT License | 5 votes |
@Test public void givenANYPropertyOrderStrategy_shouldOrderLexicographically(){ String expectedJson = "{\"authorName\":{\"firstName\":\"Alex\",\"lastName\":\"Theedom\"},\"alternativeTitle\":\"01846537\",\"title\":\"Fun with JSON binding\"}"; JsonbConfig jsonbConfig = new JsonbConfig() .withPropertyOrderStrategy(PropertyOrderStrategy.ANY); String actualJson = JsonbBuilder.create(jsonbConfig).toJson(magazine); assertThat(actualJson).isEqualTo(expectedJson); }
Example #27
Source File: UiSchemaConverterTest.java From component-runtime with Apache License 2.0 | 5 votes |
@Test void listOfObject() throws Exception { final List<SimplePropertyDefinition> properties = asList( new SimplePropertyDefinition("configuration", "configuration", "configuration", "OBJECT", null, NVAL, emptyMap(), null, NPROPS), new SimplePropertyDefinition("configuration.list", "list", "list", "ARRAY", null, NVAL, emptyMap(), null, NPROPS), new SimplePropertyDefinition("configuration.list[].name", "name", "name", "STRING", null, NVAL, emptyMap(), null, NPROPS)); final PropertyContext<Object> propertyContext = new PropertyContext<>(properties.iterator().next(), null, new PropertyContext.Configuration(false)); final List<UiSchema> schemas = new ArrayList<>(); try (final Jsonb jsonb = JsonbBuilder.create()) { final JsonSchema jsonSchema = new JsonSchema(); new JsonSchemaConverter(jsonb, jsonSchema, properties) .convert(completedFuture(propertyContext)) .toCompletableFuture() .get(); new UiSchemaConverter(null, "test", schemas, properties, null, jsonSchema, properties, emptyList(), "en", emptyList(), new AtomicInteger(1)) .convert(completedFuture(propertyContext)) .toCompletableFuture() .get(); } assertEquals(1, schemas.size()); final UiSchema configuration = schemas.iterator().next(); assertNull(configuration.getKey()); assertEquals(1, configuration.getItems().size()); final UiSchema list = configuration.getItems().iterator().next(); assertEquals("configuration.list", list.getKey()); assertEquals("collapsibleFieldset", list.getItemWidget()); assertEquals(1, list.getItems().size()); final UiSchema name = list.getItems().iterator().next(); assertEquals("configuration.list[].name", name.getKey()); assertEquals("text", name.getWidget()); }
Example #28
Source File: CustomiseJsonbNillableTest.java From Java-EE-8-Sampler with MIT License | 5 votes |
@Test public void givenJsonbNillableAtClass_shouldPreserveNullsOnSerialisation() { String expectedJson = "{\"author\":null,\"id\":\"ABC-123-XYZ\",\"title\":\"Fun with JSON-B\"}"; Book book = new Book("ABC-123-XYZ", "Fun with JSON-B", null); String actualJson = JsonbBuilder.create().toJson(book); assertThat(actualJson).isEqualTo(expectedJson); }
Example #29
Source File: JsonDemo.java From Java-EE-8-and-Angular with MIT License | 5 votes |
private void jsonB() { Jsonb jsonb = JsonbBuilder.create(); Issue newIssue = jsonb.fromJson("{\"id\":1123,\"name\":\"Implement feature X\",\"priority\":\"High\"}", Issue.class); System.out.println("JSON-B Issue: "+ newIssue); JsonbConfig config = new JsonbConfig().withFormatting(true); Jsonb jsonbFormatted = JsonbBuilder.create(config); System.out.println("JSON-B formatted output: " + jsonbFormatted.toJson(newIssue)); }
Example #30
Source File: JobImpl.java From component-runtime with Apache License 2.0 | 5 votes |
private Supplier<Jsonb> jsonb() { return () -> { if (jsonb == null) { synchronized (this) { if (jsonb == null) { jsonb = JsonbBuilder.create(new JsonbConfig().setProperty("johnzon.cdi.activated", false)); } } } return jsonb; }; }