/** * Method handling HTTP GET requests. The returned object will be sent * to the client as "text/plain" media type. * * @return String that will be returned as a text/plain response. */ @GET @Produces(MediaType.APPLICATION_JSON) public String getIt() { JsonbConfig config = new JsonbConfig(); config.withAdapters(new EntityAdapter()); Jsonb jsonb = JsonbBuilder.create(config); CEntity entity = new EntityImpl("urn:c3im:Vehicle:4567", "Vehicle"); CProperty propertySt = new CPropertyImpl("speed", 40); entity.addProperty(propertySt); return jsonb.toJson(entity); }
@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); }
@Override public byte[] serialize(final String topic, final CoffeeEvent event) { try { if (event == null) return null; final JsonbConfig config = new JsonbConfig() .withAdapters(new UUIDAdapter()) .withSerializers(new EventJsonbSerializer()); final Jsonb jsonb = JsonbBuilder.create(config); return jsonb.toJson(event, CoffeeEvent.class).getBytes(StandardCharsets.UTF_8); } catch (Exception e) { logger.severe("Could not serialize event: " + e.getMessage()); throw new SerializationException("Could not serialize event", e); } }
/** * accept = application/json * @param <T> * @param url * @param entity * @return ClientResponse * @throws java.io.IOException */ public static <T> T get(String url,Class<?> entity) throws IOException{ OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .header("Accept", "application/json") .get() .build(); Response response = client.newCall(request).execute(); client.dispatcher().executorService().shutdown(); if(response.code() == 200){ Jsonb jsonb = JsonbBuilder.create(); return (T) jsonb.fromJson(response.body().string(), entity); } return null; }
/** * accept = application/json * @param url * @return OrganizationDao * @throws java.io.IOException */ public static OrganizationDao getOrganization(String url) throws IOException { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .header("Accept", "application/json") .get() .build(); Response response = client.newCall(request).execute(); client.dispatcher().executorService().shutdown(); if(response.code() == 200){ Jsonb jsonb = JsonbBuilder.create(); return jsonb.fromJson(response.body().string(), OrganizationDao.class); } return null; }
public static DecisionTypeDetailsDao getDecisionTypeDetailsDao(String url) throws IOException { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .header("Accept", "application/json") .get() .build(); Response response = client.newCall(request).execute(); client.dispatcher().executorService().shutdown(); if(response.code() == 200){ Jsonb jsonb = JsonbBuilder.create(); return jsonb.fromJson(response.body().string(), DecisionTypeDetailsDao.class); } return null; }
public static DictionaryItemsDao getDictionaryItemsDao(String url) throws IOException { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .header("Accept", "application/json") .get() .build(); Response response = client.newCall(request).execute(); client.dispatcher().executorService().shutdown(); if(response.code() == 200){ Jsonb jsonb = JsonbBuilder.create(); return jsonb.fromJson(response.body().string(), DictionaryItemsDao.class); } return null; }
public static SignersDao getSignersDao(String url) throws IOException{ OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .header("Accept", "application/json") .get() .build(); Response response = client.newCall(request).execute(); client.dispatcher().executorService().shutdown(); if(response.code() == 200){ Jsonb jsonb = JsonbBuilder.create(); return jsonb.fromJson(response.body().string(), SignersDao.class); } return null; }
public static UnitsDao getUnitsDao(String url) throws IOException { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .header("Accept", "application/json") .get() .build(); Response response = client.newCall(request).execute(); client.dispatcher().executorService().shutdown(); if(response.code() == 200){ Jsonb jsonb = JsonbBuilder.create(); return jsonb.fromJson(response.body().string(), UnitsDao.class); } return null; }
public static DictionaryItemsDao getDictionaryItems(String url) throws IOException { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .header("Accept", "application/json") .get() .build(); Response response = client.newCall(request).execute(); client.dispatcher().executorService().shutdown(); if(response.code() == 200){ Jsonb jsonb = JsonbBuilder.create(); return jsonb.fromJson(response.body().string(), DictionaryItemsDao.class); } return null; }
public static DecisionTypesDao getTypes(String url) throws IOException { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .header("Accept", "application/json") .get() .build(); Response response = client.newCall(request).execute(); client.dispatcher().executorService().shutdown(); if(response.code() == 200){ Jsonb jsonb = JsonbBuilder.create(); return jsonb.fromJson(response.body().string(), DecisionTypesDao.class); } return null; }
public static DecisionDao getDecision(String url) throws IOException { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .header("Accept", "application/json") .get() .build(); Response response = client.newCall(request).execute(); client.dispatcher().executorService().shutdown(); if(response.code() == 200){ Jsonb jsonb = JsonbBuilder.create(); return jsonb.fromJson(response.body().string(), DecisionDao.class); } return null; }
/** * Same problem as above but now field is public, so clash takes place. */ @Test public void testConflictingProperties() { ConflictingProperties conflictingProperties = new ConflictingProperties(); conflictingProperties.setDOI("DOI value"); Jsonb jsonb = JsonbBuilder.create(new JsonbConfig() ); try { jsonb.toJson(conflictingProperties); fail(); } catch (JsonbException e) { if (!e.getMessage().equals("Property DOI clashes with property doi by read or write name in class org.eclipse.yasson.customization.JsonbPropertyTest$ConflictingProperties.")) { throw e; } } }
/** * Tests clash with property altered by naming strategy. */ @Test public void testConflictingWithUpperCamelStrategy() { ConflictingWithUpperCamelStrategy pojo = new ConflictingWithUpperCamelStrategy(); pojo.setDOI("DOI value"); Jsonb jsonb = JsonbBuilder.create(); String json = jsonb.toJson(pojo); Assert.assertEquals("{\"Doi\":\"DOI value\",\"doi\":\"DOI value\"}", json); jsonb = JsonbBuilder.create(new JsonbConfig() .withPropertyNamingStrategy(PropertyNamingStrategy.UPPER_CAMEL_CASE)); try { jsonb.toJson(pojo); fail(); } catch (JsonbException e) { if (!e.getMessage().equals("Property DOI clashes with property doi by read or write name in class org.eclipse.yasson.customization.JsonbPropertyTest$ConflictingWithUpperCamelStrategy.")) { throw e; } } }
/** * Tests applying for both public and nonpublic fields. */ @Test public void testFieldVisibilityStrategy() { JsonbConfig customizedConfig = new JsonbConfig(); customizedConfig.setProperty(JsonbConfig.PROPERTY_VISIBILITY_STRATEGY, new PropertyVisibilityStrategy() { @Override public boolean isVisible(Field field) { final String fieldName = field.getName(); return fieldName.equals("afield") || fieldName.equals("dfield"); } @Override public boolean isVisible(Method method) { throw new IllegalStateException("Not supported"); } }); FieldPojo fieldPojo = new FieldPojo("avalue", "bvalue", "cvalue", "dvalue"); Jsonb jsonb = JsonbBuilder.create(customizedConfig); assertEquals("{\"afield\":\"avalue\",\"dfield\":\"dvalue\"}", jsonb.toJson(fieldPojo)); }
/** * Tests applying for both public and nonpublic getters. */ @Test public void testMethodVisibilityStrategy() { JsonbConfig customizedConfig = new JsonbConfig(); customizedConfig.setProperty(JsonbConfig.PROPERTY_VISIBILITY_STRATEGY, new PropertyVisibilityStrategy() { @Override public boolean isVisible(Field field) { throw new IllegalStateException("Not supported"); } @Override public boolean isVisible(Method method) { final String methodName = method.getName(); return methodName.equals("getAgetter") || methodName.equals("getDgetter"); } }); GetterPojo getterPojo = new GetterPojo(); Jsonb jsonb = JsonbBuilder.create(customizedConfig); assertEquals("{\"agetter\":\"avalue\",\"dgetter\":\"dvalue\"}", jsonb.toJson(getterPojo)); }
@Test public void testMarshallOptionalIntArray() { final Jsonb jsonb = (new JsonBindingBuilder()).build(); final OptionalInt[] array = {OptionalInt.of(1), OptionalInt.of(2), OptionalInt.empty()}; assertEquals("[1,2,null]", jsonb.toJson(array)); OptionalInt[] result = jsonb.fromJson("[1,2,null]", new TestTypeToken<OptionalInt[]>() {}.getType()); assertTrue(result[0].isPresent()); assertEquals(1, result[0].getAsInt()); assertTrue(result[1].isPresent()); assertEquals(2, result[1].getAsInt()); assertEquals(OptionalInt.empty(), result[2]); }
@Test @SuppressWarnings("unchecked") public void testMarshallRawList() throws ParseException { List rawList = new ArrayList(); final SimpleDateFormat ddMMyyyy = new SimpleDateFormat("ddMMyyyy"); ddMMyyyy.setTimeZone(TimeZone.getTimeZone("Z")); rawList.add(ddMMyyyy.parse("24031981")); Box box = new Box(); box.boxStr = "box string"; box.crate = new Crate(); box.crate.crateStr = "crate str"; rawList.add(box); final Jsonb jsonb = JsonbBuilder.create(); String result = jsonb.toJson(rawList); assertEquals("[\"1981-03-24T00:00:00Z[UTC]\",{\"boxStr\":\"box string\",\"crate\":{\"crate_str\":\"crate str\"}}]", result); }
@Test public void testDifferentConfigsLocalDateTime() { final LocalDateTime dateTime = LocalDateTime.of(2015, 2, 16, 13, 21); final long millis = dateTime.atZone(ZoneId.of("Z")).toInstant().toEpochMilli(); final ScalarValueWrapper<LocalDateTime> pojo = new ScalarValueWrapper<>(); pojo.setValue(dateTime); final String expected = "{\"value\":\"2015-02-16T13:21:00\"}"; assertEquals(expected, jsonb.toJson(pojo)); final Jsonb jsonbCustom = JsonbBuilder.create(new JsonbConfig().withDateFormat(JsonbDateFormat.TIME_IN_MILLIS, Locale.FRENCH)); assertEquals("{\"value\":\"" + millis + "\"}", jsonbCustom.toJson(pojo)); ScalarValueWrapper<LocalDateTime> result = this.jsonb.fromJson(expected, new TestTypeToken<ScalarValueWrapper<LocalDateTime>>(){}.getType()); assertEquals(dateTime, result.getValue()); result = jsonbCustom.fromJson("{\"value\":\"" + millis + "\"}", new TestTypeToken<ScalarValueWrapper<LocalDateTime>>(){}.getType()); assertEquals(dateTime, result.getValue()); }
@Test public void testDateInMap() { JsonbConfig config = new JsonbConfig() .withDateFormat("yyyy", Locale.ENGLISH); Jsonb jsonb = JsonbBuilder.create(config); LocalDate localDate = LocalDate.of(2017, 9, 14); DateInMapPojo pojo = new DateInMapPojo(); pojo.setLocalDate(localDate); pojo.setDateMap(new HashMap<>()); pojo.getDateMap().put("first", localDate); String json = jsonb.toJson(pojo); Assert.assertEquals("{\"dateMap\":{\"first\":\"2017\"},\"localDate\":\"2017\"}", json); config = new JsonbConfig() .withDateFormat("dd.MM.yyyy", Locale.ENGLISH); jsonb = JsonbBuilder.create(config); DateInMapPojo result = jsonb.fromJson("{\"dateMap\":{\"first\":\"01.01.2017\"},\"localDate\":\"01.01.2017\"}", DateInMapPojo.class); Assert.assertEquals(LocalDate.of(2017,1,1), result.localDate); Assert.assertEquals(LocalDate.of(2017,1,1), result.dateMap.get("first")); }
@Test public void testWithSecurityManager() { Jsonb jsonb = JsonbBuilder.create(new JsonbConfig().withPropertyVisibilityStrategy(new PropertyVisibilityStrategy() { @Override public boolean isVisible(Field field) { return Modifier.isPublic(field.getModifiers()) || field.getName().equals("privateProperty"); } @Override public boolean isVisible(Method method) { return Modifier.isPublic(method.getModifiers()); } })); Pojo pojo = new Pojo(); pojo.setStrProperty("string propery"); Crate crate = new Crate(); crate.crateBigDec = BigDecimal.TEN; crate.crateStr = "crate string"; pojo.setCrate(crate); String result = jsonb.toJson(pojo); }
@Test public void testAdapter() { JsonbConfig config = new JsonbConfig().withAdapters(new AnimalAdapter()); Jsonb jsonb = JsonbBuilder.create(config); Animals animals = new Animals(); animals.listOfAnimals.add(new Dog("Hunting")); animals.listOfAnimals.add(new Cat("Playing")); String expectedJson = "{\"listOfAnimals\":[{\"className\":\"org.eclipse.yasson.adapters.PolymorphicAdapterTest$Dog\",\"instance\":{\"name\":\"NoName animal\",\"dogProperty\":\"Hunting\"}},{\"className\":\"org.eclipse.yasson.adapters.PolymorphicAdapterTest$Cat\",\"instance\":{\"name\":\"NoName animal\",\"catProperty\":\"Playing\"}}]}"; Assert.assertEquals(expectedJson, jsonb.toJson(animals, new ArrayList<Animal>(){}.getClass().getGenericSuperclass())); Animals reuslt = jsonb.fromJson(expectedJson, Animals.class); Assert.assertTrue(reuslt.listOfAnimals.get(0) instanceof Dog); Assert.assertTrue(reuslt.listOfAnimals.get(1) instanceof Cat); }
@Test public void testLowerCase() throws Exception { PropertyNamingStrategy strategy = new LowerCaseWithUnderscoresStrategy(); assertEquals("camel_case_property", strategy.translateName("camelCaseProperty")); assertEquals("camelcase_property", strategy.translateName("CamelcaseProperty")); assertEquals("camel_case_property", strategy.translateName("CamelCaseProperty")); assertEquals("_camel_case_property", strategy.translateName("_camelCaseProperty")); assertEquals("_camel_case_property", strategy.translateName("_CamelCaseProperty")); Jsonb jsonb = JsonbBuilder.create(new JsonbConfig().withPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CASE_WITH_UNDERSCORES)); String lowercaseUnderscoresJson = "{\"_starting_with_underscore_property\":\"def\",\"caps_underscore_property\":\"ghi\",\"upper_cased_property\":\"abc\"}"; assertEquals(lowercaseUnderscoresJson, jsonb.toJson(pojo)); NamingPojo result = jsonb.fromJson(lowercaseUnderscoresJson, NamingPojo.class); assertResult(result); }
@Test public void testNonCdiEnvironment() { JsonbConfig config = new JsonbConfig(); //allow only field with components that doesn't has cdi dependencies. config.withPropertyVisibilityStrategy(new PropertyVisibilityStrategy() { @Override public boolean isVisible(Field field) { return "adaptedValue3".equals(field.getName()); } @Override public boolean isVisible(Method method) { return false; } }); Jsonb jsonb = JsonbBuilder.create(config); final String result = jsonb.toJson(new AdaptedPojo()); assertEquals("{\"adaptedValue3\":1010}", result); }
@Test public void testClassLevelAnnotation() { Crate crate = new Crate(); crate.crateBigDec = BigDecimal.TEN; crate.crateStr = "crateStr"; crate.annotatedType = new AnnotatedWithSerializerType(); crate.annotatedType.value = "abc"; crate.annotatedTypeOverriddenOnProperty = new AnnotatedWithSerializerType(); crate.annotatedTypeOverriddenOnProperty.value = "def"; final Jsonb jsonb = JsonbBuilder.create(); String expected = "{\"annotatedType\":{\"valueField\":\"replaced value\"},\"annotatedTypeOverriddenOnProperty\":{\"valueField\":\"overridden value\"},\"crateBigDec\":10,\"crate_str\":\"crateStr\"}"; assertEquals(expected, jsonb.toJson(crate)); Crate result = jsonb.fromJson(expected, Crate.class); assertEquals("replaced value", result.annotatedType.value); assertEquals("overridden value", result.annotatedTypeOverriddenOnProperty.value); }
/** * Tests JSONB deserialization of arbitrary type invoked from a Deserializer. */ @Test public void testDeserializerDeserializationByType() { JsonbConfig config = new JsonbConfig().withDeserializers(new CrateDeserializer()); Jsonb jsonb = JsonbBuilder.create(config); Box box = createPojoWithDates(); String expected = "{\"boxStr\":\"Box string\",\"crate\":{\"crateInner\":{\"crateInnerBigDec\":10,\"crate_inner_str\":\"Single inner\",\"date\":\"14.05.2015 || 11:10:01\"},\"crateInnerList\":[{\"crateInnerBigDec\":10,\"crate_inner_str\":\"List inner 0\"},{\"crateInnerBigDec\":10,\"crate_inner_str\":\"List inner 1\"}],\"date\":\"2015-05-14T11:10:01\"},\"secondBoxStr\":\"Second box string\"}"; Box result = jsonb.fromJson(expected, Box.class); //deserialized by deserializationContext.deserialize(Class c) assertEquals(box.crate.crateInner.crateInnerBigDec, result.crate.crateInner.crateInnerBigDec); assertEquals(box.crate.crateInner.crateInnerStr, result.crate.crateInner.crateInnerStr); assertEquals("List inner 0", result.crate.crateInnerList.get(0).crateInnerStr); assertEquals("List inner 1", result.crate.crateInnerList.get(1).crateInnerStr); //set by deserializer statically assertEquals(new BigDecimal("123"), result.crate.crateBigDec); assertEquals("abc", result.crate.crateStr); }
/** * Tests JSONB serialization of arbitrary type invoked from a Serializer. */ @Test public void testSerializerSerializationOfType() { JsonbConfig config = new JsonbConfig().withSerializers(new CrateSerializer()); Jsonb jsonb = JsonbBuilder.create(config); String expected = "{\"boxStr\":\"Box string\",\"crate\":{\"crateStr\":\"REPLACED crate str\",\"crateInner\":{\"crateInnerBigDec\":10,\"crate_inner_str\":\"Single inner\"},\"crateInnerList\":[{\"crateInnerBigDec\":10,\"crate_inner_str\":\"List inner 0\"},{\"crateInnerBigDec\":10,\"crate_inner_str\":\"List inner 1\"}],\"crateBigDec\":54321},\"secondBoxStr\":\"Second box string\"}"; Box pojo = createPojo(); assertEquals(expected, jsonb.toJson(pojo)); Box result = jsonb.fromJson(expected, Box.class); assertEquals(new BigDecimal("54321"), result.crate.crateBigDec); //result.crate.crateStr is mapped to crate_str by jsonb property assertNull(result.crate.crateStr); assertEquals(pojo.crate.crateInner.crateInnerStr, result.crate.crateInner.crateInnerStr); assertEquals(pojo.crate.crateInner.crateInnerBigDec, result.crate.crateInner.crateInnerBigDec); }
@Test public void testContainerSerializer() { Jsonb jsonb = JsonbBuilder.create(); SimpleAnnotatedSerializedArrayContainer container = new SimpleAnnotatedSerializedArrayContainer(); SimpleContainer instance1 = new SimpleContainer(); instance1.setInstance("Test String 1"); SimpleContainer instance2 = new SimpleContainer(); instance2.setInstance("Test String 2"); container.setArrayInstance(new SimpleContainer[] {instance1, instance2}); container.setListInstance(new ArrayList<>()); container.getListInstance().add(new SimpleContainer("Test List 1")); container.getListInstance().add(new SimpleContainer("Test List 2")); String jsonString = jsonb.toJson(container); Assert.assertEquals("{\"arrayInstance\":[{\"instance\":\"Test String 1\"},{\"instance\":\"Test String 2\"}],\"listInstance\":[{\"instance\":\"Test List 1\"},{\"instance\":\"Test List 2\"}]}", jsonString); SimpleAnnotatedSerializedArrayContainer unmarshalledObject = jsonb.fromJson("{\"arrayInstance\":[{\"instance\":\"Test String 1\"},{\"instance\":\"Test String 2\"}],\"listInstance\":[{\"instance\":\"Test List 1\"},{\"instance\":\"Test List 2\"}]}", SimpleAnnotatedSerializedArrayContainer.class); Assert.assertEquals("Test String 1", unmarshalledObject.getArrayInstance()[0].getInstance()); Assert.assertEquals("Test String 2", unmarshalledObject.getArrayInstance()[1].getInstance()); Assert.assertEquals("Test List 1", unmarshalledObject.getListInstance().get(0).getInstance()); Assert.assertEquals("Test List 2", unmarshalledObject.getListInstance().get(1).getInstance()); }
@Test public void adapt() { final Jsonb jsonb = JsonbBuilder.create(new JsonbConfig().withAdapters(new BarAdapter())); final Foo foo = new Foo(); foo.bar = new Bar(); foo.bar.value = 1; foo.dummy = new Dummy(); foo.dummy.value = 2L; final String toString = jsonb.toJson(foo); assertEquals("{\"bar\":\"1\",\"dummy\":\"2\"}", toString); final Foo read = jsonb.fromJson(toString, Foo.class); assertEquals(foo.bar.value, read.bar.value); assertEquals(foo.dummy.value, read.dummy.value); }
@Test public void run() { WebBeansFinder.clearInstances(WebBeansUtil.getCurrentClassLoader()); final OpenWebBeansTestLifeCycle testLifecycle = new OpenWebBeansTestLifeCycle(); final WebBeansContext ctx = WebBeansContext.currentInstance(); final OpenWebBeansTestMetaDataDiscoveryService discoveryService = OpenWebBeansTestMetaDataDiscoveryService.class.cast(ctx.getScannerService()); discoveryService.deployClasses(asList(Service.class, ModelAdapter.class)); testLifecycle.startApplication(null); try { Jsonb jsonb = JsonbBuilder.create(); assertEquals("{\"model\":\"5\"}", jsonb.toJson(new Root(new Model(5)))); try { AutoCloseable.class.cast(jsonb).close(); } catch (final Exception e) { fail(e.getMessage()); } } finally { testLifecycle.stopApplication(null); } }
@Test public void ignoreNested() { final To to = new To(); to.name = "to"; final Person from = new Person(); from.name = "myname"; from.street = "blastreet 1"; from.description = "gets ignored"; to.person = from; to.persons = singletonList(from); final Jsonb jsonb = JsonbProvider.provider().create().build(); assertEquals("{\"name\":\"to\",\"person\":{\"name\":\"myname\"},\"persons\":[{\"name\":\"myname\"}]}", jsonb.toJson(to)); }
/** * Method handling HTTP GET requests. The returned object will be sent * to the client as "application/json" media type. * * @return Object that will be transformed to application/json response. */ @GET @Produces(MediaType.APPLICATION_JSON) @Path("{id}") public Response getEntity(@PathParam("id") String id, @QueryParam("attrs") String attrs, @QueryParam("options") List<String> options) { JsonbConfig config = new JsonbConfig(); config.withAdapters(new EntityAdapter()); Jsonb jsonb = JsonbBuilder.create(config); QueryData qd = new QueryData(); qd.entityIds = id; if (attrs != null) { qd.attrs = attrs; } QueryResult result = retrieveNgsiEntity(qd, options); if (result.status != 200) { return Response.status(result.status).build(); } else { JsonArray array = result.result.asJsonArray(); if (array.size() == 0) { return Response.status(404).build(); } if (options.indexOf("keyValues") != -1) { return Response.status(200).entity(array.getJsonObject(0)).build(); } CEntity c3imEntity = Ngsi2NGSILD.toNGSILD(array.getJsonObject(0)); return addJsonLinkHeader(Response.ok()).entity(jsonb.toJson(c3imEntity)).build(); } }
@POST @Consumes(MediaType.APPLICATION_JSON) public Response addEntity(String ent) { JsonbConfig config = new JsonbConfig(); config.withAdapters(new EntityAdapter()); Jsonb jsonb = JsonbBuilder.create(config); JsonObject obj = null; try { CEntity entity = jsonb.fromJson(ent, EntityImpl.class); obj = Ngsi2NGSILD.toNgsi(entity); } catch(Exception ex) { if(ex.getCause().getMessage().equals("400")) { return Response.status(400).build(); } } NgsiClient client = new NgsiClient(Configuration.ORION_BROKER); Response res = client.createEntity(obj); if(res.getStatus() == 201) { res = Response.status(201).location(URI.create( "entities/" + obj.getString("id"))).build(); } return res; }
public String customizedMapping() { JsonbConfig jsonbConfig = new JsonbConfig() .withPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CASE_WITH_DASHES) .withPropertyOrderStrategy(PropertyOrderStrategy.LEXICOGRAPHICAL) .withStrictIJSON(true) .withFormatting(true) .withNullValues(true); Jsonb jsonb = JsonbBuilder.create(jsonbConfig); return jsonb.toJson(book1); }
public String allCustomizedMapping() { PropertyVisibilityStrategy vis = new PropertyVisibilityStrategy() { @Override public boolean isVisible(Field field) { return false; } @Override public boolean isVisible(Method method) { return false; } }; JsonbConfig jsonbConfig = new JsonbConfig() .withPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CASE_WITH_DASHES) .withPropertyOrderStrategy(PropertyOrderStrategy.LEXICOGRAPHICAL) .withPropertyVisibilityStrategy(vis) .withStrictIJSON(true) .withFormatting(true) .withNullValues(true) .withBinaryDataStrategy(BinaryDataStrategy.BASE_64_URL) .withDateFormat("MM/dd/yyyy", Locale.ENGLISH); Jsonb jsonb = JsonbBuilder.create(jsonbConfig); return jsonb.toJson(book1); }
public Book deserializeBook() { Book book = new Book("SHDUJ-4532", "Fun with Java", "Alex Theedom"); Jsonb jsonb = JsonbBuilder.create(); String json = jsonb.toJson(book); book = jsonb.fromJson(json, Book.class); return book; }
@Test public void givenJSON_shouldDeserializeToBook() { Book expectedBook = new Book("SHDUJ-4532", "Fun with Java", "Alex Theedom"); String json = "{\"com.readlearncode.devWorks.overview.domain.Book\":{\"author\":\"Alex Theedom\",\"id\":\"SHDUJ-4532\",\"title\":\"Fun with Java\"}}"; JsonbConfig config = new JsonbConfig().withDeserializers(new BookDeserializer()); Jsonb jsonb = JsonbBuilder.newBuilder().withConfig(config).build(); Book actualBook = jsonb.fromJson(json, Book.class); assertThat(actualBook).isEqualTo(expectedBook); }
@Test public void givenSerialize_shouldSerialiseBook() { Book book = new Book("SHDUJ-4532", "Fun with Java", "Alex Theedom"); String expectedJson = "{\"com.readlearncode.devWorks.overview.domain.Book\":{\"author\":\"Alex Theedom\",\"id\":\"SHDUJ-4532\",\"title\":\"Fun with Java\"}}"; JsonbConfig config = new JsonbConfig().withSerializers(new BookSerializer()); Jsonb jsonb = JsonbBuilder.newBuilder().withConfig(config).build(); String actualJson = jsonb.toJson(book); assertThat(actualJson).isEqualTo(expectedJson); }