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

项目: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);
}
项目: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);
}
项目: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);
    }
}
项目:yasson    文件:JsonBinding.java   
/**
 * Propagates properties from JsonbConfig to JSONP generator / parser factories.
 *
 * @param jsonbConfig jsonb config
 * @return properties for JSONP generator / parser
 */
protected Map<String, ?> createJsonpProperties(JsonbConfig jsonbConfig) {
    //JSONP 1.0 actually ignores the value, just checks the key is present. Only set if JsonbConfig.FORMATTING is true.
    final Optional<Object> property = jsonbConfig.getProperty(JsonbConfig.FORMATTING);
    final Map<String, Object> factoryProperties = new HashMap<>();
    if (property.isPresent()) {
        final Object value = property.get();
        if (!(value instanceof Boolean)) {
            throw new JsonbException(Messages.getMessage(MessageKeys.JSONB_CONFIG_FORMATTING_ILLEGAL_VALUE));
        }
        if ((Boolean) value) {
            factoryProperties.put(JsonGenerator.PRETTY_PRINTING, Boolean.TRUE);
        }
        return factoryProperties;
    }
    return factoryProperties;
}
项目:yasson    文件:JsonbConfigProperties.java   
private PropOrderStrategy initOrderStrategy() {
    final Optional<Object> property = jsonbConfig.getProperty(JsonbConfig.PROPERTY_ORDER_STRATEGY);
    if (property.isPresent()) {
        final Object strategy = property.get();
        if (!(strategy instanceof String)) {
            throw new JsonbException(Messages.getMessage(MessageKeys.PROPERTY_ORDER, strategy));
        }
        switch ((String) strategy) {
            case PropertyOrderStrategy.LEXICOGRAPHICAL:
                return new LexicographicalOrderStrategy();
            case PropertyOrderStrategy.REVERSE:
                return new ReverseOrderStrategy();
            case PropertyOrderStrategy.ANY:
                return new AnyOrderStrategy();
            default:
                throw new JsonbException(Messages.getMessage(MessageKeys.PROPERTY_ORDER, strategy));
        }
    }
    //default by spec
    return new LexicographicalOrderStrategy();
}
项目:yasson    文件:JsonbConfigProperties.java   
private PropertyNamingStrategy initPropertyNamingStrategy() {
    final Optional<Object> property = jsonbConfig.getProperty(JsonbConfig.PROPERTY_NAMING_STRATEGY);
    if (!property.isPresent()) {
        return new IdentityStrategy();
    }
    Object propertyNamingStrategy = property.get();
    if (propertyNamingStrategy instanceof String) {
        String namingStrategyName = (String) propertyNamingStrategy;
        final PropertyNamingStrategy foundNamingStrategy = DefaultNamingStrategies.getStrategy(namingStrategyName);
        if (foundNamingStrategy == null) {
            throw new JsonbException("No property naming strategy was found for: " + namingStrategyName);
        }
        return foundNamingStrategy;
    }
    if (!(propertyNamingStrategy instanceof PropertyNamingStrategy)) {
        throw new JsonbException(Messages.getMessage(MessageKeys.PROPERTY_NAMING_STRATEGY_INVALID));
    }
    return (PropertyNamingStrategy) property.get();
}
项目:yasson    文件:ComponentMatcher.java   
/**
 * Called during context creation, introspecting user components provided with JsonbConfig.
 */
void init() {
    final JsonbSerializer<?>[] serializers = (JsonbSerializer<?>[])jsonbContext.getConfig().getProperty(JsonbConfig.SERIALIZERS).orElseGet(()->new JsonbSerializer<?>[]{});
    for (JsonbSerializer serializer : serializers) {
        SerializerBinding serializerBinding = introspectSerializerBinding(serializer.getClass(), serializer);
        addSerializer(serializerBinding.getBindingType(), serializerBinding);
    }
    final JsonbDeserializer<?>[] deserializers = (JsonbDeserializer<?>[])jsonbContext.getConfig().getProperty(JsonbConfig.DESERIALIZERS).orElseGet(()->new JsonbDeserializer<?>[]{});
    for (JsonbDeserializer deserializer : deserializers) {
        DeserializerBinding deserializerBinding = introspectDeserializerBinding(deserializer.getClass(), deserializer);
        addDeserializer(deserializerBinding.getBindingType(), deserializerBinding);
    }

    final JsonbAdapter<?, ?>[] adapters = (JsonbAdapter<?, ?>[]) jsonbContext.getConfig().getProperty(JsonbConfig.ADAPTERS).orElseGet(()->new JsonbAdapter<?, ?>[]{});
    for (JsonbAdapter<?, ?> adapter : adapters) {
        AdapterBinding adapterBinding = introspectAdapterBinding(adapter.getClass(), adapter);
        addAdapter(adapterBinding.getBindingType(), adapterBinding);
    }
}
项目:yasson    文件:JsonbPropertyTest.java   
/**
 * 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;
        }
    }
}
项目:yasson    文件:JsonbPropertyTest.java   
/**
 * 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;
        }
    }

}
项目:yasson    文件:JsonbPropertyVisibilityStrategyTest.java   
/**
 * 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));
}
项目:yasson    文件:JsonbPropertyVisibilityStrategyTest.java   
/**
 * 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));
}
项目:yasson    文件:DatesTest.java   
@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());
}
项目:yasson    文件:DatesTest.java   
@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"));
}
项目:yasson    文件:SecurityManagerTest.java   
@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);
}
项目:yasson    文件:PolymorphicAdapterTest.java   
@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);
}
项目:yasson    文件:AdaptersTest.java   
@Test
public void testValueFieldAdapter() throws Exception {
    JsonbAdapter<?, ?>[] adapters = {
            new JsonbAdapter<Integer, String>() {
                @Override
                public String adaptToJson(Integer integer) {
                    return String.valueOf(integer);
                }

                @Override
                public Integer adaptFromJson(String s) {
                    return Integer.parseInt(s);
                }
            }
    };
    jsonb = JsonbBuilder.create(new JsonbConfig().setProperty(JsonbConfig.ADAPTERS, adapters));

    AdaptedPojo pojo = new AdaptedPojo();
    pojo.intField = 11;
    String json = jsonb.toJson(pojo);
    assertEquals("{\"intField\":\"11\"}", json);

    AdaptedPojo<?> result = jsonb.fromJson("{\"intField\":\"10\"}", AdaptedPojo.class);
    assertEquals(Integer.valueOf(10), result.intField);
}
项目:yasson    文件:AdaptersTest.java   
@Test
public void testStringToGenericCollectionAdapter() throws Exception {

    JsonbAdapter<?, ?>[] adapters = {new IntegerListToStringAdapter()};
    jsonb = JsonbBuilder.create(new JsonbConfig().setProperty(JsonbConfig.ADAPTERS, adapters));

    AdaptedPojo<List<Integer>> pojo = new AdaptedPojo<>();
    pojo.tVar = Arrays.asList(11, 22, 33);
    pojo.integerList = Arrays.asList(110, 111, 101);
    String marshalledJson = jsonb.toJson(pojo, new TestTypeToken<AdaptedPojo<List<Integer>>>(){}.getType());
    assertEquals("{\"integerList\":\"110#111#101\"," +
            "\"tVar\":\"11#22#33\"}", marshalledJson);

    String toUnmarshall = "{\"integerList\":\"11#22#33#44\",\"stringList\":[\"first\",\"second\"]," +
            "\"tVar\":\"110#111#101\"}";

    AdaptedPojo result = jsonb.fromJson(toUnmarshall, new TestTypeToken<AdaptedPojo<List<Integer>>>(){}.getType());
    List<Integer> expectedIntegerList = Arrays.asList(11, 22, 33, 44);
    List<String> expectedStringList = Arrays.asList("first", "second");
    List<Integer> expectedTList = Arrays.asList(110, 111, 101);

    assertEquals(expectedIntegerList, result.integerList);
    assertEquals(expectedStringList, result.stringList);
    assertEquals(expectedTList, result.tVar);
}
项目:yasson    文件:AdaptersTest.java   
@Test
public void testAdaptObjectInCollection() throws Exception {
    JsonbAdapter<?, ?>[] adapters = {new BoxToCrateCompatibleGenericsAdapter<Integer>() {
    }};
    jsonb = JsonbBuilder.create(new JsonbConfig().setProperty(JsonbConfig.ADAPTERS, adapters));

    AdaptedPojo<Integer> pojo = new AdaptedPojo<>();

    pojo.tGenericBoxList = new ArrayList<>();
    pojo.tGenericBoxList.add(new GenericBox<>("GEN_BOX_STR_1", 110));
    pojo.tGenericBoxList.add(new GenericBox<>("GEN_BOX_STR_2", 101));

    String marshalledJson = jsonb.toJson(pojo, new TestTypeToken<AdaptedPojo<Integer>>(){}.getType());
    assertEquals("{\"tGenericBoxList\":[{\"adaptedT\":110,\"crateStrField\":\"GEN_BOX_STR_1\"},{\"adaptedT\":101,\"crateStrField\":\"GEN_BOX_STR_2\"}]}", marshalledJson);

    String toUnmarshall = "{\"integerList\":[11,22,33,44],\"stringList\":[\"first\",\"second\"]," +
            "\"tGenericBoxList\":[{\"crateStrField\":\"FirstCrate\",\"adaptedT\":11},{\"crateStrField\":\"SecondCrate\",\"adaptedT\":22}]}";

    AdaptedPojo<Integer> result = jsonb.fromJson(toUnmarshall, new TestTypeToken<AdaptedPojo<Integer>>(){}.getType());
    assertEquals("FirstCrate", result.tGenericBoxList.get(0).getStrField());
    assertEquals("SecondCrate", result.tGenericBoxList.get(1).getStrField());
    assertEquals(Integer.valueOf(11), result.tGenericBoxList.get(0).getX());
    assertEquals(Integer.valueOf(22), result.tGenericBoxList.get(1).getX());
}
项目:yasson    文件:AdaptersTest.java   
@Test
public void testAdaptRoot() throws Exception {

    JsonbAdapter<?, ?>[] adapters = {new JsonbAdapter<Box, Crate>() {
        @Override
        public Crate adaptToJson(Box box) {
            return new Crate(box.getBoxStrField(), box.getBoxIntegerField());
        }

        @Override
        public Box adaptFromJson(Crate crate) {
            return new Box(crate.getCrateStrField(), crate.getCrateIntField());
        }
    }};
    jsonb = JsonbBuilder.create(new JsonbConfig().setProperty(JsonbConfig.ADAPTERS, adapters));

    Box pojo = new Box("BOX_STR", 101);
    String marshalledJson = jsonb.toJson(pojo);
    assertEquals("{\"crateIntField\":101,\"crateStrField\":\"BOX_STR\"}", marshalledJson);

    Box result = jsonb.fromJson("{\"crateIntField\":110,\"crateStrField\":\"CRATE_STR\"}", Box.class);
    assertEquals("CRATE_STR", result.getBoxStrField());
    assertEquals(Integer.valueOf(110), result.getBoxIntegerField());
}
项目:yasson    文件:PropertyNamingStrategyTest.java   
@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);

}
项目:yasson    文件:CdiInjectionTest.java   
@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);
}
项目:yasson    文件:SerializersTest.java   
/**
 * 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);

}
项目:yasson    文件:SerializersTest.java   
/**
 * 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);
}
项目:johnzon    文件:AdapterTest.java   
@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);
}
项目:JSON-framework-comparison    文件:RuntimeSampler.java   
public static JsonbConfig jsonbConfig() {
    return new JsonbConfig()

            // Property visibility
            .withNullValues(true)
            .withPropertyVisibilityStrategy(new PropertyVisibilityStrategy() {
                @Override
                public boolean isVisible(Field field) {
                    return false;
                }

                @Override
                public boolean isVisible(Method method) {
                    return false;
                }
            })

            // Property naming and order
            .withPropertyNamingStrategy(PropertyNamingStrategy.CASE_INSENSITIVE)
            .withPropertyOrderStrategy(PropertyOrderStrategy.REVERSE)

            // Customised de/serializers
            .withAdapters(new ClassAdapter())
            .withDeserializers(new CustomDeserializer())
            .withSerializers(new CustomSerializer())

            // Formats, locals, encoding, binary data
            .withBinaryDataStrategy(BinaryDataStrategy.BASE_64_URL)
            .withDateFormat("MM/dd/yyyy", Locale.ENGLISH)
            .withLocale(Locale.CANADA)
            .withEncoding("UTF-8")
            .withStrictIJSON(true)
            .withFormatting(true);
}
项目: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);
    }
项目:Java-EE-8-Sampler    文件:JsonBindingExample.java   
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);
    }
项目:Java-EE-8-Sampler    文件:BookletAdapterTest.java   
@Test
public void givenJSON_shouldUseAdapterToDeserialise() {
    String actualJson = "{\"title\":\"Fun with Java\",\"firstName\":\"Alex\",\"lastName\":\"Theedom\"}";
    Booklet actualBooklet = new Booklet("Fun with Java", "Alex", "Theedom");
    JsonbConfig config = new JsonbConfig().withAdapters(new BookletAdapter());
    Booklet expectedBooklet = JsonbBuilder.create(config).fromJson(actualJson, Booklet.class);

    assertThat(actualBooklet).isEqualTo(expectedBooklet);
}
项目:Java-EE-8-Sampler    文件:BookletAdapterTest.java   
@Test
public void givenBookObject_shouldUseAdapterToSerialise() {
    String expectedJson = "{\"title\":\"Fun with Java\",\"firstName\":\"Alex\",\"lastName\":\"Theedom\"}";
    Booklet booklet = new Booklet("Fun with Java", "Alex", "Theedom");
    JsonbConfig config = new JsonbConfig().withAdapters(new BookletAdapter());
    String actualJson = JsonbBuilder.create(config).toJson(booklet);

    assertThat(actualJson).isEqualTo(expectedJson);
}