/** 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(); } }
/* * (non-Javadoc) * * @see * org.codehaus.jackson.map.JsonDeserializer#deserialize(org.codehaus.jackson * .JsonParser, org.codehaus.jackson.map.DeserializationContext) */ @Override public NamedErlangFunction deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonToken token = jp.getCurrentToken(); if (JsonToken.START_OBJECT.equals(token)) { String mod = null; String fun = null; while (!JsonToken.END_OBJECT.equals(token)) { String field = jp.getCurrentName(); if (Constants.FL_SCHEMA_FUN_MOD.equals(field)) { jp.nextToken(); mod = jp.getText(); } else if (Constants.FL_SCHEMA_FUN_FUN.equals(field)) { jp.nextToken(); fun = jp.getText(); } token = jp.nextToken(); } if (mod != null && fun != null) { return new NamedErlangFunction(mod, fun); } else { return null; } } throw ctxt.mappingException(NamedErlangFunction.class); }
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; }
private void parseTagList(Reader in, ITagListHandler handler) throws JsonParseException, IOException, RemoteException { JsonFactory f = new JsonFactory(); JsonParser jp = f.createParser(in); String currName; ITag tag = null; List<ITag> tagList = new ArrayList<ITag>(); jp.nextToken(); // will return JsonToken.START_OBJECT (verify?) while (jp.nextToken() != JsonToken.END_OBJECT) { currName = jp.getCurrentName(); jp.nextToken(); // move to value, or START_OBJECT/START_ARRAY if (currName.equals("tags")) { // contains an object // start items while (jp.nextToken() != JsonToken.END_ARRAY) { if (jp.getCurrentToken() == JsonToken.START_OBJECT) { tag = new ITag(); } else if (jp.getCurrentToken() == JsonToken.END_OBJECT) { tagList.add(tag); tag = null; } currName = jp.getCurrentName(); if (currName == null) continue; jp.nextToken(); if (currName.equals("id")) { tag.uid = jp.getText(); int i = tag.uid.indexOf("/label/"); if (i != -1) { tag.label = tag.uid.substring(i + "/label/".length()); // NOTE: @see ReaderManager#updateTagTypes tag.type = ITag.TYPE_TAG_LABEL; } else if (tag.uid.endsWith("state/com.google/starred")) { tag.label = "state/com.google/starred"; tag.type = ITag.TYPE_TAG_STARRED; } } else if (currName.equals("sortid")) { tag.sortid = jp.getText(); } else { jp.skipChildren(); } } handler.tags(tagList); } else { jp.skipChildren(); } } }
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()); }
protected String _valueDesc() { try { return _desc(_parser.getText()); } catch (Exception e) { return "[N/A]"; } }
@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; }
@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."); }
public final class StringDeserializer extends StdScalarDeserializer { public static final StringDeserializer instance = new StringDeserializer(); public StringDeserializer() { super(java/lang/String); } public volatile Object deserialize(JsonParser jsonparser, DeserializationContext deserializationcontext) { return deserialize(jsonparser, deserializationcontext); } public String deserialize(JsonParser jsonparser, DeserializationContext deserializationcontext) { JsonToken jsontoken = jsonparser.getCurrentToken(); if (jsontoken != JsonToken.VALUE_STRING) goto _L2; else goto _L1 _L1: Object obj = jsonparser.getText(); _L4: return ((String) (obj)); _L2: if (jsontoken != JsonToken.START_ARRAY || !deserializationcontext.isEnabled(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS)) { break; /* Loop/switch isn't completed */ } jsonparser.nextToken(); obj = _parseString(jsonparser, deserializationcontext); if (jsonparser.nextToken() != JsonToken.END_ARRAY) { throw deserializationcontext.wrongTokenException(jsonparser, JsonToken.END_ARRAY, "Attempted to unwrap single value array for single 'String' value but there was more than a single value in the array"); } if (true) goto _L4; else goto _L3 _L3: if (jsontoken == JsonToken.VALUE_EMBEDDED_OBJECT) { jsonparser = ((JsonParser) (jsonparser.getEmbeddedObject())); if (jsonparser == null) { return null; } if (jsonparser instanceof byte[]) { return Base64Variants.getDefaultVariant().encode((byte[])(byte[])jsonparser, false); } else { return jsonparser.toString(); } } jsonparser = jsonparser.getValueAsString(); obj = jsonparser; if (jsonparser == null) { throw deserializationcontext.mappingException(_valueClass, jsontoken); } if (true) goto _L4; else goto _L5 _L5: }
@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); }
/** @param bioID */ private boolean setBioID(String bioID) { boolean toRet = false; try { JsonFactory factory = new JsonFactory(); JsonParser jparser = factory.createParser(bioID); String key = ""; // Get StartObject for JSON, after first { jparser.nextToken(); while (jparser.nextToken() != JsonToken.END_OBJECT) { key = jparser.getText(); if (key.equals("id")) { key = jparser.nextTextValue(); // Set bioID in Experiment selExp.setBioID(key); toRet = true; } else { jparser.skipChildren(); } } jparser.close(); } catch (JsonParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return toRet; }
protected final String _locateTypeId( JsonParser paramJsonParser, DeserializationContext paramDeserializationContext) throws IOException { if (!paramJsonParser.isExpectedStartArrayToken()) { if (this._defaultImpl != null) { return this._idResolver.idFromBaseType(); } throw paramDeserializationContext.wrongTokenException( paramJsonParser, JsonToken.START_ARRAY, "need JSON Array to contain As.WRAPPER_ARRAY type information for class " + baseTypeName()); } if (paramJsonParser.nextToken() == JsonToken.VALUE_STRING) { paramDeserializationContext = paramJsonParser.getText(); paramJsonParser.nextToken(); return paramDeserializationContext; } if (this._defaultImpl != null) { return this._idResolver.idFromBaseType(); } throw paramDeserializationContext.wrongTokenException( paramJsonParser, JsonToken.VALUE_STRING, "need JSON String that contains type id (for subtype of " + baseTypeName() + ")"); }
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 parseItemIdList(Reader in, IItemIdListHandler handler) throws JsonParseException, IOException, RemoteException { JsonFactory f = new JsonFactory(); JsonParser jp = f.createParser(in); String currName; List<String> idList = new ArrayList<String>(); jp.nextToken(); // will return JsonToken.START_OBJECT (verify?) while (jp.nextToken() != JsonToken.END_OBJECT) { currName = jp.getCurrentName(); jp.nextToken(); // move to value, or START_OBJECT/START_ARRAY if (currName.equals("itemRefs")) { // contains an object // start items while (jp.nextToken() != JsonToken.END_ARRAY) { currName = jp.getCurrentName(); if (currName == null) continue; jp.nextToken(); if (currName.equals("id")) { idList.add(Utils.dec2Hex(jp.getText())); // convert dec to hex } else { jp.skipChildren(); } } handler.items(idList); } else { jp.skipChildren(); } } }
@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; } }
@Override public Integer deserialize(JsonParser parser, DeserializationContext context) throws IOException { JsonToken t = parser.getCurrentToken(); if (t == JsonToken.VALUE_NUMBER_INT || t == JsonToken.VALUE_NUMBER_FLOAT) { // coercing should work too return rangeCheckedInteger(parser, context); } if (t == JsonToken.VALUE_STRING) { // let's do implicit re-parse String text = parser.getText().trim(); try { int len = text.length(); if (len > 9) { return rangeCheckedInteger(parser, context); } if (len == 0) { return null; } return Integer.valueOf(NumberInput.parseInt(text)); } catch (IllegalArgumentException iae) { throw context.weirdStringException(_valueClass, "not a valid Integer value"); // NOSONAR } } if (t == JsonToken.VALUE_NULL) { return null; } // Otherwise, no can do: throw context.mappingException(_valueClass); }
@Override public LocalDateTime deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { String date = jp.getText(); return LocalDateTimeJsonSerializer.formatter.parseLocalDateTime(date); }
/** {@inheritDoc} */ @Override public ZonedDateTime deserialize( JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { String value = jsonParser.getText(); if (value == null || value.isEmpty()) { return null; } return ZonedDateTime.parse(value, DATE_FORMAT); }
/** * Unmarshal. * * @param parser the parser * @param idNull the id null * @param expectedClass the expected class * @return the id * @throws IOException Signals that an I/O exception has occurred. */ public static Id unmarshal(JsonParser parser, @Nullable Id idNull, Class<Id> expectedClass) throws IOException { JsonToken token = parser.getCurrentToken(); if (token == JsonToken.VALUE_EMBEDDED_OBJECT) { ObjectId objectId = (ObjectId) parser.getEmbeddedObject(); return Id.of(objectId.getTime(), objectId.getMachine(), objectId.getInc()); } return Id.fromString(parser.getText()); }
private String processNext(final JsonParser jsonParser) throws IOException { String next = null; jsonParser.nextToken(); if (JsonPaths.HREF.equals(jsonParser.getCurrentName())) { jsonParser.nextToken(); next = jsonParser.getText(); jsonParser.nextToken(); } return next; }
@Override public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy"); String date = jp.getText(); try { return format.parse(date); } catch (ParseException e) { throw new RuntimeException(e); } }
@Override public Set<String> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonToken token = jp.getCurrentToken(); if (token.isScalarValue()) { String list = jp.getText(); list = list.replaceAll("\\s+", ","); return new LinkedHashSet<String>( Arrays.asList(StringUtils.commaDelimitedListToStringArray(list))); } return jp.readValueAs(new TypeReference<Set<String>>() {}); }
@Override public Timestamp deserialize(JsonParser jsonparser, DeserializationContext deserializationcontext) throws IOException, JsonProcessingException { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String date = jsonparser.getText(); try { return new Timestamp(format.parse(date).getTime()); } catch (ParseException e) { throw new RuntimeException(e); } }
@Override public LocalDate deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { JsonToken t = jp.getCurrentToken(); if (t == JsonToken.VALUE_STRING) { String str = jp.getText().trim(); return ISODateTimeFormat.dateTimeParser().parseDateTime(str).toLocalDate(); } if (t == JsonToken.VALUE_NUMBER_INT) { return new LocalDate(jp.getLongValue()); } throw ctxt.mappingException(handledType()); }
/** * 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(); }
/** * @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(); }
@Override public Date deserialize(JsonParser parser, DeserializationContext context) throws IOException, JsonProcessingException { String dataString = parser.getText(); Date data = null; if (dataString.length() > 8) // Eh somente data data = DateFormater.yyyyMMdd(dataString); else data = DateFormater.HHmmss(dataString); // Eh somente hora return data; }
@Override public Boolean deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { String s = jsonParser.getText(); if (s == null) { return false; } s = s.toLowerCase(); return "true".equals(s) || "yes".equals(s); }
@Override protected Void doInBackground(String... urls) { locationsList = new ArrayList<>(); final JsonFactory jfactory = new JsonFactory(); JsonParser jParser = null; try { jParser = jfactory.createParser(new URL(urls[0])); Log.d("MyLogs", "URL - " + urls[0]); while (jParser.nextToken() != JsonToken.END_ARRAY) { String fieldname = jParser.getCurrentName(); if ("id".equals(fieldname)) { map = new HashMap<>(); jParser.nextToken(); map.put("id", jParser.getText()); } else if ("name".equals(fieldname)) { jParser.nextToken(); map.put("name", jParser.getText()); locationsList.add(map); } } } catch (IOException | RuntimeException e) { e.printStackTrace(); } finally { if (jParser != null) { try { jParser.close(); } catch (IOException e) { e.printStackTrace(); } } } list = new ArrayList<>(); for (HashMap<String, String> a : locationsList) { list.add(a.get("name")); } return null; }
@Override public String read(JsonParser parser) throws IOException, JsonReadException { try { String v = parser.getText(); String error = getKeyFormatError(v); if (error != null) { throw new JsonReadException( "bad format for app secret: " + error, parser.getTokenLocation()); } parser.nextToken(); return v; } catch (JsonParseException ex) { throw JsonReadException.fromJackson(ex); } }