// [JACKSON-597]
 public void testClass() throws IOException {
   ObjectMapper mapper = new ObjectMapper();
   assertEquals(quote("java.lang.String"), mapper.writeValueAsString(String.class));
   assertEquals(quote("int"), mapper.writeValueAsString(Integer.TYPE));
   assertEquals(quote("boolean"), mapper.writeValueAsString(Boolean.TYPE));
   assertEquals(quote("void"), mapper.writeValueAsString(Void.TYPE));
 }
  // [JACKSON-684]
  public void testAsIndex() throws Exception {
    // By default, serialize using name
    ObjectMapper m = new ObjectMapper();
    assertFalse(m.isEnabled(SerializationFeature.WRITE_ENUMS_USING_INDEX));
    assertEquals(quote("B"), m.writeValueAsString(TestEnum.B));

    // but we can change (dynamically, too!) it to be number-based
    m.enable(SerializationFeature.WRITE_ENUMS_USING_INDEX);
    assertEquals("1", m.writeValueAsString(TestEnum.B));
  }
 // [JACKSON-212]
 public void testToStringEnumWithEnumMap() throws Exception {
   ObjectMapper m = new ObjectMapper();
   m.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);
   EnumMap<LowerCaseEnum, String> enums = new EnumMap<LowerCaseEnum, String>(LowerCaseEnum.class);
   enums.put(LowerCaseEnum.C, "value");
   assertEquals("{\"c\":\"value\"}", m.writeValueAsString(enums));
 }
 // [databind#601]
 public void testEnumsWithJsonValueInMap() throws Exception {
   EnumMap<EnumWithJsonValue, String> input =
       new EnumMap<EnumWithJsonValue, String>(EnumWithJsonValue.class);
   input.put(EnumWithJsonValue.B, "x");
   assertEquals(
       "{\"" + EnumWithJsonValue.B.toString() + "\":\"x\"}", mapper.writeValueAsString(input));
 }
 // [Issue#227]
 public void testGenericEnumSerializer() throws Exception {
   // By default, serialize using name
   ObjectMapper m = new ObjectMapper();
   SimpleModule module = new SimpleModule("foobar");
   module.addSerializer(Enum.class, new LowerCasingEnumSerializer());
   m.registerModule(module);
   assertEquals(quote("b"), m.writeValueAsString(TestEnum.B));
 }
示例#6
0
 /**
  * @param Will be JSON-encoded.
  * @return the view query for chained calls
  */
 public ViewQuery endKey(Object o) {
   reset();
   try {
     endKey = mapper.writeValueAsString(o);
   } catch (Exception e) {
     throw Exceptions.propagate(e);
   }
   return this;
 }
  // [JACKSON-212]
  public void testToStringEnum() throws Exception {
    ObjectMapper m = new ObjectMapper();
    m.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);
    assertEquals("\"b\"", m.writeValueAsString(LowerCaseEnum.B));

    // [databind#749] but should also be able to dynamically disable
    assertEquals(
        "\"B\"",
        m.writer()
            .without(SerializationFeature.WRITE_ENUMS_USING_TO_STRING)
            .writeValueAsString(LowerCaseEnum.B));
  }
示例#8
0
 public String toJson(ObjectMapper mapper) {
   ObjectNode rootNode = mapper.createObjectNode();
   ArrayNode keysNode = rootNode.putArray("keys");
   for (Object key : keys) {
     keysNode.addPOJO(key);
   }
   try {
     return mapper.writeValueAsString(rootNode);
   } catch (Exception e) {
     throw Exceptions.propagate(e);
   }
 }
  @SuppressWarnings("hiding")
  public void testJackson703() throws Exception {
    // note: need a separate mapper, need to reconfigure
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(MapperFeature.USE_ANNOTATIONS, false);
    BasicBeanDescription beanDesc =
        mapper.getSerializationConfig().introspect(mapper.constructType(Jackson703.class));
    assertNotNull(beanDesc);

    Jackson703 bean = new Jackson703();
    String json = mapper.writeValueAsString(bean);
    assertNotNull(json);
  }
示例#10
0
  /**
   * Simple test to verify that byte[] values can be handled properly when converting, as long as
   * there is metadata (from POJO definitions).
   */
  public void testIssue709() throws Exception {
    byte[] inputData = new byte[] {1, 2, 3};
    ObjectNode node = MAPPER.createObjectNode();
    node.put("data", inputData);
    Issue709Bean result = MAPPER.treeToValue(node, Issue709Bean.class);
    String json = MAPPER.writeValueAsString(node);
    Issue709Bean resultFromString = MAPPER.readValue(json, Issue709Bean.class);
    Issue709Bean resultFromConvert = MAPPER.convertValue(node, Issue709Bean.class);

    // all methods should work equally well:
    Assert.assertArrayEquals(inputData, resultFromString.data);
    Assert.assertArrayEquals(inputData, resultFromConvert.data);
    Assert.assertArrayEquals(inputData, result.data);
  }
  // [databind#938]
  public void testRecursivePair() throws Exception {
    JavaType t = MAPPER.constructType(ImmutablePair.class);

    assertNotNull(t);
    assertEquals(ImmutablePair.class, t.getRawClass());

    List<ImmutablePair<String, Double>> list = new ArrayList<ImmutablePair<String, Double>>();
    list.add(ImmutablePair.of("Hello World!", 123d));
    String json = MAPPER.writeValueAsString(list);

    assertNotNull(json);

    // can not deserialize with current definition, however
  }
  /** tests getting serializer/deserializer instances. */
  public void testSerializeDeserializeWithJaxbAnnotations() throws Exception {
    ObjectMapper mapper = getJaxbMapper();
    // test expects that wrapper name be used...
    mapper.enable(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME);

    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    JaxbExample ex = new JaxbExample();
    QName qname = new QName("urn:hi", "hello");
    ex.setQname(qname);
    QName qname1 = new QName("urn:hi", "hello1");
    ex.setQname1(qname1);
    ex.setAttributeProperty("attributeValue");
    ex.setElementProperty("elementValue");
    ex.setWrappedElementProperty(Arrays.asList("wrappedElementValue"));
    ex.setEnumProperty(EnumExample.VALUE1);
    ex.setPropertyToIgnore("ignored");
    String json = mapper.writeValueAsString(ex);

    // uncomment to see what the JSON looks like.
    // System.out.println(json);

    // make sure the json is written out correctly.
    JsonNode node = mapper.readValue(json, JsonNode.class);
    assertEquals(qname.toString(), node.get("qname").asText());
    JsonNode attr = node.get("myattribute");
    assertNotNull(attr);
    assertEquals("attributeValue", attr.asText());
    assertEquals("elementValue", node.get("myelement").asText());
    assertTrue(node.has("mywrapped"));
    assertEquals(1, node.get("mywrapped").size());
    assertEquals("wrappedElementValue", node.get("mywrapped").get(0).asText());
    assertEquals("Value One", node.get("enumProperty").asText());
    assertNull(node.get("propertyToIgnore"));

    // now make sure it gets deserialized correctly.
    JaxbExample readEx = mapper.readValue(json, JaxbExample.class);
    assertEquals(ex.qname, readEx.qname);
    assertEquals(ex.qname1, readEx.qname1);
    assertEquals(ex.attributeProperty, readEx.attributeProperty);
    assertEquals(ex.elementProperty, readEx.elementProperty);
    assertEquals(ex.wrappedElementProperty, readEx.wrappedElementProperty);
    assertEquals(ex.enumProperty, readEx.enumProperty);
    assertNull(readEx.propertyToIgnore);
  }
示例#13
0
  public void testJackson428() throws Exception {
    ObjectMapper serMapper = new ObjectMapper();

    TypeResolverBuilder<?> serializerTyper =
        new ObjectMapper.DefaultTypeResolverBuilder(ObjectMapper.DefaultTyping.NON_FINAL);
    serializerTyper = serializerTyper.init(JsonTypeInfo.Id.NAME, createTypeNameIdResolver(true));
    serializerTyper = serializerTyper.inclusion(JsonTypeInfo.As.PROPERTY);
    serMapper.setDefaultTyping(serializerTyper);

    // Let's start by constructing something to serialize first
    MapHolder holder = new MapHolder();
    holder.map = new HashMap<MapKey, List<Object>>();
    List<Object> ints = new ArrayList<Object>();
    ints.add(Integer.valueOf(3));
    holder.map.put(new MapKey("key"), ints);
    String json = serMapper.writeValueAsString(holder);

    // Then deserialize: need separate mapper to initialize type id resolver appropriately
    ObjectMapper deserMapper = new ObjectMapper();
    TypeResolverBuilder<?> deserializerTyper =
        new ObjectMapper.DefaultTypeResolverBuilder(ObjectMapper.DefaultTyping.NON_FINAL);
    deserializerTyper =
        deserializerTyper.init(JsonTypeInfo.Id.NAME, createTypeNameIdResolver(false));
    deserializerTyper = deserializerTyper.inclusion(JsonTypeInfo.As.PROPERTY);
    deserMapper.setDefaultTyping(deserializerTyper);

    MapHolder result = deserMapper.readValue(json, MapHolder.class);
    assertNotNull(result);
    Map<?, ?> map = result.map;
    assertEquals(1, map.size());
    Map.Entry<?, ?> entry = map.entrySet().iterator().next();
    Object key = entry.getKey();
    assertEquals(MapKey.class, key.getClass());
    Object value = entry.getValue();
    assertTrue(value instanceof List<?>);
    List<?> list = (List<?>) value;
    assertEquals(1, list.size());
    assertEquals(Integer.class, list.get(0).getClass());
    assertEquals(Integer.valueOf(3), list.get(0));
  }
  public static void main(String[] args) throws Exception {
    Bean bean = new Bean("mr bean", "goofy", "secret!");
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializerFactory(new CustomBeanFactory());

    // First, without enabling view handling:
    System.out.println("With default serializer: " + mapper.writeValueAsString(bean));

    // Then with customized view-handling
    /* note: View class being passed is irrelevant since we customize handling)
     * Also: setting view would not be necessary if we just completely
     * overrode handling (we didn't, mostly to show more flexible
     * approach: conceivably you could have another way for passing
     * your own view id system, using ThreadLocal or some other
     * configurable part of <code>SerializationConfig</code> or
     * <code>SerializerProvider</code>)
     */
    /* note: if we wanted use 'writeValueAsString', would have to call
     * 'mapper.getSerializationConfig().setSerializationView(...)' first
     */
    String json = mapper.viewWriter(String.class).writeValueAsString(bean);
    System.out.println("With custom serializer: " + json);
  }
 // Test [JACKSON-214]
 public void testSubclassedEnums() throws Exception {
   assertEquals("\"B\"", mapper.writeValueAsString(EnumWithSubClass.B));
 }
 public void testEnumsWithJsonValue() throws Exception {
   assertEquals("\"bar\"", mapper.writeValueAsString(EnumWithJsonValue.B));
 }
 public void testIgnoreViaOnlyProps() throws Exception {
   assertEquals("{\"value\":{\"x\":1}}", MAPPER.writeValueAsString(new WrapperWithPropIgnore()));
 }
 // [JACKSON-757]
 public void testAnnotationsOnEnumCtor() throws Exception {
   assertEquals(quote("V1"), mapper.writeValueAsString(OK.V1));
   assertEquals(quote("V1"), mapper.writeValueAsString(NOT_OK.V1));
   assertEquals(quote("V2"), mapper.writeValueAsString(NOT_OK2.V2));
 }
 public void testIgnoreViaPropsAndClass() throws Exception {
   assertEquals("{\"value\":{\"y\":2}}", MAPPER.writeValueAsString(new WrapperWithPropIgnore2()));
 }
 // [databind#594]
 public void testJsonValueForEnumMapKey() throws Exception {
   assertEquals(
       aposToQuotes("{'stuff':{'longValue':'foo'}}"),
       mapper.writeValueAsString(new MyStuff594("foo")));
 }
 // [databind#661]
 public void testCustomEnumMapKeySerializer() throws Exception {
   String json = mapper.writeValueAsString(new MyBean661("abc"));
   assertEquals(aposToQuotes("{'X-FOO':'abc'}"), json);
 }
 public void testEnumsWithJsonValueUsingMixin() throws Exception {
   // can't share, as new mix-ins are added
   ObjectMapper m = new ObjectMapper();
   m.addMixIn(TestEnum.class, ToStringMixin.class);
   assertEquals("\"b\"", m.writeValueAsString(TestEnum.B));
 }
 public void testOverrideEnumAsNumber() throws Exception {
   assertEquals("{\"value\":1}", mapper.writeValueAsString(new PoOverrideAsNumber()));
 }
 // As of 2.5, use of Shape.ARRAY is legal alias for "write as number"
 public void testEnumAsObjectBroken() throws Exception {
   assertEquals("0", mapper.writeValueAsString(PoAsArray.A));
 }
 /**
  * Test for ensuring that @JsonSerializable is used with Enum types as well as with any other
  * types.
  */
 public void testSerializableEnum() throws Exception {
   assertEquals("\"foo\"", mapper.writeValueAsString(SerializableEnum.A));
 }
 public void testEnumAsObjectValid() throws Exception {
   assertEquals("{\"value\":\"a1\"}", mapper.writeValueAsString(PoNUM.A));
 }
 public void testSimple() throws Exception {
   assertEquals("\"B\"", mapper.writeValueAsString(TestEnum.B));
 }
 public void testIgnoreWithMapProperty() throws Exception {
   assertEquals("{\"value\":{\"b\":2}}", MAPPER.writeValueAsString(new MapWrapper()));
 }
 public void testEnumAsIndexViaAnnotations() throws Exception {
   assertEquals("{\"text\":0}", mapper.writeValueAsString(new PoNUMContainer()));
 }
 // [JACKSON-576]
 public void testMapWithEnumKeys() throws Exception {
   MapBean bean = new MapBean();
   bean.add(TestEnum.B, 3);
   String json = mapper.writeValueAsString(bean);
   assertEquals("{\"map\":{\"b\":3}}", json);
 }