Generating JSON strings from Java objects with JSON-B

In addition to populating Java objects from JSON data, JSON-B can also generate JSON strings from Java objects. The following example illustrates how to do this:

    package net.ensode.javaee8book.jsonbjavatojson.service; 
 
    //imports omitted for brevity 
 
    @Path("/customersearchcontroller") 
    public class CustomerSearchControllerService { 
      private final List<Customer> customerList = new ArrayList<>(); 
 
      @GET 
      @Path("{firstName}") 
      public Response getCustomerByFirstName(@PathParam("firstName")   
String firstName) { List<Customer> filteredCustomerList; String jsonString; initializeCustomerList(); //method declaration omitted Jsonb jsonb = JsonbBuilder.create(); filteredCustomerList = customerList.stream().filter( customer -> customer.getFirstName().equals(firstName)). collect(Collectors.toList()); jsonString = jsonb.toJson(filteredCustomerList); return Response.ok(jsonString).build(); } }

In this example, we are converting a List of Customer objects to JSON.

We chose a List for the example to illustrate that JSON-B supports this functionality, but of course, we could also convert a single object to its JSON representation.

Just as before, we create an instance of javax.json.bind.Jsonb by invoking the static javax.json.bind.JsonbBuilder.create() method. Once we have our Jsonb instance, we simply invoke its toJson() method to convert the list of objects to its equivalent JSON representation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.218.221