/** Unit test to check for regression of [JACKSON-18]. */
  public void testSmallNumbers() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    ArrayNode root = mapper.createArrayNode();
    for (int i = -20; i <= 20; ++i) {
      JsonNode n = root.numberNode(i);
      root.add(n);
      // Hmmh. Not sure why toString() won't be triggered otherwise...
      assertEquals(String.valueOf(i), n.toString());
    }

    // Loop over 2 different serialization methods
    for (int type = 0; type < 2; ++type) {
      StringWriter sw = new StringWriter();
      if (type == 0) {
        JsonGenerator gen = new JsonFactory().createGenerator(sw);
        root.serialize(gen, null);
        gen.close();
      } else {
        mapper.writeValue(sw, root);
      }

      String doc = sw.toString();
      JsonParser p = new JsonFactory().createParser(new StringReader(doc));

      assertEquals(JsonToken.START_ARRAY, p.nextToken());
      for (int i = -20; i <= 20; ++i) {
        assertEquals(JsonToken.VALUE_NUMBER_INT, p.nextToken());
        assertEquals(i, p.getIntValue());
        assertEquals("" + i, p.getText());
      }
      assertEquals(JsonToken.END_ARRAY, p.nextToken());
      p.close();
    }
  }
 // [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));
 }
  public void testFromMap() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode root = mapper.createObjectNode();
    root.put(FIELD4, TEXT2);
    root.put(FIELD3, -1);
    root.putArray(FIELD2);
    root.put(FIELD1, DOUBLE_VALUE);

    /* Let's serialize using one of two alternate methods:
     * first preferred (using generator)
     * (there are 2 variants here too)
     */
    for (int i = 0; i < 2; ++i) {
      StringWriter sw = new StringWriter();
      if (i == 0) {
        JsonGenerator gen = new JsonFactory().createGenerator(sw);
        root.serialize(gen, null);
        gen.close();
      } else {
        mapper.writeValue(sw, root);
      }
      verifyFromMap(sw.toString());
    }

    // And then convenient but less efficient alternative:
    verifyFromMap(root.toString());
  }
  public void testFromArray() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    ArrayNode root = mapper.createArrayNode();
    root.add(TEXT1);
    root.add(3);
    ObjectNode obj = root.addObject();
    obj.put(FIELD1, true);
    obj.putArray(FIELD2);
    root.add(false);

    /* Ok, ready... let's serialize using one of two alternate
     * methods: first preferred (using generator)
     * (there are 2 variants here too)
     */
    for (int i = 0; i < 2; ++i) {
      StringWriter sw = new StringWriter();
      if (i == 0) {
        JsonGenerator gen = new JsonFactory().createGenerator(sw);
        root.serialize(gen, null);
        gen.close();
      } else {
        mapper.writeValue(sw, root);
      }
      verifyFromArray(sw.toString());
    }

    // And then convenient but less efficient alternative:
    verifyFromArray(root.toString());
  }
 // [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));
 }
  // [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));
  }
Пример #7
0
 // Test for [JACKSON-554]
 public void testTreeToValue() throws Exception {
   String JSON = "{\"leaf\":{\"value\":13}}";
   ObjectMapper mapper = new ObjectMapper();
   mapper.addMixInAnnotations(Leaf.class, LeafMixIn.class);
   JsonNode root = mapper.readTree(JSON);
   // Ok, try converting to bean using two mechanisms
   Root r1 = mapper.treeToValue(root, Root.class);
   assertNotNull(r1);
   assertEquals(13, r1.leaf.value);
 }
Пример #8
0
 // [Issue#232]
 public void testBigDecimalAsPlainStringTreeConversion() throws Exception {
   ObjectMapper mapper = new ObjectMapper();
   mapper.enable(SerializationFeature.WRITE_BIGDECIMAL_AS_PLAIN);
   Map<String, Object> map = new HashMap<String, Object>();
   String PI_STR = "3.00000000";
   map.put("pi", new BigDecimal(PI_STR));
   JsonNode tree = mapper.valueToTree(map);
   assertNotNull(tree);
   assertEquals(1, tree.size());
   assertTrue(tree.has("pi"));
 }
  // [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));
  }
Пример #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#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));
 }
Пример #12
0
 public static String toJson(Object value) {
   try {
     return OBJECT_MAPPER.writer().writeValueAsString(value);
   } catch (JsonProcessingException e) {
     throw new IllegalArgumentException("Unable to serialize to json", e);
   }
 }
  public void testBinary() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    final int LENGTH = 13045;
    byte[] data = new byte[LENGTH];
    for (int i = 0; i < LENGTH; ++i) {
      data[i] = (byte) i;
    }
    StringWriter sw = new StringWriter();
    mapper.writeValue(sw, BinaryNode.valueOf(data));

    JsonParser p = new JsonFactory().createParser(sw.toString());
    // note: can't determine it's binary from json alone:
    assertToken(JsonToken.VALUE_STRING, p.nextToken());
    assertArrayEquals(data, p.getBinaryValue());
    p.close();
  }
Пример #14
0
 public static <T> T fromJson(String json, Class<T> type) {
   try {
     return OBJECT_MAPPER.readValue(json, type);
   } catch (IOException e) {
     throw new IllegalArgumentException("Unable to parse json", e);
   }
 }
Пример #15
0
 public static byte[] toByteArray(Object value) {
   try {
     return OBJECT_MAPPER.writer().writeValueAsBytes(value);
   } catch (JsonProcessingException e) {
     throw new IllegalArgumentException("Unable to serialize to json", e);
   }
 }
Пример #16
0
  @Override
  public Record deserialize(InputStream in) throws RecordSerializationException {

    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    module.addDeserializer(Record.class, new EventDeserializer());
    mapper.registerModule(module);

    Record record = null;
    try {
      record = mapper.readValue(in, Record.class);
    } catch (IOException e) {
      e.printStackTrace();
    }

    return record;
  }
Пример #17
0
 public void testEmbeddedObject() throws Exception {
   TokenBuffer buf = new TokenBuffer(MAPPER);
   buf.writeObject(new byte[3]);
   JsonNode node = MAPPER.readTree(buf.asParser());
   buf.close();
   assertTrue(node.isBinary());
   byte[] data = node.binaryValue();
   assertNotNull(data);
   assertEquals(3, data.length);
 }
Пример #18
0
 public void testEmbeddedObjectInArray() throws Exception {
   TokenBuffer buf = new TokenBuffer(MAPPER);
   buf.writeStartArray();
   buf.writeObject(MARKER);
   buf.writeEndArray();
   JsonNode node = MAPPER.readTree(buf.asParser());
   buf.close();
   assertTrue(node.isArray());
   assertEquals(1, node.size());
   JsonNode n = node.get(0);
   assertTrue(n.isPojo());
   assertSame(MARKER, ((POJONode) n).getPojo());
 }
Пример #19
0
  @Override
  public void serialize(OutputStream out, Record record) throws RecordSerializationException {

    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    module.addSerializer(StandardRecord.class, new EventSerializer());
    mapper.registerModule(module);

    // map json to student

    try {
      mapper.enable(SerializationFeature.INDENT_OUTPUT);
      mapper.setPropertyNamingStrategy(
          PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
      String jsonString = mapper.writeValueAsString(record);

      out.write(jsonString.getBytes());
      out.flush();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  public static void main(String[] args) throws Exception {
    if (args.length != 1) {
      System.err.println("Usage: java [input]");
      System.exit(1);
    }
    byte[] data = readAll(args[0]);

    JsonFactory f = new JsonFactory();
    boolean doIntern = true;

    f.configure(JsonFactory.Feature.CANONICALIZE_FIELD_NAMES, doIntern);
    f.configure(JsonFactory.Feature.INTERN_FIELD_NAMES, doIntern);

    ObjectMapper m = new ObjectMapper();
    Object input1 = m.readValue(data, Object.class);
    JsonNode input2 = m.readTree(data);

    new ManualReadPerfUntypedStream()
        .testFromBytes(
            //            .testFromString(
            m, "JSON-as-Object", input1, Object.class, m, "JSON-as-Object2", input2, Object.class
            //               ,m, "JSON-as-Node", input2, JsonNode.class
            );
  }
Пример #21
0
 public static <T> T convertValue(Object value, Class<T> type) {
   return OBJECT_MAPPER.convertValue(value, type);
 }
 /**
  * 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));
 }
 // [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);
 }
 public void testEnumAsIndexViaAnnotations() throws Exception {
   assertEquals("{\"text\":0}", mapper.writeValueAsString(new PoNUMContainer()));
 }
 // [databind#661]
 public void testCustomEnumMapKeySerializer() throws Exception {
   String json = mapper.writeValueAsString(new MyBean661("abc"));
   assertEquals(aposToQuotes("{'X-FOO':'abc'}"), json);
 }
 // [databind#594]
 public void testJsonValueForEnumMapKey() throws Exception {
   assertEquals(
       aposToQuotes("{'stuff':{'longValue':'foo'}}"),
       mapper.writeValueAsString(new MyStuff594("foo")));
 }
 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));
 }
 // [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 testEnumAsObjectValid() throws Exception {
   assertEquals("{\"value\":\"a1\"}", mapper.writeValueAsString(PoNUM.A));
 }