Java Code Examples for javax.json.bind.Jsonb#toJson()
The following examples show how to use
javax.json.bind.Jsonb#toJson() .
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: BaseBotSampler.java From BotServiceStressToolkit with MIT License | 6 votes |
protected String getSuggestedActionsResponseAsJsonString(List<Message> responses) { String suggestedActionsJsonAsString = ""; Jsonb jsonb = JsonbBuilder.create(); int i = 1; for (Message message : responses) { if (message.getSuggestedActions() != null && message.getSuggestedActions().getActions() != null && message.getSuggestedActions().getActions().size() > 0) { for (CardAction action : message.getSuggestedActions().getActions()) { String payload = jsonb.toJson(action); suggestedActionsJsonAsString += String.format(SUGGESTED_ACTION_NUMBER, i++) + payload + NEW_LINE; } } } if (suggestedActionsJsonAsString.length() == 0) { suggestedActionsJsonAsString = null; return null; } return StringUtils.trimToEmpty(suggestedActionsJsonAsString + NEW_LINE); }
Example 2
Source File: QuoteGenerator.java From Hands-On-Cloud-Native-Applications-with-Java-and-Quarkus with MIT License | 6 votes |
private String generateQuote(int type, int company, int amount) { System.out.println("<!>> QuoteGenerator wants to create " +type + " "+company+ ""+amount); Jsonb jsonb = JsonbBuilder.create(); /* MyOperation o = new MyOperation(); o.setAmount(11); o.setCompany("zaza"); o.setType(1); String j = jsonb.toJson(o); System.out.println(">>>>generateQuote "+j); Operation operation = new Operation(type, amount); */ Operation operation = new Operation(type, Company.values()[company], amount); // String quote="{ \"type\":1,\"company\":\"Acme\",\"amount\":50}"; System.out.println("<>> QuoteGenerator " +jsonb.toJson(operation)); return jsonb.toJson(operation); }
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: 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 5
Source File: JsonbUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void givenPersonObject_whenSerializeWithJsonb_thenGetPersonJson() { Jsonb jsonb = JsonbBuilder.create(); 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\"," + "\"registeredDate\":\"07-09-2019\"," + "\"salary\":\"1000.0\"}"; // @formatter:on assertTrue(jsonExpected.equals(jsonPerson)); }
Example 6
Source File: JsonbUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void givenPersonList_whenSerializeWithJsonb_thenGetPersonJsonArray() { Jsonb jsonb = JsonbBuilder.create(); // @formatter:off List<Person> personList = Arrays.asList( new Person(1, "Jhon", "[email protected]", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)), new Person(2, "Jhon", "[email protected]", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500)), new Person(3, "Jhon", null, 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)), new Person(4, "Tom", "[email protected]", 21, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500))); // @formatter:on String jsonArrayPerson = jsonb.toJson(personList); // @formatter:off String jsonExpected = "[" + "{\"email\":\"[email protected]\"," + "\"id\":1,\"person-name\":\"Jhon\"," + "\"registeredDate\":\"09-09-2019\"," + "\"salary\":\"1000.0\"}," + "{\"email\":\"[email protected]\"," + "\"id\":2,\"person-name\":\"Jhon\"," + "\"registeredDate\":\"09-09-2019\"," + "\"salary\":\"1500.0\"},{\"email\":null," + "\"id\":3,\"person-name\":\"Jhon\"," + "\"registeredDate\":\"09-09-2019\"," + "\"salary\":\"1000.0\"}," + "{\"email\":\"[email protected]\"," + "\"id\":4,\"person-name\":\"Tom\"," + "\"registeredDate\":\"09-09-2019\"," + "\"salary\":\"1500.0\"}" + "]"; // @formatter:on assertTrue(jsonArrayPerson.equals(jsonExpected)); }
Example 7
Source File: SchemaBuilderTest.java From smallrye-graphql with Apache License 2.0 | 5 votes |
static String toString(Schema schema) { JsonbConfig config = new JsonbConfig() .withFormatting(true); Jsonb jsonb = JsonbBuilder.create(config); return jsonb.toJson(schema); }
Example 8
Source File: JsonBindingExample.java From Java-EE-8-Sampler with MIT License | 5 votes |
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); }
Example 9
Source File: BookSerializerTest.java From Java-EE-8-Sampler with MIT License | 5 votes |
@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); }
Example 10
Source File: ExampleResource.java From example-health-jee-openshift with Apache License 2.0 | 5 votes |
@GET @Path("/v1/getInfo/prescription/{patId}") @Produces(MediaType.APPLICATION_JSON) public Response getPrescriptions(@PathParam("patId") String patId) { List<Prescription> results = entityManager.createNamedQuery("Prescription.getPrescription", Prescription.class) .setParameter("pid", patId) .getResultList(); Jsonb jsonb = JsonbBuilder.create(); logger.info("Found this many prescriptions with id " + patId + " = " + results.size()); int returnCode = 0; if (results.size() == 0) { returnCode=1; // return Response.ok("No prescriptions found.").build(); } String prescriptionBlob = "{\"GETMEDO\": {" + " \"CA_REQUEST_ID\" : \"01IPAT\"," + " \"CA_RETURN_CODE\": " + returnCode + "," + " \"CA_PATIENT_ID\": \"" + patId + "\"," + " \"CA_LIST_MEDICATION_REQUEST\": { \"CA_MEDICATIONS\": " + jsonb.toJson(results) + "}}}"; logger.info("Prescription blob: " + prescriptionBlob); JsonReader jsonReader = Json.createReader(new StringReader(prescriptionBlob)); JsonObject jresponse = jsonReader.readObject(); jsonReader.close(); return Response.ok(jresponse).build(); }
Example 11
Source File: JsonBUser.java From javaee8-cookbook with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws Exception { User user = new User("Elder", "[email protected]"); Jsonb jb = JsonbBuilder.create(); String jsonUser = jb.toJson(user); User u = jb.fromJson(jsonUser, User.class); jb.close(); System.out.println("json: " + jsonUser); System.out.println("user: " + u); }
Example 12
Source File: ExampleResource.java From example-health-jee-openshift with Apache License 2.0 | 5 votes |
@GET @Path("/v1/getInfo/patients") @Produces(MediaType.APPLICATION_JSON) public Response getPatients() { List<Patient> results = entityManager.createNamedQuery("Patient.getPatients", Patient.class).getResultList(); Jsonb jsonb = JsonbBuilder.create(); String patientBlob = "{\"ResultSet Output\": " + jsonb.toJson(results) + ", \"StatusCode\": 200, \n \"StatusDescription\": \"Execution Successful\"}"; JsonReader jsonReader = Json.createReader(new StringReader(patientBlob)); JsonObject jresponse = jsonReader.readObject(); jsonReader.close(); return Response.ok(jresponse).build(); }
Example 13
Source File: ExampleResource.java From example-health-jee-openshift with Apache License 2.0 | 5 votes |
@GET @Path("/v1/showAllergies") @Produces(MediaType.APPLICATION_JSON) public Response showAllergies() { /* "ResultSet Output": [ { "CITY": "Albany ", "POSTCODE": "12202 ", "PATIENT_NUM": 1437, "BIRTHDATE": "1961-11-26", "ALLERGY_START": "1991-10-08", "ALLERGY_STOP": null, "DESCRIPTION": "Allergy to fish" } ], "StatusCode": 200, "StatusDescription": "Execution Successful" } */ // select Patients.patient_id, Patients.birthdate, Patients.city, Patients.postcode, Allergies.description, Allergies.allergy_start, Allergies.allergy_stop from Patients JOIN Allergies ON Patients.patient_id = Allergies.patient_id; List<AllergyList> results = entityManager.createNamedQuery("Allergy.getAllergies", AllergyList.class).getResultList(); Jsonb jsonb = JsonbBuilder.create(); String allergyBlob = "{\"ResultSet Output\": " + jsonb.toJson(results) + ", \"StatusCode\": 200, \n \"StatusDescription\": \"Execution Successful\"}"; JsonReader jsonReader = Json.createReader(new StringReader(allergyBlob)); JsonObject jresponse = jsonReader.readObject(); jsonReader.close(); return Response.ok(jresponse).build(); }
Example 14
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 15
Source File: JsonbTest.java From ee8-sandbox with Apache License 2.0 | 5 votes |
@Test public void personToJsonString() { Person duke = new Person("Duke", LocalDate.of(1995, 5, 23)); duke.setPhoneNumbers( Arrays.asList( new PhoneNumber(HOME, "100000"), new PhoneNumber(OFFICE, "200000") ) ); Jsonb jsonMapper = JsonbBuilder.create(); String json = jsonMapper.toJson(duke); LOG.log(Level.INFO, "converted json result: {0}", json); String name = JsonPath.parse(json).read("$.name"); assertEquals("Duke", name); Configuration config = Configuration.defaultConfiguration() .jsonProvider(new GsonJsonProvider()) .mappingProvider(new GsonMappingProvider()); TypeRef<List<String>> typeRef = new TypeRef<List<String>>() { }; List<String> numbers = JsonPath.using(config).parse(json).read("$.phoneNumbers[*].number", typeRef); assertEquals(Arrays.asList("100000", "200000"), numbers); }
Example 16
Source File: QuoteGenerator.java From Hands-On-Cloud-Native-Applications-with-Java-and-Quarkus with MIT License | 4 votes |
private String generateQuote(int type, int company, int amount) { Jsonb jsonb = JsonbBuilder.create(); Operation operation = new Operation(type, Company.values()[company], amount); return jsonb.toJson(operation); }
Example 17
Source File: JsonBindingExample.java From Java-EE-8-Sampler with MIT License | 4 votes |
public String bookAdapterToJson() { JsonbConfig jsonbConfig = new JsonbConfig().withAdapters(new BookletAdapter()); Jsonb jsonb = JsonbBuilder.create(jsonbConfig); return jsonb.toJson(book1); }
Example 18
Source File: ExampleResource.java From example-health-jee-openshift with Apache License 2.0 | 4 votes |
@GET @Path("/v1/listObs/{patId}") @Produces(MediaType.APPLICATION_JSON) public Response listObs(@PathParam("patId") String patId) { List<Observation> results = entityManager.createNamedQuery("Observation.getObservations", Observation.class) .setParameter("pid", patId) .getResultList(); Jsonb jsonb = JsonbBuilder.create(); logger.info("Found this many observations with id " + patId + " = " + results.size()); int returnCode = 0; if (results.size() == 0) { returnCode=1; } /* output Format of JSON output: "ResultSet Output": [ { "PATIENTID": 1, "DATEOFOBSERVATION": "2018-05-03", "CODE": "11111-0 ", "DESCRIPTION": "Tobacco smoking status NHIS", "NUMERICVALUE": null, "CHARACTERVALUE": "Former smoker", "UNITS": null }], "StatusCode": 200, "StatusDescription": "Execution Successful" */ String observationBlob = "{\"ResultSet Output\": " + jsonb.toJson(results) + ", \"StatusCode\": 200, \n \"StatusDescription\": \"Execution Successful\"}"; logger.info("Observation blob: " + observationBlob); JsonReader jsonReader = Json.createReader(new StringReader(observationBlob)); JsonObject jresponse = jsonReader.readObject(); jsonReader.close(); return Response.ok(jresponse).build(); }
Example 19
Source File: QuoteGenerator.java From Hands-On-Cloud-Native-Applications-with-Java-and-Quarkus with MIT License | 4 votes |
private String generateQuote(int type, int company, int amount) { Jsonb jsonb = JsonbBuilder.create(); Operation operation = new Operation(type, Company.values()[company], amount); return jsonb.toJson(operation); }
Example 20
Source File: BasicTypeExampleTest.java From Java-EE-8-Sampler with MIT License | 3 votes |
@Test public void givenObject_shouldSerialiseInLexicographicalOrder(){ Jsonb jsonb = JsonbBuilder.create(); String actualJson = jsonb.toJson(new LexicographicalOrder()); assertThat(actualJson).isEqualTo("{\"animal\":\"Cat\",\"bread\":\"Chiapata\",\"car\":\"Ford\",\"dog\":\"Labradoodle\"}"); }