Java 类javax.json.bind.JsonbBuilder 实例源码

项目:JSON-framework-comparison    文件:JavaTypesTest.java   
@Test
public void givenJavaTypes_shouldSerialise() throws MalformedURLException, URISyntaxException {

    /*
        {
          "atomicInteger": 10,
          "bigDecimal": 10,
          "bigInteger": 10,
          "longAdder": 0,
          "optionalDouble": 10,
          "optionalInt": 10,
          "optionalLong": 10,
          "stringOptional": "Hello World",
          "uri": "http://www.readlearncode.com",
          "url": "http://www.readlearncode.com"
        }
     */

    String expectedJson = "{\"atomicInteger\":10,\"bigDecimal\":10,\"bigInteger\":10,\"longAdder\":0,\"optionalDouble\":10.0,\"optionalInt\":10,\"optionalLong\":10,\"stringOptional\":\"Hello World\",\"uri\":\"http://www.readlearncode.com\",\"url\":\"http://www.readlearncode.com\"}";
    String actualJson = JsonbBuilder.create().toJson(new JavaTypes());
    assertThat(actualJson).isEqualTo(expectedJson);
}
项目:JSON-framework-comparison    文件:AllDateTypesTest.java   
@Test
public void givenDateTypes_shouldSerialize() throws ParseException {

    /*
        {
          "date": "2017-12-25T00:00:00Z[UTC]",
          "dayOfWeek": "MONDAY",
          "localDate": "2017-12-25",
          "localDateTime": "2017-12-25T00:00:00",
          "offset": "+01:00",
          "offsetDateTime": "2017-12-25T00:00:00+01:00",
          "sixThirty": "23:00:00",
          "zoneId": "Europe/London",
          "zonedDateTime": "2017-12-25T00:00:00Z[Europe/London]"
        }
     */

    String expectedJson = "{\"date\":\"2017-12-25T00:00:00Z[UTC]\",\"dayOfWeek\":\"MONDAY\",\"localDate\":\"2017-12-25\",\"localDateTime\":\"2017-12-25T00:00:00\",\"offset\":\"+01:00\",\"offsetDateTime\":\"2017-12-25T00:00:00+01:00\",\"sixThirty\":\"23:00:00\",\"zoneId\":\"Europe/London\",\"zonedDateTime\":\"2017-12-25T00:00:00Z[Europe/London]\"}";
    String actualJson = JsonbBuilder.create().toJson(new AllDateTypes());
    assertThat(actualJson).isEqualTo(expectedJson);
}
项目:JSON-framework-comparison    文件:JsonProcessingTypesTest.java   
@Test
public void givenJsonProcessing_shouldSerialise(){

    /*
        {
          "jsonArray": [
            "Cat",
            "Dog"
          ],
          "jsonNumber": 100,
          "jsonObject": {
            "firstName": "Alex",
            "lastName": "Theedom"
          },
          "jsonString": "Flat",
          "jsonValue": "House"
        }
     */

    String expectedJson = "{\"jsonArray\":[\"Cat\",\"Dog\"],\"jsonNumber\":100,\"jsonObject\":{\"firstName\":\"Alex\",\"lastName\":\"Theedom\"},\"jsonString\":\"Flat\",\"jsonValue\":\"House\"}";
    String actualJson = JsonbBuilder.create().toJson(new JsonProcessingTypes());
    assertThat(actualJson).isEqualTo(expectedJson);
}
项目:JSON-framework-comparison    文件:FieldsVisibilityTest.java   
@Test
public void givenFieldVisibility_shouldSerialise() {
    /*
        {
          "defaultStringWithSetterGetter": "",
          "finalPrivateStringWithSetterGetter": "",
          "finalPublicString": "",
          "finalPublicStringWithSetterGetter": "",
          "privateStringWithSetterGetter": "",
          "protectedStringWithSetterGetter": "",
          "publicString": "",
          "publicStringWithSetterGetter": "",
          "virtualField": ""
        }
     */

    String expectedJson = "{\"defaultStringWithSetterGetter\":\"\",\"finalPrivateStringWithSetterGetter\":\"\",\"finalPublicString\":\"\",\"finalPublicStringWithSetterGetter\":\"\",\"privateStringWithSetterGetter\":\"\",\"protectedStringWithSetterGetter\":\"\",\"publicString\":\"\",\"publicStringWithSetterGetter\":\"\",\"virtualField\":\"\"}";
    String actualJson = JsonbBuilder.create().toJson(new FieldsVisibility());
    assertThat(actualJson).isEqualTo(expectedJson);
}
项目:JSON-framework-comparison    文件:RuntimeSamplerTest.java   
@Test
public void test_using_jsonbConfig() {
    String expectedJson = "\n" +
            "{\n" +
            "    \"string\": null,\n" +
            "    \"shortWrapper\": null,\n" +
            "    \"shortPrimitive\": null,\n" +
            "    \"longWrapper\": null,\n" +
            "    \"longPrimitive\": null,\n" +
            "    \"intWrapper\": null,\n" +
            "    \"intPrimitive\": null,\n" +
            "    \"floatWrapper\": null,\n" +
            "    \"floatPrimitive\": null,\n" +
            "    \"doubleWrapper\": null,\n" +
            "    \"doublePrimitive\": null,\n" +
            "    \"charWrapper\": null,\n" +
            "    \"charPrimitive\": null,\n" +
            "    \"byteWrapper\": null,\n" +
            "    \"bytePrimitive\": null,\n" +
            "    \"booleanWrapper\": null,\n" +
            "    \"aBoolean\": null\n" +
            "}";
    String actualJson = JsonbBuilder.create(RuntimeSampler.jsonbConfig()).toJson(new AllBasicTypes());
    assertThat(actualJson).isEqualTo(expectedJson);
}
项目:NGSI-LD_Wrapper    文件:MyResourceJson2.java   
/**
 * 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);
}
项目:DiavgeiaUtils    文件:DiavgeiaHttpUtils.java   
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;
}
项目:Java-EE-8-Sampler    文件:ComprehensiveExample.java   
public String serialiseMagazine() throws MalformedURLException {
    Magazine magazine = new Magazine();
    magazine.setId("ABCD-1234");
    magazine.setTitle("Fun with Java");
    magazine.setAuthor(new Author("Alex", "Theedom"));
    magazine.setPrice(45.00f);
    magazine.setPages(300);
    magazine.setInPrint(true);
    magazine.setBinding(Binding.SOFT_BACK);
    magazine.setLanguages(Arrays.asList("French", "English", "Spanish", null));
    magazine.setWebsite(new URL("https://www.readlearncode.com"));
    magazine.setInternalAuditCode("IN-675X-NF09"); // Only has setter method
    magazine.setPublished(LocalDate.parse("01/01/2018", DateTimeFormatter.ofPattern("MM/dd/yyyy")));
    magazine.setAlternativeTitle(null);
    return JsonbBuilder.create().toJson(magazine);
}
项目:Java-EE-8-Sampler    文件:MagazineSerializerTest.java   
@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);

}
项目:Java-EE-8-Sampler    文件:CustomisePropertyNamingStrategyTest.java   
@Test
public void givenIDENTITYStrategy_shouldNotChangeAnyPropertyName() {
    /*
        {
          "alternativetitle": "Fun with JSON-B",
          "authorName": {
            "firstName": "Alex",
            "lastName": "Theedom"
          },
          "title": "Fun with JSON binding"
        }
     */

    String expectedJson = "{\"alternativetitle\":\"Fun with JSON-B\",\"authorName\":{\"firstName\":\"Alex\",\"lastName\":\"Theedom\"},\"title\":\"Fun with JSON binding\"}";
    JsonbConfig jsonbConfig = new JsonbConfig()
            .withPropertyNamingStrategy(PropertyNamingStrategy.IDENTITY);

    String actualJson = JsonbBuilder.create(jsonbConfig).toJson(magazine);

    assertThat(actualJson).isEqualTo(expectedJson);
}
项目:Java-EE-8-Sampler    文件:CustomisePropertyNamingStrategyTest.java   
@Test
public void givenLOWER_CASE_WITH_DASHESStrategy_shouldDelimitPropertyNameWithDashes() {
    /*
        {
          "alternativetitle": "Fun with JSON-B",
          "author-name": {
            "first-name": "Alex",
            "last-name": "Theedom"
          },
          "title": "Fun with JSON binding"
        }
     */

    String expectedJson = "{\"alternativetitle\":\"Fun with JSON-B\",\"author-name\":{\"first-name\":\"Alex\",\"last-name\":\"Theedom\"},\"title\":\"Fun with JSON binding\"}";
    JsonbConfig jsonbConfig = new JsonbConfig()
            .withPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CASE_WITH_DASHES);

    String actualJson = JsonbBuilder.create(jsonbConfig).toJson(magazine);

    assertThat(actualJson).isEqualTo(expectedJson);
}
项目:Java-EE-8-Sampler    文件:CustomisePropertyNamingStrategyTest.java   
@Test
public void givenLOWER_CASE_WITH_DASHESStrategy_shouldDeserialiseCorrectly() {
    /*
        {
          "alternativetitle": "Fun with JSON-B",
          "author-name": {
            "first-name": "Alex",
            "last-name": "Theedom"
          },
          "title": "Fun with JSON binding"
        }
     */

    String expectedJson = "{\"alternativetitle\":\"Fun with JSON-B\",\"author-name\":{\"first-name\":\"Alex\",\"last-name\":\"Theedom\"},\"title\":\"Fun with JSON binding\"}";
    JsonbConfig jsonbConfig = new JsonbConfig()
            .withPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CASE_WITH_DASHES);

    Magazine magazine = JsonbBuilder.create(jsonbConfig).fromJson(expectedJson, Magazine.class);

    assertThat(magazine.getAlternativetitle()).isEqualTo("Fun with JSON-B");
    assertThat(magazine.getAuthorName().getFirstName()).isEqualTo("Alex");
    assertThat(magazine.getAuthorName().getLastName()).isEqualTo("Theedom");
    assertThat(magazine.getTitle()).isEqualTo("Fun with JSON binding");
}
项目:Java-EE-8-Sampler    文件:CustomisePropertyNamingStrategyTest.java   
@Test
public void givenLOWER_CASE_WITH_UNDERSCORESStrategy_shouldDelimitLowercasePropertyNameWithUnderscore() {
    /*
        {
          "alternativetitle": "Fun with JSON-B",
          "author_name": {
            "first_name": "Alex",
            "last_name": "Theedom"
          },
          "title": "Fun with JSON binding"
        }
     */

    String expectedJson = "{\"alternativetitle\":\"Fun with JSON-B\",\"author_name\":{\"first_name\":\"Alex\",\"last_name\":\"Theedom\"},\"title\":\"Fun with JSON binding\"}";
    JsonbConfig jsonbConfig = new JsonbConfig()
            .withPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CASE_WITH_UNDERSCORES);

    String actualJson = JsonbBuilder.create(jsonbConfig).toJson(magazine);

    assertThat(actualJson).isEqualTo(expectedJson);
}
项目:Java-EE-8-Sampler    文件:CustomisePropertyNamingStrategyTest.java   
@Test
public void givenUPPER_CAMEL_CASEStrategy_shouldDelimitLowercasePropertyNameWithUnderscore() {
    /*
        {
          "Alternativetitle": "Fun with JSON-B",
          "AuthorName": {
            "FirstName": "Alex",
            "LastName": "Theedom"
          },
          "Title": "Fun with JSON binding"
        }
     */

    String expectedJson = "{\"Alternativetitle\":\"Fun with JSON-B\",\"AuthorName\":{\"FirstName\":\"Alex\",\"LastName\":\"Theedom\"},\"Title\":\"Fun with JSON binding\"}";
    JsonbConfig jsonbConfig = new JsonbConfig()
            .withPropertyNamingStrategy(PropertyNamingStrategy.UPPER_CAMEL_CASE);

    String actualJson = JsonbBuilder.create(jsonbConfig).toJson(magazine);

    assertThat(actualJson).isEqualTo(expectedJson);
}
项目:Java-EE-8-Sampler    文件:CustomisePropertyNamingStrategyTest.java   
@Test
public void givenUPPER_CAMEL_CASE_WITH_SPACESStrategy_shouldDelimitLowercasePropertyNameWithUnderscore() {
    /*
        {
          "Alternativetitle": "Fun with JSON-B",
          "Author Name": {
            "First Name": "Alex",
            "Last Name": "Theedom"
          },
          "Title": "Fun with JSON binding"
        }
     */

    String expectedJson = "{\"Alternativetitle\":\"Fun with JSON-B\",\"Author Name\":{\"First Name\":\"Alex\",\"Last Name\":\"Theedom\"},\"Title\":\"Fun with JSON binding\"}";
    JsonbConfig jsonbConfig = new JsonbConfig()
            .withPropertyNamingStrategy(PropertyNamingStrategy.UPPER_CAMEL_CASE_WITH_SPACES);

    String actualJson = JsonbBuilder.create(jsonbConfig).toJson(magazine);

    assertThat(actualJson).isEqualTo(expectedJson);
}
项目:Java-EE-8-Sampler    文件:CustomisePropertyNamingStrategyTest.java   
@Test
public void givenCASE_INSENSITIVEStrategy_shouldDelimitLowercasePropertyNameWithUnderscore() {
    /*
        {
          "alternativetitle": "Fun with JSON-B",
          "authorName": {
            "firstName": "Alex",
            "lastName": "Theedom"
          },
          "title": "Fun with JSON binding"
        }
     */

    String expectedJson = "{\"alternativetitle\":\"Fun with JSON-B\",\"authorName\":{\"firstName\":\"Alex\",\"lastName\":\"Theedom\"},\"title\":\"Fun with JSON binding\"}";
    JsonbConfig jsonbConfig = new JsonbConfig()
            .withPropertyNamingStrategy(PropertyNamingStrategy.CASE_INSENSITIVE);

    String actualJson = JsonbBuilder.create(jsonbConfig).toJson(magazine);

    assertThat(actualJson).isEqualTo(expectedJson);
}
项目:Java-EE-8-Sampler    文件:CustomisePropertyOrderStrategyTest.java   
@Test
public void givenJsonbPropertyOrderSet_shouldOrderProperties() {
    /*
        {
          "id": "ABC-123-XYZ",
          "title": "Fun with JSON-B",
          "author": "Alex Theedom"
        }
     */

    String expectedJson = "{\"id\":\"ABC-123-XYZ\",\"title\":\"Fun with JSON-B\",\"author\":\"Alex Theedom\"}";
    Book book = new Book("ABC-123-XYZ", "Fun with JSON-B", "Alex Theedom");

    String actualJson = JsonbBuilder.create().toJson(book);

    assertThat(expectedJson).isEqualTo(actualJson);
}
项目:Java-EE-8-Sampler    文件:SimplestExampleTest.java   
@Test
public void givenBookObject_shouldSerialise() {
    String expectedJson = "{\"title\":\"Fun with Java\"}";

    Book book = new Book();
    book.title = "Fun with Java";

    String actualJson = JsonbBuilder.create().toJson(book);

    assertThat(actualJson).isEqualTo(expectedJson);

    /*
        {
          "title": "Fun with Java"
        }
     */
}
项目:Java-EE-8-Sampler    文件:BasicTypeExampleTest.java   
@Test
public void deserializeBook() {

    Book expectedBook = new Book();
    expectedBook.setTitle("Fun with Java");
    expectedBook.setFirstname("John");
    expectedBook.setMiddleInitial('J');
    expectedBook.setLastname("Smith");
    expectedBook.setPrice(59.99f);
    expectedBook.setInPrint(true);
    expectedBook.setPages(200);
    expectedBook.setVersion((byte) 5);
    expectedBook.setCount(new AtomicInteger(4));

    String json = "{\"count\":4,\"firstname\":\"John\",\"inPrint\":true,\"lastname\":\"Smith\",\"middleInitial\":\"J\",\"pages\":200,\"price\":59.99,\"title\":\"Fun with Java\",\"version\":5}";

    assertThatThrownBy(() -> JsonbBuilder.create().fromJson(json, Book.class))
            .isInstanceOf(IllegalArgumentException.class)
            .hasMessageContaining("argument type mismatch");

}
项目:scalable-coffee-shop    文件:EventSerializer.java   
@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);
    }
}
项目:scalable-coffee-shop    文件:EventSerializer.java   
@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);
    }
}
项目:scalable-coffee-shop    文件:EventSerializer.java   
@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);
    }
}
项目:DiavgeiaUtils    文件:DiavgeiaHttpUtils.java   
/**
 * 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;
}
项目:DiavgeiaUtils    文件:DiavgeiaHttpUtils.java   
/**
 * 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;
}
项目:DiavgeiaUtils    文件:DiavgeiaHttpUtils.java   
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;
}
项目:DiavgeiaUtils    文件:DiavgeiaHttpUtils.java   
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;
}
项目:DiavgeiaUtils    文件:DiavgeiaHttpUtils.java   
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;
}
项目:DiavgeiaUtils    文件:DiavgeiaHttpUtils.java   
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;
}
项目:DiavgeiaUtils    文件:DiavgeiaHttpUtils.java   
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;
}
项目:DiavgeiaUtils    文件:DiavgeiaHttpUtils.java   
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;
}
项目:JSON-framework-comparison    文件:CalendarTypeTest.java   
@Test
public void givenCalendarType_shouldSerialise() {

    /*
        {
          "calendar1": "2017-12-25Z",
          "calendar2": "2017-12-25T00:00:00Z[Europe/London]"
        }
     */

    String expectedJson = "{\"calendar1\":\"2017-12-25Z\",\"calendar2\":\"2017-12-25T00:00:00Z[Europe/London]\"}";
    String actualJson = JsonbBuilder.create().toJson(new CalendarType());
    assertThat(actualJson).isEqualTo(expectedJson);
}
项目:JSON-framework-comparison    文件:ArraysCollectionsTest.java   
@Test
public void givenArrayAndCollections_shouldSerialise() {

    /*
        {
          "intArray": [
            1,
            2,
            3,
            5
          ],
          "objectCollection": [
            "one",
            "two"
          ],
          "stringArray": [
            "one",
            "two"
          ],
          "stringIntegerMap": {
            "one": 1,
            "two": 2
          }
        }
     */

    String expectedJson = "{\"intArray\":[1,2,3,5],\"objectCollection\":[\"one\",\"two\"],\"stringArray\":[\"one\",\"two\"],\"stringIntegerMap\":{\"one\":1,\"two\":2}}";
    String actualJson = JsonbBuilder.create().toJson(new ArraysCollections());
    assertThat(actualJson).isEqualTo(expectedJson);
}
项目:JSON-framework-comparison    文件:EnumTypesTest.java   
@Test
public void givenEnum_shouldSerialise(){
    /*
    {
      "hard": "Hard",
      "soft": "SOFT"
    }
     */
    String expectedJson = "{\"hard\":\"Hard\",\"soft\":\"SOFT\"}";
    String actualJson = JsonbBuilder.create().toJson(new UseEnum());
    assertThat(actualJson).isEqualTo(expectedJson);
}
项目:JSON-framework-comparison    文件:InheritanceTest.java   
@Test
public void givenInheritance_shouldSerialise(){
    /*
        {
          "parentName": "Parent",
          "child": "Child"
        }
     */
    String expectedJson = "{\"parentName\":\"Parent\",\"child\":\"Child\"}";
    String actualJson = JsonbBuilder.create().toJson(new Child());
    assertThat(actualJson).isEqualTo(expectedJson);
}
项目:javaee8-jaxrs-sample    文件:UserMessageBodyWiter.java   
@Override
public void writeTo(User t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
    t.setPassword(null);
    JsonbConfig config = new JsonbConfig().withNullValues(false);
    JsonbBuilder.create(config)
        .toJson(t, entityStream);
}
项目:JSON-framework-comparison    文件:AllBasicTypesTest.java   
@Test
public void givenDefaultValues_shouldSerialise() {

    /*
    {
      "aBoolean": false,
      "booleanWrapper": false,
      "bytePrimitive": 0,
      "byteWrapper": 0,
      "charPrimitive": "\u0000",
      "charWrapper": "\u0000",
      "doublePrimitive": 0,
      "doubleWrapper": 0,
      "floatPrimitive": 0,
      "floatWrapper": 0,
      "intPrimitive": 0,
      "intWrapper": 0,
      "longPrimitive": 0,
      "longWrapper": 0,
      "shortPrimitive": 0,
      "shortWrapper": 0,
      "string": "Hello World"
    }
     */
    String expectedJson = "{\"aBoolean\":false,\"booleanWrapper\":false,\"bytePrimitive\":0,\"byteWrapper\":0,\"charPrimitive\":\"\\u0000\",\"charWrapper\":\"\\u0000\",\"doublePrimitive\":0.0,\"doubleWrapper\":0.0,\"floatPrimitive\":0.0,\"floatWrapper\":0.0,\"intPrimitive\":0,\"intWrapper\":0,\"longPrimitive\":0,\"longWrapper\":0,\"shortPrimitive\":0,\"shortWrapper\":0,\"string\":\"Hello World\"}";
    String actualJson = JsonbBuilder.create().toJson(new AllBasicTypes());
    assertThat(actualJson).isEqualTo(expectedJson);
}
项目:JSON-framework-comparison    文件:NullTreatmentTest.java   
@Test
public void givenNulls_shouldSerialise() {
    /*
    {
      "stringList": [
        null
      ]
    }
     */
    String expectedJson = "{\"stringList\":[null]}";
    String actualJson = JsonbBuilder.create().toJson(new NullTreatment());
    assertThat(actualJson).isEqualTo(expectedJson);
}
项目:NGSI-LD_Wrapper    文件:EntityResource.java   
/**
 * 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();
    }
}
项目:NGSI-LD_Wrapper    文件:EntityResource.java   
@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;
}
项目:Java-EE-8-Sampler    文件:JsonBindingExample.java   
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);
    }