Java Code Examples for javax.json.bind.Jsonb#fromJson()

The following examples show how to use javax.json.bind.Jsonb#fromJson() . 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: StaticUiSpecGenerator.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
private void visitComponentRoute(final UiSpecService<Object> service, final Jsonb jsonb, final Route route,
        final BiConsumer<String, String> onFile) throws IOException {
    try (final InputStream stream = new ByteArrayInputStream(route.getContent())) {
        try {
            final ComponentDetailList list = jsonb.fromJson(stream, ComponentDetailList.class);
            final Ui ui =
                    service.convert(list.getDetails().iterator().next(), "en", null).toCompletableFuture().get();
            onFile
                    .accept("component/"
                            + route.getId().substring("component_server_component_details_en_".length()),
                            jsonb.toJson(ui));
        } catch (final InterruptedException | ExecutionException e) {
            throw new IllegalStateException(e);
        }
    }
}
 
Example 2
Source File: StaticUiSpecGenerator.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
private void visitConfigurationRoute(final UiSpecService<Object> service, final Jsonb jsonb, final Route route,
        final BiConsumer<String, String> onFile) throws IOException {
    final String configId = route.getId().substring("component_server_configuration_details_en_".length());
    // todo: resolve the parent since we have it in the route instead of using that hack
    final String id = new String(Base64.getDecoder().decode(configId), StandardCharsets.UTF_8);
    final String family = id.split("#")[1];
    try (final InputStream stream = new ByteArrayInputStream(route.getContent())) {
        try {
            final ConfigTypeNodes nodes = jsonb.fromJson(stream, ConfigTypeNodes.class);
            final Ui ui = service
                    .convert(family, "en", nodes.getNodes().values().iterator().next(), null)
                    .toCompletableFuture()
                    .get();
            onFile.accept("configuration/" + configId, jsonb.toJson(ui));
        } catch (final InterruptedException | ExecutionException e) {
            throw new IllegalStateException(e);
        }
    }
}
 
Example 3
Source File: JmsMessageReader.java    From blog-tutorials with MIT License 6 votes vote down vote up
@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 4
Source File: JaxrsJsonbTest.java    From thorntail with Apache License 2.0 6 votes vote down vote up
@Test
@RunAsClient
public void testJaxrsJsonb() throws Exception {
    Dog dog = new Dog();
    dog.name = "Falco";
    dog.age = 4;
    dog.bitable = false;

    Jsonb jsonb = JsonbBuilder.create();
    
    String response = client.target("http://localhost:8080/jsonb")
                          .request(MediaType.APPLICATION_JSON)
                          .post(Entity.entity(jsonb.toJson(dog), MediaType.APPLICATION_JSON),
                          String.class);
    Dog dog2 = jsonb.fromJson(response, Dog.class);
    Assert.assertEquals(dog.name, dog2.name);
    Assert.assertEquals(dog.age, dog2.age);
    Assert.assertTrue(dog2.bitable);
}
 
Example 5
Source File: JavaxJsonbTest.java    From thorntail with Apache License 2.0 6 votes vote down vote up
@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 6
Source File: MinimalExample.java    From Java-EE-8-Sampler with MIT License 5 votes vote down vote up
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;
}
 
Example 7
Source File: DefaultEventSerializationServiceTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Test
void testSerializationStructureNoEmptyElements() throws Exception {
    when(mockEvent.getInbox()).thenReturn(empty());
    when(mockEvent.getAgents()).thenReturn(emptyList());
    when(mockEvent.getObjectTypes()).thenReturn(emptyList());

    final String json = svc.serialize(mockEvent);

    final Jsonb jsonb = JsonbBuilder.create();
    @SuppressWarnings("unchecked")
    final Map<String, Object> map = jsonb.fromJson(json, Map.class);
    assertTrue(map.containsKey("@context"), "@context property not in JSON structure!");
    assertTrue(map.containsKey("id"), "id property not in JSON structure!");
    assertTrue(map.containsKey("type"), "type property not in JSON strucutre!");
    assertFalse(map.containsKey("inbox"), "inbox property unexpectedly in JSON structure!");
    assertFalse(map.containsKey("actor"), "actor property unexpectedly in JSON structure!");
    assertTrue(map.containsKey("object"), "object property not in JSON structure!");
    assertTrue(map.containsKey("published"), "published property not in JSON structure!");

    final List<?> types = (List<?>) map.get("type");
    assertTrue(types.contains("Create"), "as:Create type not in type list!");

    @SuppressWarnings("unchecked")
    final Map<String, Object> obj = (Map<String, Object>) map.get("object");
    assertTrue(obj.containsKey("id"), "object id property not in JSON structure!");
    assertFalse(obj.containsKey("type"), "empty object type unexpectedly in JSON structure!");

    assertTrue(AS.getNamespace().contains((String) map.get("@context")), "AS namespace not in @context!");

    assertEquals("info:event/12345", map.get("id"), "id property has incorrect value!");
    assertEquals(time.toString(), map.get("published"), "published property has incorrect value!");
}
 
Example 8
Source File: DefaultEventSerializationServiceTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Test
void testSerializationStructure() throws Exception {
    when(mockEvent.getTypes()).thenReturn(asList(Create, Activity));

    final String json = svc.serialize(mockEvent);

    final Jsonb jsonb = JsonbBuilder.create();
    @SuppressWarnings("unchecked")
    final Map<String, Object> map = jsonb.fromJson(json, Map.class);
    assertTrue(map.containsKey("@context"), "@context property not in JSON structure!");
    assertTrue(map.containsKey("id"), "id property not in JSON structure!");
    assertTrue(map.containsKey("type"), "type property not in JSON structure!");
    assertTrue(map.containsKey("inbox"), "inbox property not in JSON structure!");
    assertTrue(map.containsKey("actor"), "actor property not in JSON structure!");
    assertTrue(map.containsKey("object"), "object property not in JSON structure!");
    assertTrue(map.containsKey("published"), "published property not in JSON structure!");

    final List<?> types = (List<?>) map.get("type");
    assertTrue(types.contains("Create"), "as:Create not in type list!");
    assertTrue(types.contains(Activity.getIRIString()), "prov:Activity not in type list!");

    assertTrue(AS.getNamespace().contains((String) map.get("@context")), "AS namespace not in @context!");

    final List<?> actor = (List<?>) map.get("actor");
    assertTrue(actor.contains("info:user/test"), "actor property has incorrect value!");

    assertEquals("info:event/12345", map.get("id"), "id property has incorrect value!");
    assertEquals("info:ldn/inbox", map.get("inbox"), "inbox property has incorrect value!");
    assertEquals(time.toString(), map.get("published"), "published property has incorrect value!");
}
 
Example 9
Source File: RecordConverters.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
public Object toType(final MappingMetaRegistry registry, final Object data, final Class<?> parameterType,
        final Supplier<JsonBuilderFactory> factorySupplier, final Supplier<JsonProvider> providerSupplier,
        final Supplier<Jsonb> jsonbProvider, final Supplier<RecordBuilderFactory> recordBuilderProvider) {
    if (parameterType.isInstance(data)) {
        return data;
    }

    final JsonObject inputAsJson;
    if (JsonObject.class.isInstance(data)) {
        if (JsonObject.class == parameterType) {
            return data;
        }
        inputAsJson = JsonObject.class.cast(data);
    } else if (Record.class.isInstance(data)) {
        final Record record = Record.class.cast(data);
        if (!JsonObject.class.isAssignableFrom(parameterType)) {
            final MappingMeta mappingMeta = registry.find(parameterType, recordBuilderProvider);
            if (mappingMeta.isLinearMapping()) {
                return mappingMeta.newInstance(record);
            }
        }
        final JsonObject asJson = toJson(factorySupplier, providerSupplier, record);
        if (JsonObject.class == parameterType) {
            return asJson;
        }
        inputAsJson = asJson;
    } else {
        if (parameterType == Record.class) {
            return toRecord(registry, data, jsonbProvider, recordBuilderProvider);
        }
        final Jsonb jsonb = jsonbProvider.get();
        inputAsJson = jsonb.fromJson(jsonb.toJson(data), JsonObject.class);
    }
    return jsonbProvider.get().fromJson(new JsonValueReader<>(inputAsJson), parameterType);
}
 
Example 10
Source File: BookDeserializerTest.java    From Java-EE-8-Sampler with MIT License 5 votes vote down vote up
@Test
public void givenJSON_shouldDeserializeToBook() {
    String json = "{\"id\":\"QWE-123-RTS\",\"lastName\":\"Theedom\",\"firstName\":\"Alex\",\"title\":\"Fun with Java\"}";
    JsonbConfig config = new JsonbConfig().withDeserializers(new BookDeserializer());
    Jsonb jsonb = JsonbBuilder.newBuilder().withConfig(config).build();
    String id = jsonb.fromJson(json, String.class);
    assertThat(id).isEqualTo("QWE-123-RTS");
}
 
Example 11
Source File: WebsocketEndpoint.java    From Hands-On-Cloud-Native-Applications-with-Java-and-Quarkus with MIT License 5 votes vote down vote up
@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 12
Source File: JsonbServlet.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@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 13
Source File: JsonDemo.java    From Java-EE-8-and-Angular with MIT License 5 votes vote down vote up
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 14
Source File: ActivityParserFactory.java    From BotServiceStressToolkit with MIT License 5 votes vote down vote up
public static Activity parse(String type, String jsonPayload) {
	//log.debug(jsonPayload);

	Jsonb jsonb = JsonbBuilder.create();

	if (type.equals("message")) {
		return jsonb.fromJson(jsonPayload, Message.class);
	}else if (type.equals("event")) {
		return jsonb.fromJson(jsonPayload, Event.class);
	}

	return jsonb.fromJson(jsonPayload, Activity.class);
}
 
Example 15
Source File: MockChannelCallback.java    From BotServiceStressToolkit with MIT License 5 votes vote down vote up
@POST
@Path("/conversations/{conversationId}/activities/{activityId}")
@Consumes(MediaType.APPLICATION_JSON)
public Response replyToActivity(@PathParam("conversationId") String conversationId,
		@PathParam("activityId") String activityId, InputStream is) {
	log.info(String.format("replyToActivity(conversationId=%s, activityId=%s)", conversationId, activityId));
	String payload;
	try {
		payload = IOUtils.toString(is, Charset.forName("UTF-8"));
		Jsonb jsonb = JsonbBuilder.create();
		Activity activity = jsonb.fromJson(payload, Activity.class);

		if (activity.getType() == "typing") {
			log.info(String.format(
					"Typing response received, ignoging for replyToActivity(conversationId=%s, activityId=%s) [Activity(replyToId=%s)]",
					conversationId, activityId, activity.getReplyToId()));
		} else {
			activity = ActivityParserFactory.parse(activity.getType(), payload, conversationId, activityId);
			activity.setReplyToId(activityId);

			ActivityRequestReply.getInstance().setResponse(activityId, activity);
			log.info(String.format("replyToActivity(conversationId=%s, activityId=%s) [Activity(replyToId=%s)]",
					conversationId, activityId, activity.getReplyToId()));
		}

		return Response.accepted().build();
	} catch (Exception e) {
		log.error("Error in replyToActivity", e);
		return Response.serverError().entity("Error: " + e).build();
	}
}
 
Example 16
Source File: JsonbUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenPersonJsonArray_whenDeserializeWithJsonb_thenGetPersonList() {
    Jsonb jsonb = JsonbBuilder.create();
    // @formatter:off
    String personJsonArray =
        "[" + 
            "{\"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        
    @SuppressWarnings("serial")
    List<Person> personList = jsonb.fromJson(personJsonArray, new ArrayList<Person>() {
    }.getClass()
        .getGenericSuperclass());
    // @formatter:off
    List<Person> personListExpected = 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
    assertTrue(ListUtils.isEqualList(personList, personListExpected));
}
 
Example 17
Source File: ArgumentHelper.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
/**
 * This is used once we have a valid jsonString, either from above or from complex default value from graphql-java
 *
 * @param jsonString the object represented as a json String
 * @param field the field as created while scanning
 * @return the correct object
 */
private Object correctComplexObjectFromJsonString(String jsonString, Field field) throws AbstractDataFetcherException {
    Class ownerClass = classloadingService.loadClass(field.getReference().getClassName());
    try {
        Jsonb jsonb = JsonBCreator.getJsonB(field.getReference().getClassName());
        return jsonb.fromJson(jsonString, ownerClass);
    } catch (JsonbException jbe) {
        throw new TransformException(jbe, field, jsonString);
    }
}
 
Example 18
Source File: ExampleResource.java    From example-health-jee-openshift with Apache License 2.0 5 votes vote down vote up
@POST
  @Path("/v1/login/user")
  @Produces(MediaType.APPLICATION_JSON)
  @Consumes(MediaType.APPLICATION_JSON)
  public Response login(String body) {
      // {"UID":username,"PASS":password}
       Jsonb jsonb = JsonbBuilder.create();
       Credentials c = jsonb.fromJson(body, Credentials.class);
      List<Patient> results = entityManager.createNamedQuery("Patient.login", Patient.class)
              .setParameter("userId", c.UID)
              .setParameter("password", c.PASS)
              .getResultList();
      logger.info("Found this many patients: " + results.size());
      int returnCode = 0;
      if (results.size() == 0) {
          returnCode=1;
      }

      /*
          "ResultSet Output": [
          {
              "PATIENTID": 1
          }
          ],
      "StatusCode": 200,
      "StatusDescription": "Execution Successful"
  }*/
      if (returnCode==1) {
          return Response.status(Status.NOT_FOUND).build();
      }
      
      String loginBlob = "{\"ResultSet Output\":" + jsonb.toJson(results) 
      + ", \"StatusCode\": 200, \n \"StatusDescription\": \"Execution Successful\"}";

      logger.info("login blob: " + loginBlob);
      JsonReader jsonReader = Json.createReader(new StringReader(loginBlob));
      JsonObject jresponse  = jsonReader.readObject();
      jsonReader.close();
return Response.ok(jresponse).build();         
  }
 
Example 19
Source File: DIBatchSimulationTest.java    From component-runtime with Apache License 2.0 4 votes vote down vote up
private void doRun(final ComponentManager manager, final Collection<Object> sourceData,
        final Collection<Object> processorData, final Map<String, Object> globalMap,
        final AutoChunkProcessor processorProcessor, final InputsHandler inputsHandlerProcessor,
        final OutputsHandler outputHandlerProcessor, final InputFactory inputsProcessor,
        final OutputFactory outputsProcessor, final Mapper tempMapperMapper) {
    row1Struct row1 = new row1Struct();

    tempMapperMapper.start();
    final ChainedMapper mapperMapper;
    try {
        final List<Mapper> splitMappersMapper = tempMapperMapper.split(tempMapperMapper.assess());
        mapperMapper = new ChainedMapper(tempMapperMapper, splitMappersMapper.iterator());
        mapperMapper.start();
        globalMap.put("mapperMapper", mapperMapper);
    } finally {
        try {
            tempMapperMapper.stop();
        } catch (final RuntimeException re) {
            re.printStackTrace();
        }
    }

    final Input inputMapper = mapperMapper.create();
    inputMapper.start();
    globalMap.put("inputMapper", inputMapper);

    final Map<Class<?>, Object> servicesMapper =
            manager.findPlugin(mapperMapper.plugin()).get().get(ComponentManager.AllServices.class).getServices();
    final Jsonb jsonbMapper = Jsonb.class.cast(servicesMapper.get(Jsonb.class));
    final JsonProvider jsonProvider = JsonProvider.class.cast(servicesMapper.get(JsonProvider.class));
    final JsonBuilderFactory jsonBuilderFactory =
            JsonBuilderFactory.class.cast(servicesMapper.get(JsonBuilderFactory.class));
    final RecordBuilderFactory recordBuilderMapper =
            RecordBuilderFactory.class.cast(servicesMapper.get(RecordBuilderFactory.class));
    final RecordConverters converters = new RecordConverters();

    final RecordConverters.MappingMetaRegistry registry = new RecordConverters.MappingMetaRegistry();

    Object dataMapper;
    while ((dataMapper = inputMapper.next()) != null) {
        final String jsonValueMapper;
        if (javax.json.JsonValue.class.isInstance(dataMapper)) {
            jsonValueMapper = javax.json.JsonValue.class.cast(dataMapper).toString();
        } else if (org.talend.sdk.component.api.record.Record.class.isInstance(dataMapper)) {
            jsonValueMapper = converters
                    .toType(registry,
                            converters
                                    .toRecord(new RecordConverters.MappingMetaRegistry(), dataMapper,
                                            () -> jsonbMapper, () -> recordBuilderMapper),
                            JsonObject.class, () -> jsonBuilderFactory, () -> jsonProvider, () -> jsonbMapper,
                            () -> recordBuilderMapper)
                    .toString();
        } else {
            jsonValueMapper = jsonbMapper.toJson(dataMapper);
        }
        row1 = jsonbMapper.fromJson(jsonValueMapper, row1.getClass());
        sourceData.add(row1);

        inputsHandlerProcessor.reset();
        inputsHandlerProcessor.setInputValue("FLOW", row1);

        outputHandlerProcessor.reset();
        processorProcessor.onElement(name -> {
            assertEquals(Branches.DEFAULT_BRANCH, name);
            final Object read = inputsProcessor.read(name);
            processorData.add(read);
            return read;
        }, outputsProcessor);
    }
}
 
Example 20
Source File: AssertJson.java    From component-runtime with Apache License 2.0 4 votes vote down vote up
private static JsonValue read(final String json, final Jsonb jsonb) {
    return jsonb.fromJson(json, JsonValue.class);
}