/** 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(); } }
/** * Constructs a configuration file from a past configuration file that was saved to the disk. * * @param fileName - the path to the file on disk * @throws IOException - if there is any problem reading the file */ public Configuration(final String fileName) throws IOException { final JsonFactory jf = new JsonFactory(); final JsonParser jp = jf.createParser(new File(fileName)); jp.nextToken(); while (jp.nextToken() != JsonToken.END_OBJECT) { final String fieldName = jp.getCurrentName(); jp.nextToken(); switch (fieldName) { case IN_FILE_KEY: this.inputFileName = jp.getText(); break; case IN_FILE_DIR_KEY: this.inputFileDirName = jp.getText(); break; case SPLIT_PATTERN_KEY: this.splitPattern = jp.getText(); break; case OUT_FILE_KEY: this.outDirName = jp.getText(); break; case EXEC_LOC_KEY: this.execPath = jp.getText(); break; case NUM_PROCESSES_KEY: this.numberOfThreads = jp.getIntValue(); break; case STATS_KEY: this.makeStats = jp.getBooleanValue(); break; case NUM_HEADER_KEY: this.numberOfHeaderLines = jp.getIntValue(); break; case DEFAULT_MERGE_KEY: if (jp.getBooleanValue()) { this.mergeMethod = 0; } break; case CUSTOM_MERGE_KEY: if (jp.getBooleanValue()) { this.mergeMethod = 1; } break; case EXTERNAL_MERGE_KEY: if (jp.getBooleanValue()) { this.mergeMethod = 2; } break; case ARGUMENT_KEY: this.argument = jp.getText(); break; case OUTPUT_FMT_KEY: this.outputFmt = jp.getBooleanValue(); break; default: assert (false); } } jp.close(); }
private <T> String processData( final CrestApiProcessor<T> processor, final CrestContainer<T> container, final String data) { String next = null; try { final JsonFactory parserFactory = new JsonFactory(); final JsonParser jsonParser = parserFactory.createParser(data); jsonParser.nextToken(); while (jsonParser.nextToken() != JsonToken.END_OBJECT) { final String fieldname = jsonParser.getCurrentName(); jsonParser.nextToken(); switch (fieldname) { case "totalCount": container.setTotalCount(jsonParser.getIntValue()); break; case "pageCount": container.setPageCount(jsonParser.getIntValue()); break; case "items": processItems(processor, container, jsonParser); break; case "next": next = processNext(jsonParser); break; default: break; } } } catch (final IOException e) { if (LOGGER.isWarnEnabled()) { LOGGER.warn("Problems while parsing json data: " + e.getMessage(), e); } } return next; }
@Override public LocalDate deserialize(JsonParser parser, DeserializationContext context) throws IOException { switch (parser.getCurrentToken()) { case START_ARRAY: if (parser.nextToken() == JsonToken.END_ARRAY) { return null; } int year = parser.getIntValue(); parser.nextToken(); int month = parser.getIntValue(); parser.nextToken(); int day = parser.getIntValue(); if (parser.nextToken() != JsonToken.END_ARRAY) { throw context.wrongTokenException(parser, JsonToken.END_ARRAY, "Expected array to end."); } return LocalDate.of(year, month, day); case VALUE_STRING: String string = parser.getText().trim(); if (string.length() == 0) { return null; } return LocalDate.parse(string, ISO_DATE_OPTIONAL_TIME); } throw context.wrongTokenException(parser, JsonToken.START_ARRAY, "Expected array or string."); }
@Override protected void read(ImpExt.Builder ext, JsonParser par) throws IOException { switch (getCurrentName(par)) { case "billing_id": for (startArray(par); endArray(par); par.nextToken()) { ext.addBillingId(par.getLongValue()); } break; case "publisher_settings_list_id": for (startArray(par); endArray(par); par.nextToken()) { ext.addPublisherSettingsListId(par.getLongValue()); } break; case "allowed_vendor_type": for (startArray(par); endArray(par); par.nextToken()) { ext.addAllowedVendorType(par.getIntValue()); } break; case "publisher_parameter": for (startArray(par); endArray(par); par.nextToken()) { ext.addPublisherParameter(par.getText()); } break; } }
private void verifyFromMap(String input) throws Exception { JsonParser p = new JsonFactory().createParser(input); assertEquals(JsonToken.START_OBJECT, p.nextToken()); assertEquals(JsonToken.FIELD_NAME, p.nextToken()); assertEquals(FIELD4, getAndVerifyText(p)); assertEquals(JsonToken.VALUE_STRING, p.nextToken()); assertEquals(TEXT2, getAndVerifyText(p)); assertEquals(JsonToken.FIELD_NAME, p.nextToken()); assertEquals(FIELD3, getAndVerifyText(p)); assertEquals(JsonToken.VALUE_NUMBER_INT, p.nextToken()); assertEquals(-1, p.getIntValue()); assertEquals(JsonToken.FIELD_NAME, p.nextToken()); assertEquals(FIELD2, getAndVerifyText(p)); assertEquals(JsonToken.START_ARRAY, p.nextToken()); assertEquals(JsonToken.END_ARRAY, p.nextToken()); assertEquals(JsonToken.FIELD_NAME, p.nextToken()); assertEquals(FIELD1, getAndVerifyText(p)); assertEquals(JsonToken.VALUE_NUMBER_FLOAT, p.nextToken()); assertEquals(DOUBLE_VALUE, p.getDoubleValue(), 0); assertEquals(JsonToken.END_OBJECT, p.nextToken()); assertNull(p.nextToken()); p.close(); }
@Override protected Byte _parseByte(JsonParser jp, DeserializationContext ctxt) throws IOException { JsonToken t = jp.getCurrentToken(); Integer value = null; if (t == JsonToken.VALUE_NUMBER_INT || t == JsonToken.VALUE_NUMBER_FLOAT) { // coercing should work too value = jp.getIntValue(); } else if (t == JsonToken.VALUE_STRING) { // let's do implicit re-parse String text = jp.getText().trim(); try { int len = text.length(); if (len == 0) { return getEmptyValue(); } value = NumberInput.parseInt(text); } catch (IllegalArgumentException iae) { throw ctxt.weirdStringException(_valueClass, "not a valid Byte value"); // NOSONAR } } if (value != null) { // So far so good: but does it fit? if (value < Byte.MIN_VALUE || value > Byte.MAX_VALUE) { throw ctxt.weirdStringException( _valueClass, "overflow, value can not be represented as 8-bit value"); } return (byte) (int) value; } if (t == JsonToken.VALUE_NULL) { return getNullValue(); } throw ctxt.mappingException(_valueClass, t); }
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(); }
private void verifyFromArray(String input) throws Exception { JsonParser p = new JsonFactory().createParser(new StringReader(input)); assertEquals(JsonToken.START_ARRAY, p.nextToken()); assertEquals(JsonToken.VALUE_STRING, p.nextToken()); assertEquals(TEXT1, getAndVerifyText(p)); assertEquals(JsonToken.VALUE_NUMBER_INT, p.nextToken()); assertEquals(3, p.getIntValue()); assertEquals(JsonToken.START_OBJECT, p.nextToken()); assertEquals(JsonToken.FIELD_NAME, p.nextToken()); assertEquals(FIELD1, getAndVerifyText(p)); assertEquals(JsonToken.VALUE_TRUE, p.nextToken()); assertEquals(JsonToken.FIELD_NAME, p.nextToken()); assertEquals(FIELD2, getAndVerifyText(p)); assertEquals(JsonToken.START_ARRAY, p.nextToken()); assertEquals(JsonToken.END_ARRAY, p.nextToken()); assertEquals(JsonToken.END_OBJECT, p.nextToken()); assertEquals(JsonToken.VALUE_FALSE, p.nextToken()); assertEquals(JsonToken.END_ARRAY, p.nextToken()); assertNull(p.nextToken()); p.close(); }
public static RoomLocationReturn fromServerJson(JsonParser p) throws JsonParseException, IOException { RoomLocationReturn ret = new RoomLocationReturn(); RoomLocationEntry entry = new RoomLocationEntry(); while (p.nextToken() != JsonToken.END_OBJECT) { String fieldName = p.getCurrentName(); if (KEY_BUILDING.equals(fieldName)) { p.nextToken(); entry.setBuildingName(p.getText()); } else if (KEY_ROOM.equals(fieldName)) { p.nextToken(); entry.setRoomName(p.getText()); } else if (KEY_LATITUDE.equals(fieldName)) { p.nextToken(); entry.setLatitude(p.getDoubleValue()); } else if (KEY_LONGITUDE.equals(fieldName)) { p.nextToken(); entry.setLongitude(p.getDoubleValue()); } else if (KEY_RATING.equals(fieldName)) { p.nextToken(); // We assume that rating <--> productivity (they are interchangeable) entry.setProductivity(p.getDoubleValue()); } else if (KEY_CAPACITY.equals(fieldName)) { p.nextToken(); entry.setCapacity(p.getDoubleValue()); } else if (KEY_CROWD.equals(fieldName)) { p.nextToken(); entry.setAglCrowd(p.getDoubleValue()); } else if (KEY_NUM_SURVEYS.equals(fieldName)) { p.nextToken(); entry.setAglSurveys(p.getIntValue()); } else if (KEY_INTERPOLATED.equals(fieldName)) { p.nextToken(); // take the "[" token List<NoiseEntry> noises = new ArrayList<NoiseEntry>(); while (p.nextToken() != JsonToken.END_ARRAY) { noises.add(NoiseEntry.fromServerJson(p, entry)); } ret.noises = noises; } else if (KEY_COMMENTS.equals(fieldName)) { p.nextToken(); // take the "[" token List<CommentEntry> comments = new ArrayList<CommentEntry>(); while (p.nextToken() != JsonToken.END_ARRAY) { comments.add(CommentEntry.fromServerJson(p, entry)); } ret.comments = comments; } } entry.setLocal(false); ret.entry = entry; return ret; }
public void testSimpleArrayWrite() throws Exception { StringWriter sw = new StringWriter(); JsonGenerator gen = new JsonFactory().createGenerator(sw); gen.writeStartArray(); gen.writeNumber(13); gen.writeBoolean(true); gen.writeString("foobar"); gen.writeEndArray(); gen.close(); String docStr = sw.toString(); JsonParser jp = createParserUsingReader(docStr); assertEquals(JsonToken.START_ARRAY, jp.nextToken()); assertEquals(JsonToken.VALUE_NUMBER_INT, jp.nextToken()); assertEquals(13, jp.getIntValue()); assertEquals(JsonToken.VALUE_TRUE, jp.nextToken()); assertEquals(JsonToken.VALUE_STRING, jp.nextToken()); assertEquals("foobar", jp.getText()); assertEquals(JsonToken.END_ARRAY, jp.nextToken()); assertEquals(null, jp.nextToken()); jp.close(); }
/** * @param args * @throws IOException * @throws JsonParseException */ public static void main(String[] args) throws JsonParseException, IOException { JsonFactory jfactory = new JsonFactory(); JsonParser jParser = jfactory.createJsonParser(new File(FILE_PATH)); // loop until token equal to "}" while (jParser.nextToken() != JsonToken.END_OBJECT) { String fieldname = jParser.getCurrentName(); if ("name".equals(fieldname)) { // current token is "name", // move to next, which is "name"'s value jParser.nextToken(); System.out.println(jParser.getText()); // display mkyong } if ("age".equals(fieldname)) { // current token is "age", // move to next, which is "name"'s value jParser.nextToken(); System.out.println(jParser.getIntValue()); // display 29 } if ("messages".equals(fieldname)) { jParser.nextToken(); // current token is "[", move next // messages is array, loop until token equal to "]" while (jParser.nextToken() != JsonToken.END_ARRAY) { // display msg1, msg2, msg3 System.out.println(jParser.getText()); } } } jParser.close(); }
/* (non-Javadoc) * @see org.codehaus.jackson.map.JsonDeserializer#deserialize(org.codehaus.jackson.JsonParser, org.codehaus.jackson.map.DeserializationContext) */ @Override public Quorum deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonToken token = jp.getCurrentToken(); switch (token) { case VALUE_STRING: { return new Quorum(Quora.fromString(jp.getText())); } case VALUE_NUMBER_INT: { return new Quorum(jp.getIntValue()); } case VALUE_NULL: { return null; } default: break; } throw ctxt.mappingException(Quorum.class); }
@Override public Enum<?> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonToken curr = jp.getCurrentToken(); // Usually should just get string value: if (curr == JsonToken.VALUE_STRING || curr == JsonToken.FIELD_NAME) { String name = jp.getText(); Enum<?> result = _resolver.findEnum(name); if (result == null && !ctxt.isEnabled(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)) { throw ctxt.weirdStringException( name, _resolver.getEnumClass(), "value not one of declared Enum instance names"); } return result; } // But let's consider int acceptable as well (if within ordinal range) if (curr == JsonToken.VALUE_NUMBER_INT) { /* ... unless told not to do that. :-) * (as per [JACKSON-412] */ if (ctxt.isEnabled(DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS)) { throw ctxt.mappingException( "Not allowed to deserialize Enum value out of JSON number (disable DeserializationConfig.DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS to allow)"); } int index = jp.getIntValue(); Enum<?> result = _resolver.getEnum(index); if (result == null && !ctxt.isEnabled(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)) { throw ctxt.weirdNumberException( Integer.valueOf(index), _resolver.getEnumClass(), "index value outside legal index range [0.." + _resolver.lastValidIndex() + "]"); } return result; } throw ctxt.mappingException(_resolver.getEnumClass()); }
@Override public OffsetTime deserialize(JsonParser parser, DeserializationContext context) throws IOException { if (parser.hasToken(JsonToken.VALUE_STRING)) { String string = parser.getText().trim(); if (string.length() == 0) { return null; } try { return OffsetTime.parse(string, _formatter); } catch (DateTimeException e) { _rethrowDateTimeException(parser, context, e, string); } } if (!parser.isExpectedStartArrayToken()) { if (parser.hasToken(JsonToken.VALUE_EMBEDDED_OBJECT)) { return (OffsetTime) parser.getEmbeddedObject(); } throw context.wrongTokenException(parser, JsonToken.START_ARRAY, "Expected array or string."); } int hour = parser.nextIntValue(-1); if (hour == -1) { JsonToken t = parser.getCurrentToken(); if (t == JsonToken.END_ARRAY) { return null; } if (t != JsonToken.VALUE_NUMBER_INT) { _reportWrongToken(parser, context, JsonToken.VALUE_NUMBER_INT, "hours"); } hour = parser.getIntValue(); } int minute = parser.nextIntValue(-1); if (minute == -1) { JsonToken t = parser.getCurrentToken(); if (t == JsonToken.END_ARRAY) { return null; } if (t != JsonToken.VALUE_NUMBER_INT) { _reportWrongToken(parser, context, JsonToken.VALUE_NUMBER_INT, "minutes"); } minute = parser.getIntValue(); } int partialSecond = 0; int second = 0; if (parser.nextToken() == JsonToken.VALUE_NUMBER_INT) { second = parser.getIntValue(); if (parser.nextToken() == JsonToken.VALUE_NUMBER_INT) { partialSecond = parser.getIntValue(); if (partialSecond < 1_000 && !context.isEnabled(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS)) { partialSecond *= 1_000_000; // value is milliseconds, convert it to nanoseconds } parser.nextToken(); } } if (parser.getCurrentToken() == JsonToken.VALUE_STRING) { OffsetTime t = OffsetTime.of(hour, minute, second, partialSecond, ZoneOffset.of(parser.getText())); if (parser.nextToken() != JsonToken.END_ARRAY) { _reportWrongToken(parser, context, JsonToken.END_ARRAY, "timezone"); } return t; } throw context.wrongTokenException( parser, JsonToken.VALUE_STRING, "Expected string for TimeZone after numeric values"); }
private void parseField( List<String> fieldNames, List<ColumnMetaData.Rep> fieldTypes, Row.RowBuilder rowBuilder, JsonParser parser) throws IOException { final String fieldName = parser.getCurrentName(); // Move to next token, which is name's value JsonToken token = parser.nextToken(); int i = fieldNames.indexOf(fieldName); if (i < 0) { return; } ColumnMetaData.Rep type = fieldTypes.get(i); switch (token) { case VALUE_NUMBER_INT: if (type == null) { type = ColumnMetaData.Rep.INTEGER; } // fall through case VALUE_NUMBER_FLOAT: if (type == null) { type = ColumnMetaData.Rep.FLOAT; } switch (type) { case BYTE: rowBuilder.set(i, parser.getByteValue()); break; case SHORT: rowBuilder.set(i, parser.getShortValue()); break; case INTEGER: rowBuilder.set(i, parser.getIntValue()); break; case LONG: rowBuilder.set(i, parser.getLongValue()); break; case FLOAT: rowBuilder.set(i, parser.getFloatValue()); break; case DOUBLE: rowBuilder.set(i, parser.getDoubleValue()); break; } break; case VALUE_TRUE: rowBuilder.set(i, true); break; case VALUE_FALSE: rowBuilder.set(i, false); break; case VALUE_NULL: break; case VALUE_STRING: default: if (type == ColumnMetaData.Rep.JAVA_SQL_TIMESTAMP) { try { final Date parse = UTC_TIMESTAMP_FORMAT.parse(parser.getText()); rowBuilder.set(i, parse.getTime()); } catch (ParseException e) { // ignore bad value } } else { rowBuilder.set(i, parser.getText()); } break; } }
/** Parses the output of a {@code topN} query, sending the results to a {@link Sink}. */ private void parse( QueryType queryType, InputStream in, Sink sink, List<String> fieldNames, List<ColumnMetaData.Rep> fieldTypes, Page page) { final JsonFactory factory = new JsonFactory(); final Row.RowBuilder rowBuilder = Row.newBuilder(fieldNames.size()); if (CalcitePrepareImpl.DEBUG) { try { final byte[] bytes = AvaticaUtils.readFullyToBytes(in); System.out.println("Response: " + new String(bytes)); in = new ByteArrayInputStream(bytes); } catch (IOException e) { throw Throwables.propagate(e); } } try (final JsonParser parser = factory.createParser(in)) { switch (queryType) { case TOP_N: if (parser.nextToken() == JsonToken.START_ARRAY && parser.nextToken() == JsonToken.START_OBJECT) { expectScalarField(parser, "timestamp"); if (parser.nextToken() == JsonToken.FIELD_NAME && parser.getCurrentName().equals("result") && parser.nextToken() == JsonToken.START_ARRAY) { while (parser.nextToken() == JsonToken.START_OBJECT) { // loop until token equal to "}" parseFields(fieldNames, fieldTypes, rowBuilder, parser); sink.send(rowBuilder.build()); rowBuilder.reset(); } } } break; case SELECT: if (parser.nextToken() == JsonToken.START_ARRAY && parser.nextToken() == JsonToken.START_OBJECT) { page.pagingIdentifier = null; page.offset = -1; expectScalarField(parser, "timestamp"); if (parser.nextToken() == JsonToken.FIELD_NAME && parser.getCurrentName().equals("result") && parser.nextToken() == JsonToken.START_OBJECT) { if (parser.nextToken() == JsonToken.FIELD_NAME && parser.getCurrentName().equals("pagingIdentifiers") && parser.nextToken() == JsonToken.START_OBJECT) { switch (parser.nextToken()) { case FIELD_NAME: page.pagingIdentifier = parser.getCurrentName(); if (parser.nextToken() == JsonToken.VALUE_NUMBER_INT) { page.offset = parser.getIntValue(); } expect(parser, JsonToken.END_OBJECT); break; case END_OBJECT: } } if (parser.nextToken() == JsonToken.FIELD_NAME && parser.getCurrentName().equals("events") && parser.nextToken() == JsonToken.START_ARRAY) { while (parser.nextToken() == JsonToken.START_OBJECT) { expectScalarField(parser, "segmentId"); expectScalarField(parser, "offset"); if (parser.nextToken() == JsonToken.FIELD_NAME && parser.getCurrentName().equals("event") && parser.nextToken() == JsonToken.START_OBJECT) { parseFields(fieldNames, fieldTypes, rowBuilder, parser); sink.send(rowBuilder.build()); rowBuilder.reset(); } expect(parser, JsonToken.END_OBJECT); } parser.nextToken(); } } } break; case GROUP_BY: if (parser.nextToken() == JsonToken.START_ARRAY) { while (parser.nextToken() == JsonToken.START_OBJECT) { expectScalarField(parser, "version"); expectScalarField(parser, "timestamp"); if (parser.nextToken() == JsonToken.FIELD_NAME && parser.getCurrentName().equals("event") && parser.nextToken() == JsonToken.START_OBJECT) { parseFields(fieldNames, fieldTypes, rowBuilder, parser); sink.send(rowBuilder.build()); rowBuilder.reset(); } expect(parser, JsonToken.END_OBJECT); } } } } catch (IOException | InterruptedException e) { throw Throwables.propagate(e); } }
private Image readImage(JsonParser parser) throws IOException { boolean haveWidth = false; boolean haveHeight = false; Image image = new Image(); if (parser.nextFieldName(FIELD_URI)) { image.uri = parser.nextTextValue(); if (parser.nextFieldName(FIELD_TITLE)) { image.title = parser.nextTextValue(); if (parser.nextFieldName(FIELD_WIDTH)) { image.width = parser.nextIntValue(-1); haveWidth = true; if (parser.nextFieldName(FIELD_HEIGHT)) { image.height = parser.nextIntValue(-1); haveHeight = true; if (parser.nextFieldName(FIELD_SIZE)) { image.size = Image.Size.valueOf(parser.nextTextValue()); parser.nextToken(); verifyCurrent(parser, JsonToken.END_OBJECT); return image; } } } } } for (; parser.getCurrentToken() == JsonToken.FIELD_NAME; parser.nextToken()) { String field = parser.getCurrentName(); // read value token (or START_ARRAY) parser.nextToken(); Integer I = fullFieldToIndex.get(field); if (I != null) { switch (I) { case FIELD_IX_URI: image.uri = parser.getText(); continue; case FIELD_IX_TITLE: image.title = parser.getText(); continue; case FIELD_IX_WIDTH: image.width = parser.getIntValue(); haveWidth = true; continue; case FIELD_IX_HEIGHT: image.height = parser.getIntValue(); haveHeight = true; continue; case FIELD_IX_SIZE: image.size = Image.Size.valueOf(parser.getText()); continue; } } throw new IllegalStateException("Unexpected field '" + field + "'"); } if (image.uri == null) throw new IllegalStateException("Missing field: " + FIELD_URI); if (!haveWidth) throw new IllegalStateException("Missing field: " + FIELD_WIDTH); if (!haveHeight) throw new IllegalStateException("Missing field: " + FIELD_HEIGHT); if (image.size == null) throw new IllegalStateException("Missing field: " + FIELD_SIZE); verifyCurrent(parser, JsonToken.END_OBJECT); return image; }
/** * Method for copying contents of the current event that the given parser instance points to. Note * that the method <b>will not</b> copy any other events, such as events contained within Json * Array or Object structures. * * <p>Calling this method will not advance the given parser, although it may cause parser to * internally process more data (if it lazy loads contents of value events, for example) */ @Override public void copyCurrentEvent(JsonParser jp) throws IOException, JsonProcessingException { switch (jp.getCurrentToken()) { case START_OBJECT: writeStartObject(); break; case END_OBJECT: writeEndObject(); break; case START_ARRAY: writeStartArray(); break; case END_ARRAY: writeEndArray(); break; case FIELD_NAME: writeFieldName(jp.getCurrentName()); break; case VALUE_STRING: writeString(jp.getText()); break; case VALUE_NUMBER_INT: switch (jp.getNumberType()) { case INT: writeNumber(jp.getIntValue()); break; case BIG_INTEGER: writeNumber(jp.getBigIntegerValue()); break; default: writeNumber(jp.getLongValue()); } break; case VALUE_NUMBER_FLOAT: switch (jp.getNumberType()) { case BIG_DECIMAL: writeNumber(jp.getDecimalValue()); break; case FLOAT: writeNumber(jp.getFloatValue()); break; default: writeNumber(jp.getDoubleValue()); } break; case VALUE_TRUE: writeBoolean(true); break; case VALUE_FALSE: writeBoolean(false); break; case VALUE_NULL: writeNull(); break; case VALUE_EMBEDDED_OBJECT: writeObject(jp.getEmbeddedObject()); break; default: throw new IllegalStateException(); } }
@Override public Record deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { JsonToken t = jp.getCurrentToken(); SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); String id = null; String type = null; Date creationDate = null; JsonToken currentToken = null; Map<String, Field> fields = new HashMap<>(); boolean processingFields = false; while ((currentToken = jp.nextValue()) != null) { switch (currentToken) { case START_OBJECT: processingFields = true; break; case END_OBJECT: processingFields = true; break; case VALUE_NUMBER_INT: try { fields.put( jp.getCurrentName(), new Field(jp.getCurrentName(), FieldType.INT, jp.getIntValue())); } catch (JsonParseException ex) { fields.put( jp.getCurrentName(), new Field(jp.getCurrentName(), FieldType.LONG, jp.getLongValue())); } break; case VALUE_NUMBER_FLOAT: try { fields.put( jp.getCurrentName(), new Field(jp.getCurrentName(), FieldType.FLOAT, jp.getFloatValue())); } catch (JsonParseException ex) { fields.put( jp.getCurrentName(), new Field(jp.getCurrentName(), FieldType.DOUBLE, jp.getDoubleValue())); } break; case VALUE_FALSE: case VALUE_TRUE: fields.put( jp.getCurrentName(), new Field(jp.getCurrentName(), FieldType.BOOLEAN, jp.getBooleanValue())); break; case START_ARRAY: logger.info(jp.getCurrentName()); break; case END_ARRAY: break; case VALUE_STRING: if (jp.getCurrentName() != null) { switch (jp.getCurrentName()) { case "id": id = jp.getValueAsString(); break; case "type": type = jp.getValueAsString(); break; case "creationDate": try { creationDate = sdf.parse(jp.getValueAsString()); // "Thu Sep 08 12:11:08 CEST 2016\" } catch (ParseException e) { e.printStackTrace(); } break; default: fields.put( jp.getCurrentName(), new Field(jp.getCurrentName(), FieldType.STRING, jp.getValueAsString())); break; } } break; default: break; } } Record record = new StandardRecord(type); record.setId(id); record.setType(type); record.setTime(creationDate); record.setFields(fields); return record; }