/** 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(); } }
private void skipToField(JsonParser jp, String fieldName, ParseState state) throws JsonParseException, IOException { String lastFieldName = null; while (jp.getCurrentToken() != null) { switch (jp.getCurrentToken()) { case FIELD_NAME: lastFieldName = jp.getCurrentName(); jp.nextToken(); break; case START_OBJECT: if (!state.inRow) { state.inRow = true; jp.nextToken(); } else { if (isInField(fieldName, lastFieldName)) { return; } else { jp.skipChildren(); } } break; default: if (isInField(fieldName, lastFieldName)) { jp.nextToken(); return; } jp.nextToken(); break; } } }
public void testUtf8Issue462() throws Exception { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); IOContext ioc = new IOContext(new BufferRecycler(), bytes, true); JsonGenerator gen = new UTF8JsonGenerator(ioc, 0, null, bytes); String str = "Natuurlijk is alles gelukt en weer een tevreden klant\uD83D\uDE04"; int length = 4000 - 38; for (int i = 1; i <= length; ++i) { gen.writeNumber(1); } gen.writeString(str); gen.flush(); gen.close(); // Also verify it's parsable? JsonFactory f = new JsonFactory(); JsonParser p = f.createParser(bytes.toByteArray()); for (int i = 1; i <= length; ++i) { assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken()); assertEquals(1, p.getIntValue()); } assertToken(JsonToken.VALUE_STRING, p.nextToken()); assertEquals(str, p.getText()); assertNull(p.nextToken()); p.close(); }
@Override public DateMidnight deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { // We'll accept either long (timestamp) or array: if (jp.isExpectedStartArrayToken()) { jp.nextToken(); // VALUE_NUMBER_INT int year = jp.getIntValue(); jp.nextToken(); // VALUE_NUMBER_INT int month = jp.getIntValue(); jp.nextToken(); // VALUE_NUMBER_INT int day = jp.getIntValue(); if (jp.nextToken() != JsonToken.END_ARRAY) { throw ctxt.wrongTokenException(jp, JsonToken.END_ARRAY, "after DateMidnight ints"); } return new DateMidnight(year, month, day); } switch (jp.getCurrentToken()) { case VALUE_NUMBER_INT: return new DateMidnight(jp.getLongValue()); case VALUE_STRING: DateTime local = parseLocal(jp); if (local == null) { return null; } return local.toDateMidnight(); } throw ctxt.wrongTokenException( jp, JsonToken.START_ARRAY, "expected JSON Array, Number or String"); }
private TwitterEntry read(JsonParser jp) throws IOException { // First: verify that we got "Json Object": if (jp.nextToken() != JsonToken.START_OBJECT) { throw new IOException("Expected data to start with an Object"); } TwitterEntry result = new TwitterEntry(); // Iterate over object fields: while (jp.nextToken() != JsonToken.END_OBJECT) { String fieldName = jp.getCurrentName(); // Let's move to value jp.nextToken(); if (fieldName.equals("id")) { result.setId(jp.getLongValue()); } else if (fieldName.equals("text")) { result.setText(jp.getText()); } else if (fieldName.equals("fromUserId")) { result.setFromUserId(jp.getIntValue()); } else if (fieldName.equals("toUserId")) { result.setToUserId(jp.getIntValue()); } else if (fieldName.equals("languageCode")) { result.setLanguageCode(jp.getText()); } else { // ignore, or signal error throw new IOException("Unrecognized field '" + fieldName + "'"); } } jp.close(); // important to close both parser and underlying File reader return result; }
public final void copyCurrentStructure(JsonParser jp) throws IOException, JsonProcessingException { JsonToken t = jp.getCurrentToken(); // Let's handle field-name separately first if (t == JsonToken.FIELD_NAME) { writeFieldName(jp.getCurrentName()); t = jp.nextToken(); // fall-through to copy the associated value } switch (t) { case START_ARRAY: writeStartArray(); while (jp.nextToken() != JsonToken.END_ARRAY) { copyCurrentStructure(jp); } writeEndArray(); break; case START_OBJECT: writeStartObject(); while (jp.nextToken() != JsonToken.END_OBJECT) { copyCurrentStructure(jp); } writeEndObject(); break; default: // others are simple: copyCurrentEvent(jp); } }
public void testEmptyArrayWrite() throws Exception { StringWriter sw = new StringWriter(); JsonGenerator gen = new JsonFactory().createGenerator(sw); JsonStreamContext ctxt = gen.getOutputContext(); assertTrue(ctxt.inRoot()); assertFalse(ctxt.inArray()); assertFalse(ctxt.inObject()); assertEquals(0, ctxt.getEntryCount()); assertEquals(0, ctxt.getCurrentIndex()); gen.writeStartArray(); ctxt = gen.getOutputContext(); assertFalse(ctxt.inRoot()); assertTrue(ctxt.inArray()); assertFalse(ctxt.inObject()); assertEquals(0, ctxt.getEntryCount()); assertEquals(0, ctxt.getCurrentIndex()); gen.writeEndArray(); ctxt = gen.getOutputContext(); assertTrue("Should be in root, was " + ctxt.getTypeDesc(), ctxt.inRoot()); assertFalse(ctxt.inArray()); assertFalse(ctxt.inObject()); assertEquals(1, ctxt.getEntryCount()); // Index won't yet move assertEquals(0, ctxt.getCurrentIndex()); gen.close(); String docStr = sw.toString(); JsonParser jp = createParserUsingReader(docStr); assertEquals(JsonToken.START_ARRAY, jp.nextToken()); assertEquals(JsonToken.END_ARRAY, jp.nextToken()); jp.close(); // Ok, then array with nested empty array sw = new StringWriter(); gen = new JsonFactory().createGenerator(sw); gen.writeStartArray(); gen.writeStartArray(); gen.writeEndArray(); gen.writeEndArray(); gen.close(); docStr = sw.toString(); jp = createParserUsingReader(docStr); assertEquals(JsonToken.START_ARRAY, jp.nextToken()); assertEquals(JsonToken.START_ARRAY, jp.nextToken()); assertEquals(JsonToken.END_ARRAY, jp.nextToken()); assertEquals(JsonToken.END_ARRAY, jp.nextToken()); assertEquals(null, jp.nextToken()); jp.close(); }
private List<Image> readImages(JsonParser parser) throws IOException { if (parser.nextToken() != JsonToken.START_ARRAY) { reportIllegal(parser, JsonToken.START_ARRAY); } List<Image> images = new ArrayList<Image>(); while (parser.nextToken() == JsonToken.START_OBJECT) { images.add(readImage(parser)); } verifyCurrent(parser, JsonToken.END_ARRAY); return images; }
public void testUnclosedArray() throws Exception { JsonParser jp = createParserUsingReader("[ 1, 2"); assertToken(JsonToken.START_ARRAY, jp.nextToken()); assertToken(JsonToken.VALUE_NUMBER_INT, jp.nextToken()); assertToken(JsonToken.VALUE_NUMBER_INT, jp.nextToken()); try { jp.nextToken(); fail("Expected an exception for unclosed ARRAY"); } catch (JsonParseException jpe) { verifyException(jpe, "expected close marker for ARRAY"); } }
private Map<String, Integer> readHeaderFields(JsonParser jp) throws JsonParseException, IOException { Map<String, Integer> map = new HashMap<String, Integer>(); jp.nextToken(); String nextFieldName = jp.getCurrentName(); while (!nextFieldName.equals(ROWS_FIELD_NAME)) { jp.nextToken(); map.put(nextFieldName, Integer.valueOf(jp.getIntValue())); jp.nextToken(); nextFieldName = jp.getCurrentName(); } return map; }
public void testUnclosedObject() throws Exception { JsonParser jp = createParserUsingReader("{ \"key\" : 3 "); assertToken(JsonToken.START_OBJECT, jp.nextToken()); assertToken(JsonToken.FIELD_NAME, jp.nextToken()); assertToken(JsonToken.VALUE_NUMBER_INT, jp.nextToken()); try { jp.nextToken(); fail("Expected an exception for unclosed OBJECT"); } catch (JsonParseException jpe) { verifyException(jpe, "expected close marker for OBJECT"); } }
@Override public EnumMap<?, ?> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { // Ok: must point to START_OBJECT if (jp.getCurrentToken() != JsonToken.START_OBJECT) { return _deserializeFromEmpty(jp, ctxt); } EnumMap result = constructMap(); final JsonDeserializer<Object> valueDes = _valueDeserializer; final TypeDeserializer typeDeser = _valueTypeDeserializer; while ((jp.nextToken()) == JsonToken.FIELD_NAME) { String keyName = jp.getCurrentName(); // just for error message // but we need to let key deserializer handle it separately, nonetheless Enum<?> key = (Enum<?>) _keyDeserializer.deserializeKey(keyName, ctxt); if (key == null) { if (!ctxt.isEnabled(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)) { throw ctxt.weirdStringException( keyName, _enumClass, "value not one of declared Enum instance names for " + _mapType.getKeyType()); } /* 24-Mar-2012, tatu: Null won't work as a key anyway, so let's * just skip the entry then. But we must skip the value as well, if so. */ jp.nextToken(); jp.skipChildren(); continue; } // And then the value... JsonToken t = jp.nextToken(); /* note: MUST check for nulls separately: deserializers will * not handle them (and maybe fail or return bogus data) */ Object value; try { if (t == JsonToken.VALUE_NULL) { value = valueDes.getNullValue(ctxt); } else if (typeDeser == null) { value = valueDes.deserialize(jp, ctxt); } else { value = valueDes.deserializeWithType(jp, ctxt, typeDeser); } } catch (Exception e) { wrapAndThrow(e, result, keyName); return null; } result.put(key, value); } return result; }
protected Object _unwrapAndDeserialize( JsonParser jp, DeserializationContext ctxt, JavaType rootType, JsonDeserializer<Object> deser) throws IOException, JsonParseException, JsonMappingException { SerializedString rootName = _provider.findExpectedRootName(ctxt.getConfig(), rootType); if (jp.getCurrentToken() != JsonToken.START_OBJECT) { throw JsonMappingException.from( jp, "Current token not START_OBJECT (needed to unwrap root name '" + rootName + "'), but " + jp.getCurrentToken()); } if (jp.nextToken() != JsonToken.FIELD_NAME) { throw JsonMappingException.from( jp, "Current token not FIELD_NAME (to contain expected root name '" + rootName + "'), but " + jp.getCurrentToken()); } String actualName = jp.getCurrentName(); if (!rootName.getValue().equals(actualName)) { throw JsonMappingException.from( jp, "Root name '" + actualName + "' does not match expected ('" + rootName + "') for type " + rootType); } // ok, then move to value itself.... jp.nextToken(); Object result; if (_valueToUpdate == null) { result = deser.deserialize(jp, ctxt); } else { deser.deserialize(jp, ctxt, _valueToUpdate); result = _valueToUpdate; } // and last, verify that we now get matching END_OBJECT if (jp.nextToken() != JsonToken.END_OBJECT) { throw JsonMappingException.from( jp, "Current token not END_OBJECT (to match wrapper object with root name '" + rootName + "'), but " + jp.getCurrentToken()); } return result; }
public void testWeirdToken() throws Exception { final String JSON = "[ nil ]"; for (int i = 0; i < 2; ++i) { JsonParser jp = (i == 0) ? createParserUsingReader(JSON) : createParserUsingStream(JSON, "UTF-8"); assertToken(JsonToken.START_ARRAY, jp.nextToken()); try { jp.nextToken(); fail("Expected an exception for weird token"); } catch (JsonParseException jpe) { verifyException(jpe, "Unrecognized token"); } } }
/** This is the trickiest thing to handle, since property we are looking for may be anywhere... */ @Override public Object deserializeTypedFromObject(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { // but first, sanity check to ensure we have START_OBJECT or FIELD_NAME JsonToken t = jp.getCurrentToken(); if (t == JsonToken.START_OBJECT) { t = jp.nextToken(); } else if (t != JsonToken.FIELD_NAME) { throw ctxt.wrongTokenException( jp, JsonToken.START_OBJECT, "need JSON Object to contain As.PROPERTY type information (for class " + baseTypeName() + ")"); } // Ok, let's try to find the property. But first, need token buffer... TokenBuffer tb = null; for (; t == JsonToken.FIELD_NAME; t = jp.nextToken()) { String name = jp.getCurrentName(); jp.nextToken(); // to point to the value if (_propertyName.equals(name)) { // gotcha! JsonDeserializer<Object> deser = _findDeserializer(ctxt, jp.getText()); // deserializer should take care of closing END_OBJECT as well if (tb != null) { jp = JsonParserSequence.createFlattened(tb.asParser(jp), jp); } /* Must point to the next value; tb had no current, jp * pointed to VALUE_STRING: */ jp.nextToken(); // to skip past String value // deserializer should take care of closing END_OBJECT as well return deser.deserialize(jp, ctxt); } if (tb == null) { tb = new TokenBuffer(null); } tb.writeFieldName(name); tb.copyCurrentStructure(jp); } // Error if we get here... throw ctxt.wrongTokenException( jp, JsonToken.FIELD_NAME, "missing property '" + _propertyName + "' that is to contain type id (for class " + baseTypeName() + ")"); }
public void testEOFInName() throws Exception { final String JSON = "{ \"abcd"; for (int i = 0; i < 2; ++i) { JsonParser jp = (i == 0) ? createParserUsingReader(JSON) : createParserUsingStream(JSON, "UTF-8"); assertToken(JsonToken.START_OBJECT, jp.nextToken()); try { jp.nextToken(); fail("Expected an exception for EOF"); } catch (JsonParseException jpe) { verifyException(jpe, "Unexpected end-of-input"); } } }
// [core#191]: similarly, but for "short" symbols: public void testShortNameCollisionsViaParser() throws Exception { JsonFactory f = new JsonFactory(); String json = _shortDoc191(); JsonParser p; // First: ensure that char-based is fine p = f.createParser(json); while (p.nextToken() != null) {} p.close(); // and then that byte-based p = f.createParser(json.getBytes("UTF-8")); while (p.nextToken() != null) {} p.close(); }
public void testMismatchObjectToArray() throws Exception { final String JSON = "{ ]"; for (int i = 0; i < 2; ++i) { JsonParser jp = (i == 0) ? createParserUsingReader(JSON) : createParserUsingStream(JSON, "UTF-8"); assertToken(JsonToken.START_OBJECT, jp.nextToken()); try { jp.nextToken(); fail("Expected an exception for incorrectly closed OBJECT"); } catch (JsonParseException jpe) { verifyException(jpe, "Unexpected close marker ']': expected '}'"); } } }
private void _testSurrogates(JsonFactory f, boolean checkText) throws IOException { byte[] json = "{\"text\":\"\uD83D\uDE03\"}".getBytes("UTF-8"); // first JsonParser jp = f.createParser(json); assertToken(JsonToken.START_OBJECT, jp.nextToken()); assertToken(JsonToken.FIELD_NAME, jp.nextToken()); if (checkText) { assertEquals("text", jp.getText()); } assertToken(JsonToken.VALUE_STRING, jp.nextToken()); if (checkText) { assertEquals("\uD83D\uDE03", jp.getText()); } assertToken(JsonToken.END_OBJECT, jp.nextToken()); }
public void testMismatchArrayToObject() throws Exception { final String JSON = "[ 1, 2 }"; for (int i = 0; i < 2; ++i) { JsonParser jp = (i == 0) ? createParserUsingReader(JSON) : createParserUsingStream(JSON, "UTF-8"); assertToken(JsonToken.START_ARRAY, jp.nextToken()); assertToken(JsonToken.VALUE_NUMBER_INT, jp.nextToken()); assertToken(JsonToken.VALUE_NUMBER_INT, jp.nextToken()); try { jp.nextToken(); fail("Expected an exception for incorrectly closed ARRAY"); } catch (JsonParseException jpe) { verifyException(jpe, "Unexpected close marker '}': expected ']'"); } } }
@Override public Collection<String> deserialize( JsonParser jp, DeserializationContext ctxt, Collection<String> result) throws IOException { // Ok: must point to START_ARRAY if (!jp.isExpectedStartArrayToken()) { return handleNonArray(jp, ctxt, result); } if (_valueDeserializer != null) { return deserializeUsingCustom(jp, ctxt, result, _valueDeserializer); } JsonToken t; while ((t = jp.nextToken()) != JsonToken.END_ARRAY) { String value; if (t == JsonToken.VALUE_STRING) { value = jp.getText(); } else if (t == JsonToken.VALUE_NULL) { value = null; } else { value = _parseString(jp, ctxt); } result.add(value); } return result; }
public void testMisssingColon() throws Exception { final String JSON = "{ \"a\" \"b\" }"; for (int i = 0; i < 2; ++i) { JsonParser jp = (i == 0) ? createParserUsingReader(JSON) : createParserUsingStream(JSON, "UTF-8"); assertToken(JsonToken.START_OBJECT, jp.nextToken()); try { // can be either here, or with next one... assertToken(JsonToken.FIELD_NAME, jp.nextToken()); jp.nextToken(); fail("Expected an exception for missing semicolon"); } catch (JsonParseException jpe) { verifyException(jpe, "was expecting a colon"); } } }
@Test public void testLocationExtraction() throws IOException { // { // "index" : "test", // "source" : { // value : "something" // } // } FastByteArrayOutputStream os = new FastByteArrayOutputStream(); JsonGenerator gen = new JsonFactory().createJsonGenerator(os, JsonEncoding.UTF8); gen.writeStartObject(); gen.writeStringField("index", "test"); gen.writeFieldName("source"); gen.writeStartObject(); gen.writeStringField("value", "something"); gen.writeEndObject(); gen.writeEndObject(); gen.close(); byte[] data = os.copiedByteArray(); JsonParser parser = new JsonFactory().createJsonParser(data); assertThat(parser.nextToken(), equalTo(JsonToken.START_OBJECT)); assertThat(parser.nextToken(), equalTo(JsonToken.FIELD_NAME)); // "index" assertThat(parser.nextToken(), equalTo(JsonToken.VALUE_STRING)); assertThat(parser.nextToken(), equalTo(JsonToken.FIELD_NAME)); // "source" // JsonLocation location1 = parser.getCurrentLocation(); // parser.skipChildren(); // JsonLocation location2 = parser.getCurrentLocation(); // // byte[] sourceData = new byte[(int) (location2.getByteOffset() - // location1.getByteOffset())]; // System.arraycopy(data, (int) location1.getByteOffset(), sourceData, 0, // sourceData.length); // // JsonParser sourceParser = new JsonFactory().createJsonParser(new // FastByteArrayInputStream(sourceData)); // assertThat(sourceParser.nextToken(), equalTo(JsonToken.START_OBJECT)); // assertThat(sourceParser.nextToken(), equalTo(JsonToken.FIELD_NAME)); // "value" // assertThat(sourceParser.nextToken(), equalTo(JsonToken.VALUE_STRING)); // assertThat(sourceParser.nextToken(), equalTo(JsonToken.END_OBJECT)); }
public ArtistImpl(JsonParser parser) throws JsonParseException, IOException { if (parser.getCurrentToken() != JsonToken.START_OBJECT) { if (parser.getCurrentToken() == JsonToken.VALUE_NULL) return; throw new IOException( "Expected data to start with an Object. Found " + parser.getCurrentToken()); } while (parser.nextToken() != JsonToken.END_OBJECT) { String fName = parser.getCurrentName(); parser.nextToken(); if (fName.equals("id")) id = parser.getLongValue(); else if (fName.equals("name")) name = parser.getText(); else if (fName.equals("eventDescription")) description = parser.getText(); else if (fName.equals("urlOfficialWebsite")) siteUrl = JFlyUtils.parseURL(parser.getText()); else if (fName.equals("urlMySpace")) myspaceUrl = JFlyUtils.parseURL(parser.getText()); else if (fName.equals("urlFacebook")) facebookUrl = JFlyUtils.parseURL(parser.getText()); else if (fName.equals("twitterScreenName")) twitterScreenName = parser.getText(); else if (fName.equals("urlAudio")) audioUrl = JFlyUtils.parseURL(parser.getText()); else if (fName.equals("urlPurchaseMusic")) purchaseUrl = JFlyUtils.parseURL(parser.getText()); else if (fName.equals("embedAudio")) audioHtml = parser.getText(); else if (fName.equals("embedVideo")) videoHtml = parser.getText(); else if (fName.equals("idMobileFriendly")) mobileFriendly = parser.getBooleanValue(); else if (fName.equals("images")) { if (parser.getCurrentToken().equals(JsonToken.START_ARRAY)) { while (parser.nextToken() != JsonToken.END_ARRAY) { images.add(new ImageMetaImpl(parser)); } } } else if (fName.equals("youtubeVideos")) { if (parser.getCurrentToken().equals(JsonToken.START_ARRAY)) { while (parser.nextToken() != JsonToken.END_ARRAY) { youTubeVideos.add(new YouTubeMetaImpl(parser)); } } } else if (parser.getCurrentToken() == JsonToken.START_OBJECT || parser.getCurrentToken() == JsonToken.START_ARRAY) { parser.skipChildren(); } } // end while }
private List<String> readPersons(JsonParser parser) throws IOException { if (parser.nextToken() != JsonToken.START_ARRAY) { reportIllegal(parser, JsonToken.START_ARRAY); } List<String> persons = new ArrayList<String>(); String str; while ((str = parser.nextTextValue()) != null) { persons.add(str); } verifyCurrent(parser, JsonToken.END_ARRAY); return persons; }
protected MediaContent readMediaContent(JsonParser parser) throws IOException { MediaContent mc = new MediaContent(); if (parser.nextToken() != JsonToken.START_OBJECT) { reportIllegal(parser, JsonToken.START_OBJECT); } // first fast version when field-order is as expected if (parser.nextFieldName(FIELD_MEDIA)) { mc.media = readMedia(parser); if (parser.nextFieldName(FIELD_IMAGES)) { mc.images = readImages(parser); parser.nextToken(); verifyCurrent(parser, JsonToken.END_OBJECT); return mc; } } // and fallback if order was changed for (; parser.getCurrentToken() == JsonToken.FIELD_NAME; parser.nextToken()) { String field = parser.getCurrentName(); Integer I = fullFieldToIndex.get(field); if (I != null) { switch (I) { case FIELD_IX_MEDIA: mc.media = readMedia(parser); continue; case FIELD_IX_IMAGES: mc.images = readImages(parser); continue; } } throw new IllegalStateException("Unexpected field '" + field + "'"); } verifyCurrent(parser, JsonToken.END_OBJECT); if (mc.media == null) throw new IllegalStateException("Missing field: " + FIELD_MEDIA); if (mc.images == null) mc.images = new ArrayList<Image>(); return mc; }
protected static JsonToken _initForReading(JsonParser jp) throws IOException, JsonParseException, JsonMappingException { /* First: must point to a token; if not pointing to one, advance. * This occurs before first read from JsonParser, as well as * after clearing of current token. */ JsonToken t = jp.getCurrentToken(); if (t == null) { // and then we must get something... t = jp.nextToken(); if (t == null) { // [JACKSON-99] Should throw EOFException? throw new EOFException("No content to map to Object due to end of input"); } } return t; }
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(); }
@Override public LocalDateTime deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { // We'll accept either long (timestamp) or array: if (jp.isExpectedStartArrayToken()) { jp.nextToken(); // VALUE_NUMBER_INT int year = jp.getIntValue(); jp.nextToken(); // VALUE_NUMBER_INT int month = jp.getIntValue(); jp.nextToken(); // VALUE_NUMBER_INT int day = jp.getIntValue(); jp.nextToken(); // VALUE_NUMBER_INT int hour = jp.getIntValue(); jp.nextToken(); // VALUE_NUMBER_INT int minute = jp.getIntValue(); jp.nextToken(); // VALUE_NUMBER_INT int second = jp.getIntValue(); // let's leave milliseconds optional? int millisecond = 0; if (jp.nextToken() != JsonToken.END_ARRAY) { // VALUE_NUMBER_INT millisecond = jp.getIntValue(); jp.nextToken(); // END_ARRAY? } if (jp.getCurrentToken() != JsonToken.END_ARRAY) { throw ctxt.wrongTokenException(jp, JsonToken.END_ARRAY, "after LocalDateTime ints"); } return new LocalDateTime(year, month, day, hour, minute, second, millisecond); } switch (jp.getCurrentToken()) { case VALUE_NUMBER_INT: return new LocalDateTime(jp.getLongValue()); case VALUE_STRING: DateTime local = parseLocal(jp); if (local == null) { return null; } return local.toLocalDateTime(); } throw ctxt.wrongTokenException(jp, JsonToken.START_ARRAY, "expected JSON Array or Number"); }
private Collection<String> deserializeUsingCustom( JsonParser jp, DeserializationContext ctxt, Collection<String> result, final JsonDeserializer<String> deser) throws IOException { JsonToken t; while ((t = jp.nextToken()) != JsonToken.END_ARRAY) { String value; if (t == JsonToken.VALUE_NULL) { value = deser.getNullValue(); } else { value = deser.deserialize(jp, ctxt); } result.add(value); } return result; }