Пример #1
0
  // Test for [JACKSON-631]
  public void testBase64Text() throws Exception {
    // let's actually iterate over sets of encoding modes, lengths

    final int[] LENS = {1, 2, 3, 4, 7, 9, 32, 33, 34, 35};
    final Base64Variant[] VARIANTS = {
      Base64Variants.MIME,
      Base64Variants.MIME_NO_LINEFEEDS,
      Base64Variants.MODIFIED_FOR_URL,
      Base64Variants.PEM
    };

    for (int len : LENS) {
      byte[] input = new byte[len];
      for (int i = 0; i < input.length; ++i) {
        input[i] = (byte) i;
      }
      for (Base64Variant variant : VARIANTS) {
        TextNode n = new TextNode(variant.encode(input));
        byte[] data = null;
        try {
          data = n.getBinaryValue(variant);
        } catch (Exception e) {
          throw new IOException(
              "Failed (variant " + variant + ", data length " + len + "): " + e.getMessage());
        }
        assertNotNull(data);
        assertArrayEquals(data, input);
      }
    }
  }
  public void testXmlElementTypeDeser() throws Exception {
    ObjectMapper mapper = getJaxbMapper();

    SimpleNamed originalModel = new SimpleNamed();
    originalModel.setName("Foobar");
    String json = mapper.writeValueAsString(originalModel);
    SimpleNamed result = null;
    try {
      result = mapper.readValue(json, SimpleNamed.class);
    } catch (Exception ie) {
      fail("Failed to deserialize '" + json + "': " + ie.getMessage());
    }
    if (!"Foobar".equals(result.name)) {
      fail("Failed, JSON == '" + json + "')");
    }
  }
  // [JACKSON-888]
  public void testStackTraceElement() throws Exception {
    StackTraceElement elem = null;
    try {
      throw new IllegalStateException();
    } catch (Exception e) {
      elem = e.getStackTrace()[0];
    }
    String json = MAPPER.writeValueAsString(elem);
    StackTraceElement back = MAPPER.readValue(json, StackTraceElement.class);

    assertEquals("testStackTraceElement", back.getMethodName());
    assertEquals(elem.getLineNumber(), back.getLineNumber());
    assertEquals(elem.getClassName(), back.getClassName());
    assertEquals(elem.isNativeMethod(), back.isNativeMethod());
    assertTrue(back.getClassName().endsWith("TestJdkTypes"));
    assertFalse(back.isNativeMethod());
  }
  /**
   * The method to be called by {@link ObjectMapper} and {@link ObjectWriter} for serializing given
   * value, using serializers that this provider has access to (via caching and/or creating new
   * serializers as need be).
   */
  public void serializeValue(JsonGenerator jgen, Object value)
      throws IOException, JsonGenerationException {
    JsonSerializer<Object> ser;
    final boolean wrap;

    if (value == null) { // no type provided; must just use the default null serializer
      ser = getDefaultNullValueSerializer();
      wrap = false; // no name to use for wrapping; can't do!
    } else {
      Class<?> cls = value.getClass();
      // true, since we do want to cache root-level typed serializers (ditto for null property)
      ser = findTypedValueSerializer(cls, true, null);

      // Ok: should we wrap result in an additional property ("root name")?
      String rootName = _config.getRootName();
      if (rootName == null) { // not explicitly specified
        // [JACKSON-163]
        wrap = _config.isEnabled(SerializationFeature.WRAP_ROOT_VALUE);
        if (wrap) {
          jgen.writeStartObject();
          jgen.writeFieldName(_rootNames.findRootName(value.getClass(), _config));
        }
      } else if (rootName.length() == 0) {
        wrap = false;
      } else { // [JACKSON-764]
        // empty String means explicitly disabled; non-empty that it is enabled
        wrap = true;
        jgen.writeStartObject();
        jgen.writeFieldName(rootName);
      }
    }
    try {
      ser.serialize(value, jgen, this);
      if (wrap) {
        jgen.writeEndObject();
      }
    } catch (IOException ioe) { // As per [JACKSON-99], pass IOException and subtypes as-is
      throw ioe;
    } catch (Exception e) { // but wrap RuntimeExceptions, to get path information
      String msg = e.getMessage();
      if (msg == null) {
        msg = "[no message for " + e.getClass().getName() + "]";
      }
      throw new JsonMappingException(msg, e);
    }
  }
Пример #5
0
  // Generates the list of stops from the included stops file
  // AG
  public static void generateStops() {
    try {
      JsonFactory f = new JsonFactory();
      JsonParser jp = f.createJsonParser(new File("stopsAdjacent.json"));
      // advance stream to START_ARRAY first:
      jp.nextToken();
      // and then each time, advance to opening START_OBJECT
      while (jp.nextToken() == JsonToken.START_OBJECT) {
        Stop stop = mapper.readValue(jp, Stop.class);
        stops.add(stop);
        // after binding, stream points to closing END_OBJECT
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    graph = new TrainGraph(stops);
  }
  /**
   * The method to be called by {@link ObjectWriter} for serializing given value (assumed to be of
   * specified root type, instead of runtime type of value), when it may know specific {@link
   * JsonSerializer} to use.
   *
   * @param rootType Type to use for locating serializer to use, instead of actual runtime type, if
   *     no serializer is passed
   * @param ser Root Serializer to use, if not null
   * @since 2.1
   */
  public void serializeValue(
      JsonGenerator jgen, Object value, JavaType rootType, JsonSerializer<Object> ser)
      throws IOException, JsonGenerationException {
    final boolean wrap;

    if (value == null) {
      ser = getDefaultNullValueSerializer();
      wrap = false;
    } else {
      // Let's ensure types are compatible at this point
      if (rootType != null) {
        if (!rootType.getRawClass().isAssignableFrom(value.getClass())) {
          _reportIncompatibleRootType(value, rootType);
        }
      }
      // root value, not reached via property:
      if (ser == null) {
        ser = findTypedValueSerializer(rootType, true, null);
      }
      wrap = _config.isEnabled(SerializationFeature.WRAP_ROOT_VALUE);
      if (wrap) {
        jgen.writeStartObject();
        jgen.writeFieldName(_rootNames.findRootName(rootType, _config));
      }
    }
    try {
      ser.serialize(value, jgen, this);
      if (wrap) {
        jgen.writeEndObject();
      }
    } catch (IOException ioe) { // no wrapping for IO (and derived)
      throw ioe;
    } catch (Exception e) { // but others do need to be, to get path etc
      String msg = e.getMessage();
      if (msg == null) {
        msg = "[no message for " + e.getClass().getName() + "]";
      }
      throw new JsonMappingException(msg, e);
    }
  }
 /**
  * Method that takes in exception of any type, and casts or wraps it to an IOException or its
  * subclass.
  */
 protected void _throwAsIOE(Exception e, Object value) throws IOException {
   if (e instanceof IllegalArgumentException) {
     String actType = (value == null) ? "[NULL]" : value.getClass().getName();
     StringBuilder msg = new StringBuilder("Problem deserializing property '").append(getName());
     msg.append("' (expected type: ").append(getType());
     msg.append("; actual type: ").append(actType).append(")");
     String origMsg = e.getMessage();
     if (origMsg != null) {
       msg.append(", problem: ").append(origMsg);
     } else {
       msg.append(" (no error message provided)");
     }
     throw new JsonMappingException(msg.toString(), null, e);
   }
   _throwAsIOE(e);
 }