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; }
@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; }
// And then one more test just for Bytes-based symbol table public void testByteBasedSymbolTable() throws Exception { // combination of short, medium1/2, long names... final String JSON = aposToQuotes( "{'abc':1, 'abc\\u0000':2, '\\u0000abc':3, " // then some medium + "'abc123':4,'abcd1234':5," + "'abcd1234a':6,'abcd1234abcd':7," + "'abcd1234abcd1':8" + "}"); JsonFactory f = new JsonFactory(); JsonParser p = f.createParser(JSON.getBytes("UTF-8")); ByteQuadsCanonicalizer symbols = _findSymbols(p); assertEquals(0, symbols.size()); _streamThrough(p); assertEquals(8, symbols.size()); p.close(); // and, for fun, try again p = f.createParser(JSON.getBytes("UTF-8")); _streamThrough(p); symbols = _findSymbols(p); assertEquals(8, symbols.size()); p.close(); p = f.createParser(JSON.getBytes("UTF-8")); _streamThrough(p); symbols = _findSymbols(p); assertEquals(8, symbols.size()); p.close(); }
@Override public final MediaContent deserialize(byte[] array) throws IOException { JsonParser parser = constructParser(array); MediaContent mc = readMediaContent(parser); parser.close(); return mc; }
@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"); }
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); } }
/** * Method for reading sequence of Objects from parser stream. * * @since 1.8 */ public <T> MappingIterator<T> readValues(URL src) throws IOException, JsonProcessingException { JsonParser jp = _jsonFactory.createJsonParser(src); if (_schema != null) { jp.setSchema(_schema); } DeserializationContext ctxt = _createDeserializationContext(jp, _config); return new MappingIterator<T>(_valueType, jp, ctxt, _findRootDeserializer(_config, _valueType)); }
private void reportIllegal(JsonParser parser, JsonToken expToken) throws IOException { JsonToken curr = parser.getCurrentToken(); String msg = "Expected token " + expToken + "; got " + curr; if (curr == JsonToken.FIELD_NAME) { msg += " (current field name '" + parser.getCurrentName() + "')"; } msg += ", location: " + parser.getTokenLocation(); throw new IllegalStateException(msg); }
@Override public MediaContent[] deserializeItems(InputStream in, int numberOfItems) throws IOException { MediaContent[] result = new MediaContent[numberOfItems]; JsonParser parser = constructParser(in); for (int i = 0; i < numberOfItems; ++i) { result[i] = readMediaContent(parser); } parser.close(); return result; }
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 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; }
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"); } }
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"); } }
public void run() { Log.d("TAG,", "connect server"); ConnectServer connect = new ConnectServer(GET_CHOOSE_PLACE); ret = connect.connect(request_name, request_value, 1); JsonParser parser = new JsonParser(CASE); ret_place_Name = parser.Parse(ret, "place_Name"); ret_place_X = parser.Parse(ret, "place_X"); ret_place_Y = parser.Parse(ret, "place_Y"); Log.d("TAG,", "name" + ret_place_Name.get(0)); Log.d("TAG,", "X" + ret_place_X.get(0)); Log.d("TAG,", "Y" + ret_place_Y.get(0)); handler.sendEmptyMessage(DOWNLOAD_COMPLETE); }
@Override public ReadablePeriod deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { // TODO: perhaps support array of numbers... // if (jp.isExpectedStartArrayToken()) { ] switch (jp.getCurrentToken()) { case VALUE_NUMBER_INT: // assume it's millisecond count return new Period(jp.getLongValue()); case VALUE_STRING: return new Period(jp.getText()); } throw ctxt.wrongTokenException(jp, JsonToken.START_ARRAY, "expected JSON Number or String"); }
@Override public JSONOptions deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonLocation l = jp.getTokenLocation(); // logger.debug("Reading tree."); TreeNode n = jp.readValueAsTree(); // logger.debug("Tree {}", n); if (n instanceof JsonNode) { return new JSONOptions((JsonNode) n, l); } else { throw new IllegalArgumentException( String.format("Received something other than a JsonNode %s", n)); } }
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"); } } }
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"); } } }
protected JsonNode _bindAndCloseAsTree(JsonParser jp) throws IOException, JsonParseException, JsonMappingException { if (_schema != null) { jp.setSchema(_schema); } try { return _bindAsTree(jp); } finally { try { jp.close(); } catch (IOException ioe) { } } }
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; } } }
/** Offlined version used when we do not use the default deserialization method. */ protected final String[] _deserializeCustom( JsonParser p, DeserializationContext ctxt, String[] old) throws IOException { final ObjectBuffer buffer = ctxt.leaseObjectBuffer(); int ix; Object[] chunk; if (old == null) { ix = 0; chunk = buffer.resetAndStart(); } else { ix = old.length; chunk = buffer.resetAndStart(old, ix); } final JsonDeserializer<String> deser = _elementDeserializer; try { while (true) { /* 30-Dec-2014, tatu: This may look odd, but let's actually call method * that suggest we are expecting a String; this helps with some formats, * notably XML. Note, however, that while we can get String, we can't * assume that's what we use due to custom deserializer */ String value; if (p.nextTextValue() == null) { JsonToken t = p.getCurrentToken(); if (t == JsonToken.END_ARRAY) { break; } // Ok: no need to convert Strings, but must recognize nulls value = (t == JsonToken.VALUE_NULL) ? deser.getNullValue(ctxt) : deser.deserialize(p, ctxt); } else { value = deser.deserialize(p, ctxt); } if (ix >= chunk.length) { chunk = buffer.appendCompletedChunk(chunk); ix = 0; } chunk[ix++] = value; } } catch (Exception e) { // note: pass String.class, not String[].class, as we need element type for error info throw JsonMappingException.wrapWithPath(e, String.class, ix); } String[] result = buffer.completeAndClearBuffer(chunk, ix, String.class); ctxt.returnObjectBuffer(buffer); return result; }
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 '}'"); } } }
// [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(); }
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; }
@Override public String[] deserialize(JsonParser p, DeserializationContext ctxt, String[] intoValue) throws IOException { // Ok: must point to START_ARRAY (or equivalent) if (!p.isExpectedStartArrayToken()) { String[] arr = handleNonArray(p, ctxt); if (arr == null) { return intoValue; } final int offset = intoValue.length; String[] result = new String[offset + arr.length]; System.arraycopy(intoValue, 0, result, 0, offset); System.arraycopy(arr, 0, result, offset, arr.length); return result; } if (_elementDeserializer != null) { return _deserializeCustom(p, ctxt, intoValue); } final ObjectBuffer buffer = ctxt.leaseObjectBuffer(); int ix = intoValue.length; Object[] chunk = buffer.resetAndStart(intoValue, ix); try { while (true) { String value = p.nextTextValue(); if (value == null) { JsonToken t = p.getCurrentToken(); if (t == JsonToken.END_ARRAY) { break; } if (t != JsonToken.VALUE_NULL) { value = _parseString(p, ctxt); } } if (ix >= chunk.length) { chunk = buffer.appendCompletedChunk(chunk); ix = 0; } chunk[ix++] = value; } } catch (Exception e) { throw JsonMappingException.wrapWithPath(e, chunk, buffer.bufferedSize() + ix); } String[] result = buffer.completeAndClearBuffer(chunk, ix, String.class); ctxt.returnObjectBuffer(buffer); return result; }
protected DateTime parseLocal(JsonParser jp) throws IOException, JsonProcessingException { String str = jp.getText().trim(); if (str.length() == 0) { // [JACKSON-360] return null; } return _localDateTimeFormat.parseDateTime(str); }
@Test public void testCreateJsonObjectReturnsJsonObject() throws JSONException { JSONObject jsonObject = mJsonParser.createJsonObject(bufferedReader); String horoscope = jsonObject.getString("prediction"); assertEquals("Test1", horoscope); }
@Override protected Void doInBackground(Void... params) { try { updateurl = new URL( "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=2de143494c0b295cca9337e1e96b00e0"); connection = (HttpURLConnection) updateurl.openConnection(); InputStream ins = connection.getInputStream(); InputStreamReader insr = new InputStreamReader(ins); BufferedReader reader = new BufferedReader(insr); StringBuffer buffer = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { buffer.append(line + "/r" + "/n"); } String response = buffer.toString(); Log.d("[DEBUG]", response); responsebundle = JsonParser.processjson(response); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
/** Actual implementation of value reading+binding operation. */ protected Object _bind(JsonParser jp) throws IOException, JsonParseException, JsonMappingException { /* First: may need to read the next token, to initialize state (either * before first read from parser, or after previous token has been cleared) */ Object result; JsonToken t = _initForReading(jp); if (t == JsonToken.VALUE_NULL) { if (_valueToUpdate == null) { result = _findRootDeserializer(_config, _valueType).getNullValue(); } else { result = _valueToUpdate; } } else if (t == JsonToken.END_ARRAY || t == JsonToken.END_OBJECT) { result = _valueToUpdate; } else { // pointing to event other than null DeserializationContext ctxt = _createDeserializationContext(jp, _config); JsonDeserializer<Object> deser = _findRootDeserializer(_config, _valueType); if (_unwrapRoot) { result = _unwrapAndDeserialize(jp, ctxt, _valueType, deser); } else { if (_valueToUpdate == null) { result = deser.deserialize(jp, ctxt); } else { deser.deserialize(jp, ctxt, _valueToUpdate); result = _valueToUpdate; } } } // Need to consume the token too jp.clearCurrentToken(); return result; }
protected String _valueDesc() { try { return _desc(_parser.getText()); } catch (Exception e) { return "[N/A]"; } }