/** 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); }
/** @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; }
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 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; } }
/** * 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; }
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 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."); }
/** * Method for copying contents of the current event <b>and following events that it encloses</b> * the given parser instance points to. * * <p>So what constitutes enclosing? Here is the list of events that have associated enclosed * events that will get copied: * * <ul> * <li>{@link JsonToken#START_OBJECT}: all events up to and including matching (closing) {@link * JsonToken#END_OBJECT} will be copied * <li>{@link JsonToken#START_ARRAY} all events up to and including matching (closing) {@link * JsonToken#END_ARRAY} will be copied * <li>{@link JsonToken#FIELD_NAME} the logical value (which can consist of a single scalar * value; or a sequence of related events for structured types (Json Arrays, Objects)) will * be copied along with the name itself. So essentially the whole <b>field entry</b> (name * and value) will be copied. * </ul> * * <p>After calling this method, parser will point to the <b>last event</b> that was copied. This * will either be the event parser already pointed to (if there were no enclosed events), or the * last enclosed event copied. */ @Override public 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); } }
@Override public void parse(T translator, JsonParser jsonParser) throws IOException { JsonParserWrapper wrapper = new JsonParserWrapper(jsonParser); wrapper.setShouldThrowExceptions(shouldThrowFieldExceptions()); if (jsonParser.getCurrentToken() == null) { jsonParser.nextToken(); } if (jsonParser.getCurrentToken() != JsonToken.START_OBJECT) { jsonParser.skipChildren(); } else { if (translator instanceof ParseStatusListener) { ((ParseStatusListener) translator).onPreParse(); } while (jsonParser.nextToken() != JsonToken.END_OBJECT) { String key = jsonParser.getCurrentName(); jsonParser.nextToken(); handleParse(translator, wrapper, jsonParser, key); jsonParser.skipChildren(); } if (translator instanceof ParseStatusListener) { ((ParseStatusListener) translator).onParseComplete(); } } }
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() + ")"); }
/** Sends a POST request to obtain an access token. */ private void obtainAccessToken() { try { token = new OAuth2Token(); error = new OAuth2Error(); /* build the request and send it to the token server */ CloseableHttpClient client = HttpClients.createDefault(); HttpPost request = new HttpPost(tokenServer); request.setEntity(new UrlEncodedFormEntity(Utils.mapToList(tokenParams))); CloseableHttpResponse response = client.execute(request); HttpEntity entity = response.getEntity(); /* get the response and parse it */ JsonParser jp = json.getFactory().createParser(entity.getContent()); while (jp.nextToken() != null) { JsonToken jsonToken = jp.getCurrentToken(); switch (jsonToken) { case FIELD_NAME: String name = jp.getCurrentName(); jsonToken = jp.nextToken(); if (name.equals("access_token")) { token.setAccessToken(jp.getValueAsString()); } else if (name.equals("token_type")) { token.setType(OAuth2TokenType.valueOf(jp.getValueAsString().toUpperCase())); } else if (name.equals("expires_in")) { token.setExpiresIn(jp.getValueAsInt()); } else if (name.equals("refresh_token")) { token.setRefreshToken(jp.getValueAsString()); } else if (name.equals("kid")) { token.setKeyId(jp.getValueAsString()); } else if (name.equals("mac_key")) { token.setMacKey(jp.getValueAsString()); } else if (name.equals("mac_algorithm")) { token.setMacAlgorithm(jp.getValueAsString()); } else if (name.equals("error")) { error.setType(OAuth2ErrorType.valueOf(jp.getValueAsString().toUpperCase())); } else if (name.equals("error_description")) { error.setDescription(jp.getValueAsString()); } else if (name.equals("error_uri")) { error.setUri(jp.getValueAsString()); } ready = true; break; default: break; } } jp.close(); response.close(); client.close(); } catch (IOException e) { error.setType(OAuth2ErrorType.SERVER_ERROR); error.setDescription("Failed to obtain access token from the server."); } /* notify all waiting objects */ synchronized (waitObject) { ready = true; waitObject.notifyAll(); } }
@Override public ScimGroup deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { ScimGroup group = new ScimGroup(); Map<ScimGroupMember.Role, List<ScimGroupMember>> roles = new HashMap<ScimGroupMember.Role, List<ScimGroupMember>>(); for (ScimGroupMember.Role role : ScimGroupMember.Role.values()) { roles.put(role, new ArrayList<ScimGroupMember>()); } Set<ScimGroupMember> allMembers = new HashSet<ScimGroupMember>(); while (jp.nextToken() != JsonToken.END_OBJECT) { if (jp.getCurrentToken() == JsonToken.FIELD_NAME) { String fieldName = jp.getCurrentName(); jp.nextToken(); if ("id".equalsIgnoreCase(fieldName)) { group.setId(jp.readValueAs(String.class)); } else if ("displayname".equalsIgnoreCase(fieldName)) { group.setDisplayName(jp.readValueAs(String.class)); } else if ("meta".equalsIgnoreCase(fieldName)) { group.setMeta(jp.readValueAs(ScimMeta.class)); } else if ("schemas".equalsIgnoreCase(fieldName)) { group.setSchemas(jp.readValueAs(String[].class)); } else { String value = fieldName.substring(0, fieldName.length() - 1); ScimGroupMember.Role role; try { role = ScimGroupMember.Role.valueOf(value.toUpperCase()); } catch (IllegalArgumentException ex) { role = null; } if (role != null) { ScimGroupMember[] members = jp.readValueAs(ScimGroupMember[].class); for (ScimGroupMember member : members) { member.setRoles(new ArrayList<ScimGroupMember.Role>()); } roles.get(role).addAll(Arrays.asList(members)); allMembers.addAll(Arrays.asList(members)); } } } } for (ScimGroupMember member : allMembers) { for (ScimGroupMember.Role role : roles.keySet()) { if (roles.get(role).contains(member)) { member.getRoles().add(role); } } } group.setMembers(new ArrayList<ScimGroupMember>(allMembers)); return group; }
private Map<String, Object> readHeaders(JsonParser parser, String jsonMessage) throws Exception { Map<String, Object> headers = new LinkedHashMap<String, Object>(); while (JsonToken.END_OBJECT != parser.nextToken()) { String headerName = parser.getCurrentName(); parser.nextToken(); Object headerValue = this.readHeader(parser, headerName, jsonMessage); headers.put(headerName, headerValue); } return headers; }
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; }
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; }
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(); } } }
public void parseList(List<T> translatorTypes, JsonParser jsonParser) throws IOException { JsonParserWrapper wrapper = new JsonParserWrapper(jsonParser); if (jsonParser.getCurrentToken() == null) { jsonParser.nextToken(); } if (jsonParser.getCurrentToken() == JsonToken.START_ARRAY) { while (jsonParser.nextToken() != JsonToken.END_ARRAY) { translatorTypes.add(wrapper.getCurrentValue(getType(), null)); } } }
@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; }
/** * reads until the next json object * * @return json object wrapper * @throws JsonParseException * @throws IOException */ public JsonObjectReader next() throws JsonParseException, IOException { JsonToken tk = parser.nextToken(); if (isObject) { if (tk == JsonToken.END_OBJECT) return null; } else { if (tk == JsonToken.END_ARRAY) return null; } if (lastObject != null && !lastObject.isParsed()) { throw new IllegalStateException( "The last object must be read complete before the next object can be parsed."); } parser.nextToken(); // { Token return lastObject = new JsonObjectReader(parser); }
// [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(); }
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 parseArray(T[] translatorTypes, JsonParser jsonParser) throws IOException { JsonParserWrapper wrapper = new JsonParserWrapper(jsonParser); if (jsonParser.getCurrentToken() == null) { jsonParser.nextToken(); } if (jsonParser.getCurrentToken() == JsonToken.START_ARRAY) { int count = 0; while (jsonParser.nextToken() != JsonToken.END_ARRAY) { translatorTypes[count] = wrapper.getCurrentValue(getType(), null); count++; } } }
private Map<String, Long> parseUnreadCountList(Reader in) throws JsonParseException, IOException { JsonFactory f = new JsonFactory(); JsonParser jp = f.createParser(in); String currName; String uid = null; Long timestamp = null; int len; String text = null; Map<String, Long> unreadList = new HashMap<String, Long>(); 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("unreadcounts")) { // contains an object // start items while (jp.nextToken() != JsonToken.END_ARRAY) { if (jp.getCurrentToken() == JsonToken.START_OBJECT) { // do nothing } else if (jp.getCurrentToken() == JsonToken.END_OBJECT) { if (!unreadList.containsKey(uid)) unreadList.put(uid, timestamp); } currName = jp.getCurrentName(); if (currName == null) continue; jp.nextToken(); if (currName.equals("id")) { uid = jp.getText(); } else if (currName.equals("newestItemTimestampUsec")) { text = jp.getText(); len = text.length(); if (len > 13) text = jp.getText().substring(0, jp.getText().length() - 6); else if (len > 10) text = jp.getText().substring(0, jp.getText().length() - 3); timestamp = Utils.asLong(text); // millis -> unixtime } else { jp.skipChildren(); } } } else { jp.skipChildren(); } } return unreadList; }
@Override public JSONObject deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { JSONObject ob = new JSONObject(); JsonToken t = jp.getCurrentToken(); if (t == JsonToken.START_OBJECT) { t = jp.nextToken(); } for (; t == JsonToken.FIELD_NAME; t = jp.nextToken()) { String fieldName = jp.getCurrentName(); t = jp.nextToken(); try { switch (t) { case START_ARRAY: ob.put(fieldName, JSONArrayDeserializer.instance.deserialize(jp, ctxt)); continue; case START_OBJECT: ob.put(fieldName, deserialize(jp, ctxt)); continue; case VALUE_STRING: ob.put(fieldName, jp.getText()); continue; case VALUE_NULL: ob.put(fieldName, JSONObject.NULL); continue; case VALUE_TRUE: ob.put(fieldName, Boolean.TRUE); continue; case VALUE_FALSE: ob.put(fieldName, Boolean.FALSE); continue; case VALUE_NUMBER_INT: ob.put(fieldName, jp.getNumberValue()); continue; case VALUE_NUMBER_FLOAT: ob.put(fieldName, jp.getNumberValue()); continue; case VALUE_EMBEDDED_OBJECT: ob.put(fieldName, jp.getEmbeddedObject()); continue; } } catch (JSONException e) { throw ctxt.mappingException("Failed to construct JSONObject: " + e.getMessage()); } throw ctxt.mappingException("Urecognized or unsupported JsonToken type: " + t); } return ob; }
@Override public Visibility deserialize(JsonParser p) throws IOException, JsonParseException { Visibility value; boolean collapsed; String tag; if (p.getCurrentToken() == JsonToken.VALUE_STRING) { collapsed = true; tag = getStringValue(p); p.nextToken(); } else { collapsed = false; expectStartObject(p); tag = readTag(p); } if (tag == null) { throw new JsonParseException(p, "Required field missing: " + TAG_FIELD); } else if ("public".equals(tag)) { value = Visibility.PUBLIC; } else if ("team_only".equals(tag)) { value = Visibility.TEAM_ONLY; } else if ("password".equals(tag)) { value = Visibility.PASSWORD; } else if ("team_and_password".equals(tag)) { value = Visibility.TEAM_AND_PASSWORD; } else if ("shared_folder_only".equals(tag)) { value = Visibility.SHARED_FOLDER_ONLY; } else { value = Visibility.OTHER; skipFields(p); } if (!collapsed) { expectEndObject(p); } return value; }
@Override public Event deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { ObjectMapper mapper = (ObjectMapper) jp.getCodec(); String eventName = jp.nextTextValue(); EventKey ek = new EventKey(namespaceClass.get(), eventName); if (!eventMapping.containsKey(ek)) { ek = new EventKey(Namespace.DEFAULT_NAME, eventName); if (!eventMapping.containsKey(ek)) { return new Event(eventName, Collections.emptyList()); } } List<Object> eventArgs = new ArrayList<Object>(); Event event = new Event(eventName, eventArgs); List<Class<?>> eventClasses = eventMapping.get(ek); int i = 0; while (true) { JsonToken token = jp.nextToken(); if (token == JsonToken.END_ARRAY) { break; } if (i > eventClasses.size() - 1) { log.debug("Event {} has more args than declared in handler: {}", eventName, null); break; } Class<?> eventClass = eventClasses.get(i); Object arg = mapper.readValue(jp, eventClass); eventArgs.add(arg); i++; } return event; }
public static void nextExpect(JsonParser jp, String name) throws IOException { jp.nextToken(); String fieldName = jp.getCurrentName(); if (!fieldName.equals(name)) throw new IOException( "Expected " + name + " element, got: " + fieldName + " " + jp.getCurrentLocation() + " tokenType: [" + jp.getCurrentToken() + "]"); jp.nextToken(); }