// Update and return given train line with the Jackson parser
  // AG
  public static <T> TrainLine updateLine(T address, TrainLine line) {
    try {
      Object trainData = new Object();
      if (address instanceof URL) {
        // Get train data from web
        trainData = mapper.readValue((URL) address, Object.class);
      } else if (address instanceof File) {
        // Get train data locally
        trainData = mapper.readValue((File) address, Object.class);
      }
      // System.out.println(trainData.toString());
      // Go inside the wrapper
      Object tripListObj = getFromMap(trainData, TRIP_LIST_KEY);

      line = new TrainLine(tripListObj);
    } catch (JsonParseException e) {
      e.printStackTrace();
    } catch (JsonMappingException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return line;
  }
  // [JACKSON-484]
  public void testInetAddress() throws IOException {
    InetAddress address = MAPPER.readValue(quote("127.0.0.1"), InetAddress.class);
    assertEquals("127.0.0.1", address.getHostAddress());

    // should we try resolving host names? That requires connectivity...
    final String HOST = "google.com";
    address = MAPPER.readValue(quote(HOST), InetAddress.class);
    assertEquals(HOST, address.getHostName());
  }
  // for [JACKSON-652]
  // @since 1.9
  public void testUntypedWithJsonArrays() throws Exception {
    // by default we get:
    Object ob = MAPPER.readValue("[1]", Object.class);
    assertTrue(ob instanceof List<?>);

    // but can change to produce Object[]:
    MAPPER.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true);
    ob = MAPPER.readValue("[1]", Object.class);
    assertEquals(Object[].class, ob.getClass());
  }
  // [JACKSON-597]
  public void testClass() throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    assertSame(String.class, mapper.readValue(quote("java.lang.String"), Class.class));

    // then primitive types
    assertSame(Boolean.TYPE, mapper.readValue(quote("boolean"), Class.class));
    assertSame(Byte.TYPE, mapper.readValue(quote("byte"), Class.class));
    assertSame(Short.TYPE, mapper.readValue(quote("short"), Class.class));
    assertSame(Character.TYPE, mapper.readValue(quote("char"), Class.class));
    assertSame(Integer.TYPE, mapper.readValue(quote("int"), Class.class));
    assertSame(Long.TYPE, mapper.readValue(quote("long"), Class.class));
    assertSame(Float.TYPE, mapper.readValue(quote("float"), Class.class));
    assertSame(Double.TYPE, mapper.readValue(quote("double"), Class.class));
    assertSame(Void.TYPE, mapper.readValue(quote("void"), Class.class));
  }
  // [JACKSON-605]
  public void testClassWithParams() throws IOException {
    String json = MAPPER.writeValueAsString(new ParamClassBean("Foobar"));

    ParamClassBean result = MAPPER.readValue(json, ParamClassBean.class);
    assertEquals("Foobar", result.name);
    assertSame(String.class, result.clazz);
  }
 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);
   }
 }
Exemple #7
0
 @SuppressWarnings("unchecked")
 public static LelyFeedEvent fromJson(String json) {
   try {
     return new LelyFeedEvent((Map<String, Object>) jsonMapper.readValue(json, Map.class));
   } catch (Exception e) {
     throw new SamzaException(e);
   }
 }
  /** Related to issues [JACKSON-155], [#170]. */
  public void testFile() throws Exception {
    // Not portable etc... has to do:
    File src = new File("/test").getAbsoluteFile();
    String abs = src.getAbsolutePath();

    // escape backslashes (for portability with windows)
    String json = MAPPER.writeValueAsString(abs);
    File result = MAPPER.readValue(json, File.class);
    assertEquals(abs, result.getAbsolutePath());

    // Then #170
    final ObjectMapper mapper2 = new ObjectMapper();
    mapper2.setVisibility(PropertyAccessor.CREATOR, Visibility.NONE);

    result = mapper2.readValue(json, File.class);
    assertEquals(abs, result.getAbsolutePath());
  }
 public void testForJackson288() throws Exception {
   final long TIMESTAMP = 12345678L;
   ObjectMapper mapper = getJaxbMapper();
   Bean288 bean = mapper.readValue("{\"date\":" + TIMESTAMP + "}", Bean288.class);
   assertNotNull(bean);
   Date d = bean.date;
   assertNotNull(d);
   assertEquals(TIMESTAMP, d.getTime());
 }
 public void testMapError() throws Exception {
   ObjectMapper mapper = new ObjectMapper();
   try {
     Object result = mapper.readValue("[ 1, 2 ]", new TypeReference<Map<String, String>>() {});
     fail("Expected an exception, but got result value: " + result);
   } catch (JsonMappingException jex) {
     verifyException(jex, "START_ARRAY");
   }
 }
  /** 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);
  }
 // Test for verifying that Long values are coerced to boolean correctly as well
 public void testLongToBoolean() throws Exception {
   long value = 1L + Integer.MAX_VALUE;
   BooleanBean b =
       MAPPER.readValue(
           "{\"primitive\" : " + value + ", \"wrapper\":" + value + ", \"ctor\":" + value + "}",
           BooleanBean.class);
   assertEquals(Boolean.TRUE, b.wrapper);
   assertTrue(b.primitive);
   assertEquals(Boolean.TRUE, b.ctor);
 }
 public void testRegexps() throws IOException {
   final String PATTERN_STR = "abc:\\s?(\\d+)";
   Pattern exp = Pattern.compile(PATTERN_STR);
   /* Ok: easiest way is to just serialize first; problem
    * is the backslash
    */
   String json = MAPPER.writeValueAsString(exp);
   Pattern result = MAPPER.readValue(json, Pattern.class);
   assertEquals(exp.pattern(), result.pattern());
 }
  public void testInetSocketAddress() throws IOException {
    InetSocketAddress address = MAPPER.readValue(quote("127.0.0.1"), InetSocketAddress.class);
    assertEquals("127.0.0.1", address.getAddress().getHostAddress());

    InetSocketAddress ip6 =
        MAPPER.readValue(quote("2001:db8:85a3:8d3:1319:8a2e:370:7348"), InetSocketAddress.class);
    assertEquals("2001:db8:85a3:8d3:1319:8a2e:370:7348", ip6.getAddress().getHostAddress());

    InetSocketAddress ip6port =
        MAPPER.readValue(
            quote("[2001:db8:85a3:8d3:1319:8a2e:370:7348]:443"), InetSocketAddress.class);
    assertEquals("2001:db8:85a3:8d3:1319:8a2e:370:7348", ip6port.getAddress().getHostAddress());
    assertEquals(443, ip6port.getPort());

    // should we try resolving host names? That requires connectivity...
    final String HOST = "www.ning.com";
    address = MAPPER.readValue(quote(HOST), InetSocketAddress.class);
    assertEquals(HOST, address.getHostName());
  }
 public void testNoCtorMap() throws Exception {
   ObjectMapper mapper = new ObjectMapper();
   try {
     BrokenMap result = mapper.readValue("{ \"a\" : 3 }", BrokenMap.class);
     // should never get here; assert added to remove compiler warning
     assertNull(result);
   } catch (JsonMappingException e) {
     // instead, should get this exception:
     verifyException(e, "no default constructor found");
   }
 }
 public void testPolymorphicAtomicRefProperty() throws Exception {
   TypeInfoAtomic data = new TypeInfoAtomic();
   data.value = new AtomicReference<BaseForAtomic>(new ImplForAtomic(42));
   String json = MAPPER.writeValueAsString(data);
   TypeInfoAtomic result = MAPPER.readValue(json, TypeInfoAtomic.class);
   assertNotNull(result);
   BaseForAtomic value = result.value.get();
   assertNotNull(value);
   assertEquals(ImplForAtomic.class, value.getClass());
   assertEquals(42, ((ImplForAtomic) value).x);
 }
 // [Issue#239]
 public void testByteBuffer() throws Exception {
   byte[] INPUT = new byte[] {1, 3, 9, -1, 6};
   String exp = MAPPER.writeValueAsString(INPUT);
   ByteBuffer result = MAPPER.readValue(exp, ByteBuffer.class);
   assertNotNull(result);
   assertEquals(INPUT.length, result.remaining());
   for (int i = 0; i < INPUT.length; ++i) {
     assertEquals(INPUT[i], result.get());
   }
   assertEquals(0, result.remaining());
 }
 public void testAtomicRefViaDefaultTyping() throws Exception {
   ObjectMapper mapper = new ObjectMapper();
   mapper.enableDefaultTyping(DefaultTyping.NON_FINAL);
   AtomicStringWrapper data = new AtomicStringWrapper("foo");
   String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(data);
   AtomicStringWrapper result = mapper.readValue(json, AtomicStringWrapper.class);
   assertNotNull(result);
   assertNotNull(result.wrapper);
   assertEquals(AtomicReference.class, result.wrapper.getClass());
   StringWrapper w = result.wrapper.get();
   assertEquals("foo", w.str);
 }
  /** Unit test for [JACKSON-185] */
  public void testUntypedMap3() throws Exception {
    String JSON = "{\"a\":[{\"a\":\"b\"},\"value\"]}";
    ObjectMapper m = new ObjectMapper();
    Map<?, ?> result = m.readValue(JSON, Map.class);
    assertTrue(result instanceof Map<?, ?>);
    assertEquals(1, result.size());
    Object ob = result.get("a");
    assertNotNull(ob);
    Collection<?> list = (Collection<?>) ob;
    assertEquals(2, list.size());

    JSON =
        "{ \"var1\":\"val1\", \"var2\":\"val2\", "
            + "\"subvars\": ["
            + " {  \"subvar1\" : \"subvar2\", \"x\" : \"y\" }, "
            + " { \"a\":1 } ]"
            + " }";
    result = m.readValue(JSON, Map.class);
    assertTrue(result instanceof Map<?, ?>);
    assertEquals(3, result.size());
  }
 // [JACKSON-726]
 public void testUUIDKeyMap() throws Exception {
   ObjectMapper mapper = new ObjectMapper();
   UUID key = UUID.nameUUIDFromBytes("foobar".getBytes("UTF-8"));
   String JSON = "{ \"" + key + "\":4}";
   Map<UUID, Object> result = mapper.readValue(JSON, new TypeReference<Map<UUID, Object>>() {});
   assertNotNull(result);
   assertEquals(1, result.size());
   Object ob = result.keySet().iterator().next();
   assertNotNull(ob);
   assertEquals(UUID.class, ob.getClass());
   assertEquals(key, ob);
 }
 public void testSimpleKeyDeser() throws Exception {
   ObjectMapper mapper = new ObjectMapper();
   SimpleModule module = new SimpleModule("test", Version.unknownVersion());
   module.addKeyDeserializer(String.class, new ContextualDeser("???"));
   mapper.registerModule(module);
   MapBean result = mapper.readValue("{\"map\":{\"a\":3}}", MapBean.class);
   Map<String, Integer> map = result.map;
   assertNotNull(map);
   assertEquals(1, map.size());
   Map.Entry<String, Integer> entry = map.entrySet().iterator().next();
   assertEquals(Integer.valueOf(3), entry.getValue());
   assertEquals("map:a", entry.getKey());
 }
  public void testExactStringStringMap() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    // to get typing, must use type reference
    String JSON = "{ \"a\" : \"b\" }";
    Map<String, Integer> result =
        mapper.readValue(JSON, new TypeReference<TreeMap<String, String>>() {});

    assertNotNull(result);
    assertEquals(TreeMap.class, result.getClass());
    assertEquals(1, result.size());

    assertEquals("b", result.get("a"));
    assertNull(result.get("b"));
  }
  /**
   * 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);
  }
  /**
   * Let's also try another way to express "gimme a Map" deserialization; this time by specifying a
   * Map class, to reduce need to cast
   */
  public void testUntypedMap2() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    // to get "untyped" default map-to-map, pass Object.class
    String JSON = "{ \"a\" : \"x\" }";

    @SuppressWarnings("unchecked")
    HashMap<String, Object> result = /*(HashMap<String,Object>)*/
        mapper.readValue(JSON, HashMap.class);
    assertNotNull(result);
    assertTrue(result instanceof Map<?, ?>);

    assertEquals(1, result.size());

    assertEquals("x", result.get("a"));
  }
  public void testMapWithEnums() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    String JSON = "{ \"KEY2\" : \"WHATEVER\" }";

    // to get typing, must use type reference
    Map<Enum<?>, Enum<?>> result = mapper.readValue(JSON, new TypeReference<Map<Key, Key>>() {});

    assertNotNull(result);
    assertTrue(result instanceof Map<?, ?>);
    assertEquals(1, result.size());

    assertEquals(Key.WHATEVER, result.get(Key.KEY2));
    assertNull(result.get(Key.WHATEVER));
    assertNull(result.get(Key.KEY1));
  }
  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 + "')");
    }
  }
  /**
   * Unit test that verifies that it's ok to have incomplete information about Map class itself, as
   * long as it's something we good guess about: for example, <code>Map.Class</code> will be
   * replaced by something like <code>HashMap.class</code>, if given.
   */
  public void testGenericStringIntMap() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    // to get typing, must use type reference; but with abstract type
    String JSON = "{ \"a\" : 1, \"b\" : 2, \"c\" : -99 }";
    Map<String, Integer> result =
        mapper.readValue(JSON, new TypeReference<Map<String, Integer>>() {});
    assertNotNull(result);
    assertTrue(result instanceof Map<?, ?>);
    assertEquals(3, result.size());

    assertEquals(Integer.valueOf(-99), result.get("c"));
    assertEquals(Integer.valueOf(2), result.get("b"));
    assertEquals(Integer.valueOf(1), result.get("a"));

    assertNull(result.get(""));
  }
  /**
   * Let's also check that it is possible to do type conversions to allow use of non-String Map
   * keys.
   */
  public void testIntBooleanMap() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    // to get typing, must use type reference
    String JSON = "{ \"1\" : true, \"-1\" : false }";
    Map<String, Integer> result =
        mapper.readValue(JSON, new TypeReference<HashMap<Integer, Boolean>>() {});

    assertNotNull(result);
    assertEquals(HashMap.class, result.getClass());
    assertEquals(2, result.size());

    assertEquals(Boolean.TRUE, result.get(Integer.valueOf(1)));
    assertEquals(Boolean.FALSE, result.get(Integer.valueOf(-1)));
    assertNull(result.get("foobar"));
    assertNull(result.get(0));
  }
  // [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());
  }
  public void testExactStringIntMap() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    // to get typing, must use type reference
    String JSON = "{ \"foo\" : 13, \"bar\" : -39, \n \"\" : 0 }";
    Map<String, Integer> result =
        mapper.readValue(JSON, new TypeReference<HashMap<String, Integer>>() {});

    assertNotNull(result);
    assertEquals(HashMap.class, result.getClass());
    assertEquals(3, result.size());

    assertEquals(Integer.valueOf(13), result.get("foo"));
    assertEquals(Integer.valueOf(-39), result.get("bar"));
    assertEquals(Integer.valueOf(0), result.get(""));
    assertNull(result.get("foobar"));
    assertNull(result.get(" "));
  }