// [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-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); }
// [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)); }
public static String toJson(LelyFeedEvent event) { Map<String, Object> jsonObject = toMap(event); try { return jsonMapper.writeValueAsString(jsonObject); } catch (Exception e) { throw new SamzaException(e); } }
/** * @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; }
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 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 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); } }
// [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)); }
@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); }
// [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 }
/** * 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); }
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 + "')"); } }
/** 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()); }
// [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()); }
// For [databind#188] public void testMixedRefsIssue188() throws Exception { Company comp = new Company(); Employee e1 = new Employee(1, "First", null); Employee e2 = new Employee(2, "Second", e1); e1.addReport(e2); comp.add(e1); comp.add(e2); String json = MAPPER.writeValueAsString(comp); assertEquals( "{\"employees\":[" + "{\"id\":1,\"name\":\"First\",\"manager\":null,\"reports\":[2]}," + "{\"id\":2,\"name\":\"Second\",\"manager\":1,\"reports\":[]}" + "]}", json); }
public void testColumnMetadata() throws Exception { ColumnMetadata col = new ColumnMetadata("Billy", "employee", "comment"); Wrapper w = new Wrapper(); w.a = col; w.b = col; String json = MAPPER.writeValueAsString(w); Wrapper deserialized = MAPPER.readValue(json, Wrapper.class); assertNotNull(deserialized); assertNotNull(deserialized.a); assertNotNull(deserialized.b); assertEquals("Billy", deserialized.a.getName()); assertEquals("employee", deserialized.a.getType()); assertEquals("comment", deserialized.a.getComment()); assertSame(deserialized.a, deserialized.b); }
/** 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); }
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)); }
/** * Example technologies */ @Test public void showExamples() throws JsonProcessingException { if (LOG.isDebugEnabled()) { LOG.debug("Show how jackson can convert something to json"); } Customer customer = new Customer(); customer.setName("TestName"); customer.setId("12312321"); ObjectMapper mapper = new ObjectMapper(); String jsonValue = mapper.writeValueAsString(customer); if (LOG.isInfoEnabled()) { LOG.info("Json Value:" + jsonValue); } }
@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 { 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); }
// [databind#661] public void testCustomEnumMapKeySerializer() throws Exception { String json = mapper.writeValueAsString(new MyBean661("abc")); assertEquals(aposToQuotes("{'X-FOO':'abc'}"), json); }
public void testIgnoreWithMapProperty() throws Exception { assertEquals("{\"value\":{\"b\":2}}", MAPPER.writeValueAsString(new MapWrapper())); }
public void testIgnoreViaPropsAndClass() throws Exception { assertEquals("{\"value\":{\"y\":2}}", MAPPER.writeValueAsString(new WrapperWithPropIgnore2())); }
public void testIgnoreViaOnlyProps() throws Exception { assertEquals("{\"value\":{\"x\":1}}", MAPPER.writeValueAsString(new WrapperWithPropIgnore())); }