Java Examples for android.util.JsonReader
The following java examples will help you to understand the usage of android.util.JsonReader. These source code samples are taken from different open source projects.
Example 1
| Project: android-libcore64-master File: ParseBenchmark.java View source code |
private void readToken(android.util.JsonReader reader) throws IOException {
switch(reader.peek()) {
case BEGIN_ARRAY:
readArray(reader);
break;
case BEGIN_OBJECT:
readObject(reader);
break;
case BOOLEAN:
reader.nextBoolean();
break;
case NULL:
reader.nextNull();
break;
case NUMBER:
reader.nextLong();
break;
case STRING:
reader.nextString();
break;
default:
throw new IllegalArgumentException("Unexpected token" + reader.peek());
}
}Example 2
| Project: android-sdk-sources-for-api-level-23-master File: JsonReader.java View source code |
/**
* Returns the type of the next token without consuming it.
*/
public JsonToken peek() throws IOException {
if (token != null) {
return token;
}
switch(peekStack()) {
case EMPTY_DOCUMENT:
replaceTop(JsonScope.NONEMPTY_DOCUMENT);
JsonToken firstToken = nextValue();
if (!lenient && token != JsonToken.BEGIN_ARRAY && token != JsonToken.BEGIN_OBJECT) {
throw new IOException("Expected JSON document to start with '[' or '{' but was " + token);
}
return firstToken;
case EMPTY_ARRAY:
return nextInArray(true);
case NONEMPTY_ARRAY:
return nextInArray(false);
case EMPTY_OBJECT:
return nextInObject(true);
case DANGLING_NAME:
return objectValue();
case NONEMPTY_OBJECT:
return nextInObject(false);
case NONEMPTY_DOCUMENT:
try {
JsonToken token = nextValue();
if (lenient) {
return token;
}
throw syntaxError("Expected EOF");
} catch (EOFException e) {
return token = JsonToken.END_DOCUMENT;
}
case CLOSED:
throw new IllegalStateException("JsonReader is closed");
default:
throw new AssertionError();
}
}Example 3
| Project: ARTPart-master File: ParseBenchmark.java View source code |
private void readToken(android.util.JsonReader reader) throws IOException {
switch(reader.peek()) {
case BEGIN_ARRAY:
readArray(reader);
break;
case BEGIN_OBJECT:
readObject(reader);
break;
case BOOLEAN:
reader.nextBoolean();
break;
case NULL:
reader.nextNull();
break;
case NUMBER:
reader.nextLong();
break;
case STRING:
reader.nextString();
break;
default:
throw new IllegalArgumentException("Unexpected token" + reader.peek());
}
}Example 4
| Project: FBReaction-master File: KFImageDeserializer.java View source code |
static KFImage readObject(JsonReader reader) throws IOException {
reader.beginObject();
KFImage.Builder builder = new KFImage.Builder();
while (reader.hasNext()) {
String name = reader.nextName();
switch(name) {
case KFImage.FRAME_RATE_JSON_FIELD:
builder.frameRate = reader.nextInt();
break;
case KFImage.FRAME_COUNT_JSON_FIELD:
builder.frameCount = reader.nextInt();
break;
case KFImage.FEATURES_JSON_FIELD:
builder.features = KFFeatureDeserializer.LIST_DESERIALIZER.readList(reader);
break;
case KFImage.ANIMATION_GROUPS_JSON_FIELD:
builder.animationGroups = KFAnimationGroupDeserializer.LIST_DESERIALIZER.readList(reader);
break;
case KFImage.CANVAS_SIZE_JSON_FIELD:
builder.canvasSize = CommonDeserializerHelper.readFloatArray(reader);
break;
case KFImage.KEY_JSON_FIELD:
builder.key = reader.nextInt();
break;
case KFImage.BITMAPS_JSON_FIELD:
builder.bitmaps = readBitmaps(reader);
break;
default:
reader.skipValue();
}
}
reader.endObject();
return builder.build();
}Example 5
| Project: android-vlc-remote-master File: JsonContentHandler.java View source code |
protected final Object parse(URLConnection connection) throws IOException {
InputStream input;
try {
input = connection.getInputStream();
} catch (FileNotFoundException ex) {
throw new FileNotFoundException(FILE_NOT_FOUND);
}
JsonReader reader = new JsonReader(new InputStreamReader(input, "UTF-8"));
try {
return parse(reader);
} finally {
reader.close();
}
}Example 6
| Project: DrupalCloud-master File: RESTServerClient.java View source code |
public JsonReader taxonomyVocabGetTree(int vid, int parent, int maxdepth) throws ServiceNotAvailableException, ClientProtocolException, IOException { String uri = mENDPOIN + "taxonomy_vocabulary/getTree"; int size = 2; BasicNameValuePair[] parameters = null; if (maxdepth != 0) { size = 3; parameters = new BasicNameValuePair[size]; parameters[2] = new BasicNameValuePair("maxdepth", String.valueOf(maxdepth)); } else { parameters = new BasicNameValuePair[size]; } parameters[0] = new BasicNameValuePair("vid", String.valueOf(vid)); parameters[1] = new BasicNameValuePair("parent", String.valueOf(parent)); JsonReader jsr = new JsonReader(callPost(uri, parameters)); return jsr; }
Example 7
| Project: SmallCloudEmoji-master File: RepositoryJsonLoader.java View source code |
@Override
protected void loadRepository(Reader reader) throws PullParserException, IOException, LoadingCancelException {
parser = new JsonReader(reader);
parser.beginObject();
while (parser.hasNext()) {
String name = parser.nextName();
if (!name.equals("categories")) {
parser.skipValue();
continue;
}
parser.beginArray();
while (parser.hasNext()) {
loadCategory();
}
parser.endArray();
}
parser.endObject();
}Example 8
| Project: android_frameworks_base-master File: JsonReader.java View source code |
/**
* Returns the type of the next token without consuming it.
*/
public JsonToken peek() throws IOException {
if (token != null) {
return token;
}
switch(peekStack()) {
case EMPTY_DOCUMENT:
replaceTop(JsonScope.NONEMPTY_DOCUMENT);
JsonToken firstToken = nextValue();
if (!lenient && token != JsonToken.BEGIN_ARRAY && token != JsonToken.BEGIN_OBJECT) {
throw new IOException("Expected JSON document to start with '[' or '{' but was " + token);
}
return firstToken;
case EMPTY_ARRAY:
return nextInArray(true);
case NONEMPTY_ARRAY:
return nextInArray(false);
case EMPTY_OBJECT:
return nextInObject(true);
case DANGLING_NAME:
return objectValue();
case NONEMPTY_OBJECT:
return nextInObject(false);
case NONEMPTY_DOCUMENT:
try {
JsonToken token = nextValue();
if (lenient) {
return token;
}
throw syntaxError("Expected EOF");
} catch (EOFException e) {
return token = JsonToken.END_DOCUMENT;
}
case CLOSED:
throw new IllegalStateException("JsonReader is closed");
default:
throw new AssertionError();
}
}Example 9
| Project: CatSaver-master File: UpdateChecker.java View source code |
@Override
protected ReleaseInfo doInBackground(final Void... params) {
HttpURLConnection connection = null;
ReleaseInfo info = mCachedReleaseInfo.orNull();
try {
connection = (HttpURLConnection) API_URL.openConnection();
connection.setRequestProperty("Accept", "application/vnd.github.v3+json");
if (info != null) {
final String prevETag = info.eTag;
connection.setRequestProperty("If-None-Match", prevETag);
}
connection.connect();
final int code = connection.getResponseCode();
if (code == 304) {
return info;
}
info = new ReleaseInfo();
info.eTag = connection.getHeaderField("ETag");
final InputStream stream = connection.getInputStream();
final JsonReader reader = new JsonReader(new InputStreamReader(stream));
reader.setLenient(true);
info.initialize(reader);
return info;
} catch (final IOExceptionParseException | e) {
CsLog.e("Cannot fetch upgrade", e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
return info;
}Example 10
| Project: hwbotprime-master File: SubmitResultTask.java View source code |
@Override
public SubmitResponse doInBackground(Void... params) {
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 20;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection * 1000);
HttpConnectionParams.setSoTimeout(httpParameters, timeoutConnection * 1000);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
try {
// Create a response handler
HttpPost req = new HttpPost(BenchService.SERVER + "/submit/api?client=hwbot_prime&clientVersion=" + PrimeBenchService.getInstance().version + "&mode=remote");
MultipartEntity mpEntity = new MultipartEntity();
mpEntity.addPart("data", new ByteArrayBody(data, "data"));
req.setEntity(mpEntity);
BasicResponseStatusHandler responseHandler = new BasicResponseStatusHandler();
String response = httpclient.execute(req, responseHandler);
Reader in = new StringReader(response);
JsonReader reader = null;
try {
reader = new JsonReader(in);
Log.i(this.getClass().getSimpleName(), "Reading response: " + response);
return readSubmitResponse(reader);
} catch (Exception e) {
Log.e(this.getClass().getSimpleName(), "Error: " + e.getMessage());
e.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
}
} catch (UnknownHostException e) {
Log.w(this.getClass().getSimpleName(), "No network access: " + e.getMessage());
networkStatusAware.showNetworkPopupOnce();
} catch (HttpHostConnectException e) {
Log.i(this.getClass().getName(), "Failed to connect to HWBOT server! Are you connected to the internet?");
e.printStackTrace();
} catch (Exception e) {
Log.i(this.getClass().getName(), "Error communicating with online service. If this issue persists, please contact HWBOT crew. Error: " + e.getMessage());
e.printStackTrace();
} finally {
httpclient.getConnectionManager().shutdown();
}
return null;
}Example 11
| Project: OMzen-master File: JSON.java View source code |
public void inisiasi() {
FileReader r = null;
try {
r = new FileReader(S.DEFAULT_ICON_DIR + "/notif_apps_icon.json");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (r == null)
return;
try {
List<DATA> ld = new ArrayList<DATA>();
String namapaket = "";
List<String> default_icon, nama_icon;
default_icon = new ArrayList<String>();
nama_icon = new ArrayList<String>();
JsonReader reader = new JsonReader(r);
reader.beginArray();
while (reader.hasNext()) {
DATA dd = new DATA();
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("package")) {
namapaket = reader.nextString();
dd.setNAMA_PAKET(namapaket);
} else if (name.equals("icon")) {
reader.beginObject();
while (reader.hasNext()) {
String n = reader.nextName();
if (n.equals("nama")) {
default_icon.add(reader.nextString());
} else if (n.equals("ic")) {
nama_icon.add(reader.nextString());
} else {
reader.skipValue();
}
}
dd.setOLD_IC(default_icon);
dd.setNEW_IC(nama_icon);
reader.endObject();
} else {
reader.skipValue();
}
}
reader.endObject();
ld.add(dd);
}
reader.endArray();
reader.close();
for (int i = 0; i < ld.size(); i++) {
DATA d = ld.get(i);
Log.e("namapaket :", d.getNAMA_PAKET());
}
} catch (IOException e) {
e.printStackTrace();
}
}Example 12
| Project: platform_frameworks_base-master File: JsonReader.java View source code |
/**
* Returns the type of the next token without consuming it.
*/
public JsonToken peek() throws IOException {
if (token != null) {
return token;
}
switch(peekStack()) {
case EMPTY_DOCUMENT:
replaceTop(JsonScope.NONEMPTY_DOCUMENT);
JsonToken firstToken = nextValue();
if (!lenient && token != JsonToken.BEGIN_ARRAY && token != JsonToken.BEGIN_OBJECT) {
throw new IOException("Expected JSON document to start with '[' or '{' but was " + token);
}
return firstToken;
case EMPTY_ARRAY:
return nextInArray(true);
case NONEMPTY_ARRAY:
return nextInArray(false);
case EMPTY_OBJECT:
return nextInObject(true);
case DANGLING_NAME:
return objectValue();
case NONEMPTY_OBJECT:
return nextInObject(false);
case NONEMPTY_DOCUMENT:
try {
JsonToken token = nextValue();
if (lenient) {
return token;
}
throw syntaxError("Expected EOF");
} catch (EOFException e) {
return token = JsonToken.END_DOCUMENT;
}
case CLOSED:
throw new IllegalStateException("JsonReader is closed");
default:
throw new AssertionError();
}
}Example 13
| Project: rover-android-master File: JsonResponseHandler.java View source code |
public void onHandleResponse(HttpResponse response) throws IOException {
if (response.getBody() == null) {
return;
}
JsonReader jsonReader = new JsonReader(response.getBody());
JsonToken token = jsonReader.peek();
switch(token) {
case BEGIN_OBJECT:
JSONObject jsonObject = readJSONObject(jsonReader);
if (mComletionHandler != null) {
mComletionHandler.onReceivedJSONObject(jsonObject);
}
break;
case BEGIN_ARRAY:
JSONArray jsonArray = readJSONArray(jsonReader);
if (mComletionHandler != null) {
mComletionHandler.onReceivedJSONArray(jsonArray);
}
break;
default:
break;
}
}Example 14
| Project: android_packages_inputmethods_LatinIME-master File: MetadataParser.java View source code |
/**
* Parse one JSON-formatted word list metadata.
* @param reader the reader containing the data.
* @return a WordListMetadata object from the parsed data.
* @throws IOException if the underlying reader throws IOException during reading.
*/
private static WordListMetadata parseOneWordList(final JsonReader reader) throws IOException, BadFormatException {
final TreeMap<String, String> arguments = new TreeMap<>();
reader.beginObject();
while (reader.hasNext()) {
final String name = reader.nextName();
if (!TextUtils.isEmpty(name)) {
arguments.put(name, reader.nextString());
}
}
reader.endObject();
if (TextUtils.isEmpty(arguments.get(ID_FIELD_NAME)) || TextUtils.isEmpty(arguments.get(LOCALE_FIELD_NAME)) || TextUtils.isEmpty(arguments.get(DESCRIPTION_FIELD_NAME)) || TextUtils.isEmpty(arguments.get(UPDATE_FIELD_NAME)) || TextUtils.isEmpty(arguments.get(FILESIZE_FIELD_NAME)) || TextUtils.isEmpty(arguments.get(CHECKSUM_FIELD_NAME)) || TextUtils.isEmpty(arguments.get(REMOTE_FILENAME_FIELD_NAME)) || TextUtils.isEmpty(arguments.get(VERSION_FIELD_NAME)) || TextUtils.isEmpty(arguments.get(FORMATVERSION_FIELD_NAME))) {
throw new BadFormatException(arguments.toString());
}
// be decided later.
return new WordListMetadata(arguments.get(ID_FIELD_NAME), MetadataDbHelper.TYPE_BULK, arguments.get(DESCRIPTION_FIELD_NAME), Long.parseLong(arguments.get(UPDATE_FIELD_NAME)), Long.parseLong(arguments.get(FILESIZE_FIELD_NAME)), arguments.get(RAW_CHECKSUM_FIELD_NAME), arguments.get(CHECKSUM_FIELD_NAME), MetadataDbHelper.DICTIONARY_RETRY_THRESHOLD, /* retryCount */
null, arguments.get(REMOTE_FILENAME_FIELD_NAME), Integer.parseInt(arguments.get(VERSION_FIELD_NAME)), Integer.parseInt(arguments.get(FORMATVERSION_FIELD_NAME)), 0, arguments.get(LOCALE_FIELD_NAME));
}Example 15
| Project: cw-omnibus-master File: EditHistory.java View source code |
public List<Uri> getOpenEditors() {
String editors = prefsRef.get().getString(PREF_OPEN_EDITORS, null);
ArrayList<Uri> result = new ArrayList<Uri>();
if (editors != null) {
StringReader sr = new StringReader(editors);
JsonReader json = new JsonReader(sr);
try {
json.beginArray();
while (json.hasNext()) {
result.add(Uri.parse(json.nextString()));
}
json.endArray();
json.close();
} catch (IOException e) {
Log.e(getClass().getSimpleName(), "Exception reading JSON", e);
}
}
return (result);
}Example 16
| Project: EasyDice-master File: DieHandTests.java View source code |
private void serializeAndEquals(DieHand h1) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Writer out = new PrintWriter(baos);
h1.serialize(new JsonWriter(out));
out.flush();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
InputStreamReader rd = new InputStreamReader(bais);
DieHand h2 = new DieHand(new JsonReader(rd));
assertEquals(h1, h2);
}Example 17
| Project: Indic-Keyboard-master File: MetadataParser.java View source code |
/**
* Parse one JSON-formatted word list metadata.
* @param reader the reader containing the data.
* @return a WordListMetadata object from the parsed data.
* @throws IOException if the underlying reader throws IOException during reading.
*/
private static WordListMetadata parseOneWordList(final JsonReader reader) throws IOException, BadFormatException {
final TreeMap<String, String> arguments = new TreeMap<>();
reader.beginObject();
while (reader.hasNext()) {
final String name = reader.nextName();
if (!TextUtils.isEmpty(name)) {
arguments.put(name, reader.nextString());
}
}
reader.endObject();
if (TextUtils.isEmpty(arguments.get(ID_FIELD_NAME)) || TextUtils.isEmpty(arguments.get(LOCALE_FIELD_NAME)) || TextUtils.isEmpty(arguments.get(DESCRIPTION_FIELD_NAME)) || TextUtils.isEmpty(arguments.get(UPDATE_FIELD_NAME)) || TextUtils.isEmpty(arguments.get(FILESIZE_FIELD_NAME)) || TextUtils.isEmpty(arguments.get(CHECKSUM_FIELD_NAME)) || TextUtils.isEmpty(arguments.get(REMOTE_FILENAME_FIELD_NAME)) || TextUtils.isEmpty(arguments.get(VERSION_FIELD_NAME)) || TextUtils.isEmpty(arguments.get(FORMATVERSION_FIELD_NAME))) {
throw new BadFormatException(arguments.toString());
}
// be decided later.
return new WordListMetadata(arguments.get(ID_FIELD_NAME), MetadataDbHelper.TYPE_BULK, arguments.get(DESCRIPTION_FIELD_NAME), Long.parseLong(arguments.get(UPDATE_FIELD_NAME)), Long.parseLong(arguments.get(FILESIZE_FIELD_NAME)), arguments.get(RAW_CHECKSUM_FIELD_NAME), arguments.get(CHECKSUM_FIELD_NAME), null, arguments.get(REMOTE_FILENAME_FIELD_NAME), Integer.parseInt(arguments.get(VERSION_FIELD_NAME)), Integer.parseInt(arguments.get(FORMATVERSION_FIELD_NAME)), 0, arguments.get(LOCALE_FIELD_NAME));
}Example 18
| Project: meetup-client-master File: SkyjamPlaybackService.java View source code |
public final void onOperationComplete(HttpOperation httpoperation) {
int i;
String s;
String s1;
if (httpoperation.hasError() || mMediaPlayer == null) {
return;
}
i = 0;
s = null;
s1 = null;
String s2 = httpoperation.getOutputStream().toString();
if (EsLog.isLoggable("SkyjamPlaybackService", 3))
Log.d("SkyjamPlaybackService", (new StringBuilder("Received server response: ")).append(s2).toString());
try {
JsonReader jsonreader = new JsonReader(new StringReader(s2));
jsonreader.beginObject();
while (jsonreader.hasNext()) {
String s3 = jsonreader.nextName();
if (s3.equals("durationMillis"))
i = jsonreader.nextInt();
else if (s3.equals("playType"))
s = jsonreader.nextString().toLowerCase();
else if (s3.equals("url"))
s1 = jsonreader.nextString();
else
jsonreader.skipValue();
}
jsonreader.endObject();
sTotalPlayableTime = i;
if (s != null && !s.equals("full") && s.endsWith("sp")) {
sTotalPlayableTime = 1000 * Integer.parseInt(s.substring(0, -2 + s.length()));
}
if (EsLog.isLoggable("SkyjamPlaybackService", 3))
Log.d("SkyjamPlaybackService", (new StringBuilder("Total playable time set to ")).append(sTotalPlayableTime).append(" ms").toString());
try {
if (EsLog.isLoggable("SkyjamPlaybackService", 3))
Log.d("SkyjamPlaybackService", "play");
mMediaPlayer.setAudioStreamType(3);
mMediaPlayer.setLooping(false);
mMediaPlayer.setDataSource(s1);
mMediaPlayer.prepareAsync();
sStatus = getString(R.string.skyjam_status_buffering);
dispatchStatusUpdate();
} catch (IOException ioexception1) {
}
stop();
} catch (IOException e) {
}
}Example 19
| Project: nuntius-android-master File: EventType.java View source code |
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
void manageEvent(NotificationListenerService context, JsonReader reader) throws IOException {
String[] values = parse(reader);
String key = values[0];
String actionTitle = values[1];
if (!key.equals("")) {
StatusBarNotification[] activeNotifications = context.getActiveNotifications(new String[] { key });
if (activeNotifications.length > 0) {
StatusBarNotification activeNotification = activeNotifications[0];
for (Notification.Action action : activeNotification.getNotification().actions) {
if (actionTitle.equals(action.title)) {
try {
action.actionIntent.send();
} catch (PendingIntent.CanceledException e) {
}
}
}
}
}
}Example 20
| Project: packages_inputmethods_latinime-master File: MetadataParser.java View source code |
/**
* Parse one JSON-formatted word list metadata.
* @param reader the reader containing the data.
* @return a WordListMetadata object from the parsed data.
* @throws IOException if the underlying reader throws IOException during reading.
*/
private static WordListMetadata parseOneWordList(final JsonReader reader) throws IOException, BadFormatException {
final TreeMap<String, String> arguments = new TreeMap<>();
reader.beginObject();
while (reader.hasNext()) {
final String name = reader.nextName();
if (!TextUtils.isEmpty(name)) {
arguments.put(name, reader.nextString());
}
}
reader.endObject();
if (TextUtils.isEmpty(arguments.get(ID_FIELD_NAME)) || TextUtils.isEmpty(arguments.get(LOCALE_FIELD_NAME)) || TextUtils.isEmpty(arguments.get(DESCRIPTION_FIELD_NAME)) || TextUtils.isEmpty(arguments.get(UPDATE_FIELD_NAME)) || TextUtils.isEmpty(arguments.get(FILESIZE_FIELD_NAME)) || TextUtils.isEmpty(arguments.get(CHECKSUM_FIELD_NAME)) || TextUtils.isEmpty(arguments.get(REMOTE_FILENAME_FIELD_NAME)) || TextUtils.isEmpty(arguments.get(VERSION_FIELD_NAME)) || TextUtils.isEmpty(arguments.get(FORMATVERSION_FIELD_NAME))) {
throw new BadFormatException(arguments.toString());
}
// be decided later.
return new WordListMetadata(arguments.get(ID_FIELD_NAME), MetadataDbHelper.TYPE_BULK, arguments.get(DESCRIPTION_FIELD_NAME), Long.parseLong(arguments.get(UPDATE_FIELD_NAME)), Long.parseLong(arguments.get(FILESIZE_FIELD_NAME)), arguments.get(RAW_CHECKSUM_FIELD_NAME), arguments.get(CHECKSUM_FIELD_NAME), MetadataDbHelper.DICTIONARY_RETRY_THRESHOLD, /* retryCount */
null, arguments.get(REMOTE_FILENAME_FIELD_NAME), Integer.parseInt(arguments.get(VERSION_FIELD_NAME)), Integer.parseInt(arguments.get(FORMATVERSION_FIELD_NAME)), 0, arguments.get(LOCALE_FIELD_NAME));
}Example 21
| Project: POSA-15-master File: AcronymDataJsonParser.java View source code |
/**
* Parse a Json stream and convert it into a List of AcronymData
* objects.
*/
public List<AcronymExpansion> parseAcronymWebServiceResults(JsonReader reader) throws IOException {
reader.beginArray();
// If the acronym wasn't expanded return null;
if (reader.peek() == JsonToken.END_ARRAY)
return null;
// Create a AcronymData object for each element in the
// Json array.
final List<AcronymExpansion> acronymExpansion = parseAcronymData(reader);
reader.endArray();
return acronymExpansion;
}Example 22
| Project: SchulinfoAPP-master File: Subst.java View source code |
public void load(String file) throws Exception {
clear();
special.clear();
InputStream in = SIAApp.SIA_APP.openFileInput(file);
JsonReader reader = new JsonReader(new InputStreamReader(in));
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
switch(name) {
case "date":
date = new Date(reader.nextLong());
break;
case "messages":
reader.beginArray();
while (reader.hasNext()) {
special.add(reader.nextString());
}
reader.endArray();
break;
case "entries":
reader.beginArray();
while (reader.hasNext()) {
reader.beginObject();
Entry e = new Entry();
e.date = date;
while (reader.hasNext()) {
String name2 = reader.nextName();
switch(name2) {
case "class":
e.clazz = reader.nextString();
break;
case "lesson":
e.lesson = reader.nextString();
break;
case "teacher":
e.teacher = reader.nextString();
break;
case "subject":
e.subject = reader.nextString();
break;
case "comment":
e.comment = reader.nextString();
break;
case "type":
e.type = reader.nextString();
break;
case "room":
e.room = reader.nextString();
break;
case "repsub":
e.repsub = reader.nextString();
break;
default:
reader.skipValue();
break;
}
}
add(e);
reader.endObject();
}
reader.endArray();
break;
default:
reader.skipValue();
break;
}
}
reader.endObject();
reader.close();
}Example 23
| Project: status-master File: HelpFragment.java View source code |
@Nullable
@Override
protected String run() throws InterruptedException {
try {
URL url = new URL(FAQ_URL);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();
JsonReader reader = new JsonReader(new InputStreamReader((InputStream) request.getContent(), "UTF-8"));
reader.beginArray();
while (reader.hasNext()) {
reader.beginObject();
String name = "", content = "";
try {
name = reader.nextName().matches("name") ? reader.nextString() : "";
content = reader.nextName().matches("content") ? reader.nextString() : "";
} catch (IllegalStateException e) {
e.printStackTrace();
}
faqs.add(new FaqData(name, content));
reader.endObject();
}
reader.endArray();
reader.close();
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
return null;
}Example 24
| Project: AiyaEffectsAndroid-master File: EffectSelectActivity.java View source code |
//�始化特效按钮��
protected void initEffectMenu(String menuPath) {
try {
Log.e("解���->" + menuPath);
JsonReader r = new JsonReader(new InputStreamReader(getAssets().open(menuPath)));
r.beginArray();
while (r.hasNext()) {
MenuBean menu = new MenuBean();
r.beginObject();
String name;
while (r.hasNext()) {
name = r.nextName();
if (name.equals("name")) {
menu.name = r.nextString();
} else if (name.equals("path")) {
menu.path = r.nextString();
}
}
mStickerData.add(menu);
Log.e("å¢žåŠ è?œå?•->" + menu.name);
r.endObject();
}
r.endArray();
mStickerAdapter.notifyDataSetChanged();
} catch (IOException e) {
e.printStackTrace();
mStickerAdapter.notifyDataSetChanged();
}
}Example 25
| Project: android-galaxyzoo-master File: LoginUtils.java View source code |
public static LoginResult parseLoginResponseContent(final InputStream content) throws IOException {
//A failure by default.
LoginResult result = new LoginResult(false, null, null);
final InputStreamReader streamReader = new InputStreamReader(content, Utils.STRING_ENCODING);
final JsonReader reader = new JsonReader(streamReader);
reader.beginObject();
boolean success = false;
String apiKey = null;
String userName = null;
String message = null;
while (reader.hasNext()) {
final String name = reader.nextName();
switch(name) {
case "success":
success = reader.nextBoolean();
break;
case "api_key":
apiKey = reader.nextString();
break;
case "name":
userName = reader.nextString();
break;
case "message":
message = reader.nextString();
break;
default:
reader.skipValue();
}
}
if (success) {
result = new LoginResult(true, userName, apiKey);
} else {
Log.info("Login failed.");
Log.info("Login failure message: " + message);
}
reader.endObject();
reader.close();
streamReader.close();
return result;
}Example 26
| Project: BernieAppAndroid-master File: ConnectTask.java View source code |
@Override
protected Object doInBackground(Object[] params) {
events = new ArrayList<>();
BufferedReader in = null;
try {
URL url = frag.fetchCountry ? new URL("https://go.berniesanders.com/page/event/search_results?orderby=date&format=json") : new URL("https://go.berniesanders.com/page/event/search_results?orderby=date&format=json&zip_radius=" + frag.mRadius + "&zip=" + frag.mZip);
Log.d("URL", url.toString());
in = new BufferedReader(new InputStreamReader(url.openStream()));
} catch (IOException e) {
e.printStackTrace();
}
if (in == null) {
Log.d("reader null", "no events, null reader,");
Event e = new Event();
e.setName("Unable to Load News");
e.setDescription("Check your internet connection?");
events.add(e);
return null;
}
JsonReader reader = new JsonReader(in);
try {
readObjects(reader);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}Example 27
| Project: DAT255-Grupp12-master File: FileHandler.java View source code |
/**
* Creates a list of todolists or log from a json object/string ie. reads the file
* @param activity the activity in which the filewriting takes place
* @return the list of todolists extracted from the file
* @throws IOException if reading somehow fails
*/
public List readListFromJson(Activity activity, String fileName) throws IOException {
ArrayList<TodoList> list = new ArrayList<TodoList>();
FileInputStream fis;
try {
if (fileName.equals(LISTFILE)) {
fis = activity.openFileInput(LISTFILE);
} else {
fis = activity.openFileInput(LOGFILE);
}
} catch (FileNotFoundException e) {
return list;
}
byte content[] = new byte[fis.available()];
fis.read(content);
String json = new String(content);
com.google.gson.stream.JsonReader reader = new com.google.gson.stream.JsonReader(new StringReader(json));
reader.setLenient(true);
if (fileName.equals(LISTFILE)) {
list = gson.fromJson(reader, new TypeToken<ArrayList<TodoList>>() {
}.getType());
return list;
} else {
LinkedList log = gson.fromJson(reader, new TypeToken<LinkedList<Modification>>() {
}.getType());
return log;
}
}Example 28
| Project: deck_old-master File: GameSaveIO.java View source code |
public static boolean openGameSave(File gameSave, HashMap<String, CardHolder> players, HashMap<String, CardHolder> leftPlayers) {
boolean success = true;
InputStreamReader inputStreamReader = null;
try {
inputStreamReader = new FileReader(gameSave);
JsonReader reader = new JsonReader(inputStreamReader);
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals(PLAYERS_NAME)) {
reader.beginArray();
while (reader.hasNext()) {
CardHolder player = CardHolder.readFromJson(reader);
players.put(player.getID(), player);
}
reader.endArray();
} else if (name.equals(LEFT_PLAYERS_NAME)) {
reader.beginArray();
while (reader.hasNext()) {
CardHolder player = CardHolder.readFromJson(reader);
leftPlayers.put(player.getID(), player);
}
reader.endArray();
} else {
reader.skipValue();
}
}
reader.endObject();
} catch (IOException io) {
Debug.e("Failed to save game.", io);
success = false;
} catch (IllegalStateException se) {
Debug.e("Failed to save game.", se);
success = false;
} finally {
try {
if (inputStreamReader != null) {
inputStreamReader.close();
}
} catch (IOException io) {
io.printStackTrace();
}
}
return success;
}Example 29
| Project: react-native-sidemenu-master File: JSDebuggerWebSocketClient.java View source code |
@Override
public void onMessage(ResponseBody response) throws IOException {
if (response.contentType() != WebSocket.TEXT) {
FLog.w(TAG, "Websocket received unexpected message with payload of type " + response.contentType());
return;
}
Integer replyID = null;
try {
JsonReader reader = new JsonReader(response.charStream());
String result = null;
reader.beginObject();
while (reader.hasNext()) {
String field = reader.nextName();
if (JsonToken.NULL == reader.peek()) {
reader.skipValue();
continue;
}
if ("replyID".equals(field)) {
replyID = reader.nextInt();
} else if ("result".equals(field)) {
result = reader.nextString();
} else if ("error".equals(field)) {
String error = reader.nextString();
abort(error, new JavascriptException(error));
}
}
if (replyID != null) {
triggerRequestSuccess(replyID, result);
}
} catch (IOException e) {
if (replyID != null) {
triggerRequestFailure(replyID, e);
} else {
abort("Parsing response message from websocket failed", e);
}
} finally {
response.close();
}
}Example 30
| Project: ReactNativeApp-master File: JSDebuggerWebSocketClient.java View source code |
@Override
public void onMessage(ResponseBody response) throws IOException {
if (response.contentType() != WebSocket.TEXT) {
FLog.w(TAG, "Websocket received unexpected message with payload of type " + response.contentType());
return;
}
Integer replyID = null;
try {
JsonReader reader = new JsonReader(response.charStream());
String result = null;
reader.beginObject();
while (reader.hasNext()) {
String field = reader.nextName();
if (JsonToken.NULL == reader.peek()) {
reader.skipValue();
continue;
}
if ("replyID".equals(field)) {
replyID = reader.nextInt();
} else if ("result".equals(field)) {
result = reader.nextString();
} else if ("error".equals(field)) {
String error = reader.nextString();
abort(error, new JavascriptException(error));
}
}
if (replyID != null) {
triggerRequestSuccess(replyID, result);
}
} catch (IOException e) {
if (replyID != null) {
triggerRequestFailure(replyID, e);
} else {
abort("Parsing response message from websocket failed", e);
}
} finally {
response.close();
}
}Example 31
| Project: xray-master File: XrayCheckTask.java View source code |
@Override
protected XrayUpdater.CheckResult doInBackground(Void... v) {
HttpsURLConnection urlConnection = null;
InputStream inputStream = null;
XrayUpdater.CheckResult result = XrayUpdater.CheckResult.UP_TO_DATE;
Log.d(TAG, "Attempting to fetch manifest...");
try {
// issue a GET request to determine the latest available apk version
URL url = new URL(XrayUpdater.VERSION_URL);
urlConnection = PinningHelper.getPinnedHttpsURLConnection(context, XrayUpdater.CERT_PINS, url);
urlConnection.setConnectTimeout(XrayUpdater.CONNECTION_TIMEOUT);
urlConnection.setReadTimeout(XrayUpdater.READ_TIMEOUT);
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.connect();
int responseCode = urlConnection.getResponseCode();
int apkVersion = -1;
String apkName = null;
String apkChecksum = null;
// read the results into a byte array stream
inputStream = new BufferedInputStream(urlConnection.getInputStream());
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
if (responseCode != HttpURLConnection.HTTP_OK) {
Log.d(TAG, "Error fetching app version, HTTP request returned: " + responseCode);
} else if (!XrayUpdater.writeToOutputStream(inputStream, byteStream)) {
Log.d(TAG, "Error fetching app version, invalid input stream");
} else {
// request looks okay, let's verify response signature
Signature ecdsaSignature = Signature.getInstance(XrayUpdater.ECDSA_ALGORITHM, XrayUpdater.ECDSA_PROVIDER);
PublicKey extPubKey = crypto.readPublicKey(XrayUpdater.SERVER_PUB_KEY);
ecdsaSignature.initVerify(extPubKey);
ecdsaSignature.update(byteStream.toByteArray());
String signature = urlConnection.getHeaderField("Xray-Signature");
byte[] signature_bytes = crypto.base64Decode(signature);
if (!ecdsaSignature.verify(signature_bytes)) {
Log.d(TAG, "Invalid signature");
} else {
Log.d(TAG, "Signature valid. Reading JSON response...");
// signature is valid, so read version and filename from JSON response
inputStream = new ByteArrayInputStream(byteStream.toByteArray());
JsonReader reader = new JsonReader(new InputStreamReader(inputStream));
reader.beginObject();
while (reader.hasNext()) {
String key = reader.nextName();
if (key.equals("apkVersion")) {
apkVersion = Integer.parseInt(reader.nextString());
} else if (key.equals("apkName")) {
apkName = reader.nextString();
} else if (key.equals("apkChecksum")) {
apkChecksum = reader.nextString();
} else {
reader.skipValue();
}
}
reader.endObject();
}
}
if (apkVersion < 0 || apkName == null || apkChecksum == null) {
Log.d(TAG, "Error fetching app version, JSON response missing fields");
} else if (apkVersion == BuildConfig.VERSION_CODE) {
Log.d(TAG, "Already up to date");
} else {
// out of date
XrayUpdater.setSharedPreference("apkName", apkName);
XrayUpdater.setSharedPreference("apkChecksum", apkChecksum);
result = XrayUpdater.CheckResult.OUT_OF_DATE;
}
} catch (MalformedURLException e) {
Log.d(TAG, "Found malformed URL when trying to update");
} catch (SocketTimeoutException e) {
Log.d(TAG, "Socket timed out when trying to update: " + e.toString());
} catch (SSLHandshakeException e) {
Log.d(TAG, "Failed SSL Handshake when trying to update: " + e.toString());
result = XrayUpdater.CheckResult.SSL_ERROR;
} catch (IOException e) {
Log.d(TAG, "Found IO exception when trying to update: " + e.toString());
} catch (Exception e) {
Log.d(TAG, "Received error when trying to update: " + e.toString());
} finally {
Log.d(TAG, "Cleaning up check task...");
// close the GET connection
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
Log.d(TAG, "Found IO exception when trying to close inputstream: " + e.toString());
}
}
if (urlConnection != null) {
urlConnection.disconnect();
}
Log.d(TAG, "Exiting check task");
}
return result;
}Example 32
| Project: Android-SoundCloud-Player-master File: SoundCloudJsonParsingUtils.java View source code |
private static TrackObject parsingNewTrackObject(JsonReader reader) {
if (reader != null) {
try {
TrackObject mTrackObject = null;
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("id")) {
mTrackObject = new TrackObject();
mTrackObject.setId(reader.nextLong());
} else if (name.equals("created_at")) {
if (mTrackObject != null) {
String createdAt = reader.nextString();
Date mDate = DateTimeUtils.getDateFromString(createdAt, DATE_PATTERN_ORI);
mTrackObject.setCreatedDate(mDate);
}
} else if (name.equals("user_id")) {
if (mTrackObject != null) {
mTrackObject.setUserId(reader.nextLong());
}
} else if (name.equals("duration")) {
if (mTrackObject != null) {
mTrackObject.setDuration(reader.nextLong());
}
} else if (name.equals("sharing")) {
if (mTrackObject != null) {
mTrackObject.setSharing(reader.nextString());
}
} else if (name.equals("tag_list") && reader.peek() != JsonToken.NULL) {
if (mTrackObject != null) {
mTrackObject.setTagList(reader.nextString());
}
} else if (name.equals("streamable") && reader.peek() != JsonToken.NULL) {
if (mTrackObject != null) {
mTrackObject.setStreamable(reader.nextBoolean());
}
} else if (name.equals("downloadable") && reader.peek() != JsonToken.NULL) {
if (mTrackObject != null) {
mTrackObject.setDownloadable(reader.nextBoolean());
}
} else if (name.equals("genre") && reader.peek() != JsonToken.NULL) {
if (mTrackObject != null) {
mTrackObject.setGenre(reader.nextString());
}
} else if (name.equals("title") && reader.peek() != JsonToken.NULL) {
if (mTrackObject != null) {
mTrackObject.setTitle(reader.nextString());
}
} else if (name.equals("description") && reader.peek() != JsonToken.NULL) {
if (mTrackObject != null) {
mTrackObject.setDescription(reader.nextString());
}
} else if (name.equals("user")) {
reader.beginObject();
while (reader.hasNext()) {
String nameTagUser = reader.nextName();
if (nameTagUser.equals("username")) {
if (mTrackObject != null) {
mTrackObject.setUsername(reader.nextString());
}
} else if (nameTagUser.equals("avatar_url") && reader.peek() != JsonToken.NULL) {
if (mTrackObject != null) {
mTrackObject.setAvatarUrl(reader.nextString());
}
} else {
reader.skipValue();
}
}
reader.endObject();
} else if (name.equals("permalink_url")) {
if (mTrackObject != null) {
mTrackObject.setPermalinkUrl(reader.nextString());
}
} else if (name.equals("artwork_url") && reader.peek() != JsonToken.NULL) {
if (mTrackObject != null) {
mTrackObject.setArtworkUrl(reader.nextString());
}
} else if (name.equals("waveform_url")) {
if (mTrackObject != null) {
mTrackObject.setWaveForm(reader.nextString());
}
} else if (name.equals("playback_count")) {
if (mTrackObject != null) {
mTrackObject.setPlaybackCount(reader.nextLong());
}
} else if (name.equals("favoritings_count")) {
if (mTrackObject != null) {
mTrackObject.setFavoriteCount(reader.nextLong());
}
} else if (name.equals("comment_count")) {
if (mTrackObject != null) {
mTrackObject.setCommentCount(reader.nextLong());
}
} else {
reader.skipValue();
}
}
return mTrackObject;
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}Example 33
| Project: AnyMemo-master File: EntryFactory.java View source code |
/**
* Parse the JSON format like this:
* "kind": "drive#fileList",
* "etag": "\"dM4Z0GasI3ekQlrgb3F8B4ytx24/bhMYFq5sxQUJKZ2H3LNeBmBcr2E\"",
* "selfLink": "https://www.googleapis.com/drive/v2/files?q=title+%3D+'IMG_5652.jpg'",
* "items": [..ITEM TYPE HERE.]
*/
public static <T extends Entry> List<T> getEntriesFromDriveApi(Class<T> clazz, InputStream inputStream) throws IOException {
List<T> entryList = new ArrayList<T>(50);
JsonReader jsonReader = null;
String name = "";
try {
jsonReader = new JsonReader(new InputStreamReader(inputStream, "UTF-8"));
jsonReader.beginObject();
while (jsonReader.hasNext()) {
if (jsonReader.peek() != JsonToken.NAME) {
jsonReader.skipValue();
continue;
}
name = jsonReader.nextName();
if (name.equals("items") && jsonReader.peek() != JsonToken.NULL) {
jsonReader.beginArray();
while (jsonReader.hasNext()) {
entryList.add(getEntryFromJsonReader(clazz, jsonReader));
}
jsonReader.endArray();
}
}
jsonReader.endObject();
} finally {
if (jsonReader != null) {
jsonReader.close();
}
}
return entryList;
}Example 34
| Project: chromium-webview-samples-master File: MainFragment.java View source code |
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public void onReceiveValue(String s) {
JsonReader reader = new JsonReader(new StringReader(s));
// Must set lenient to parse single values
reader.setLenient(true);
try {
if (reader.peek() != JsonToken.NULL) {
if (reader.peek() == JsonToken.STRING) {
String msg = reader.nextString();
if (msg != null) {
Toast.makeText(getActivity().getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
}
}
} catch (IOException e) {
Log.e("TAG", "MainActivity: IOException", e);
} finally {
try {
reader.close();
} catch (IOException e) {
}
}
}Example 35
| Project: chromium_webview-master File: DOMUtils.java View source code |
/**
* Returns the rect boundaries for a node by its id.
*/
public static Rect getNodeBounds(final ContentView view, TestCallbackHelperContainer viewClient, String nodeId) throws InterruptedException, TimeoutException {
StringBuilder sb = new StringBuilder();
sb.append("(function() {");
sb.append(" var node = document.getElementById('" + nodeId + "');");
sb.append(" if (!node) return null;");
sb.append(" var width = node.offsetWidth;");
sb.append(" var height = node.offsetHeight;");
sb.append(" var x = -window.scrollX;");
sb.append(" var y = -window.scrollY;");
sb.append(" do {");
sb.append(" x += node.offsetLeft;");
sb.append(" y += node.offsetTop;");
sb.append(" } while (node = node.offsetParent);");
sb.append(" return [ x, y, width, height ];");
sb.append("})();");
String jsonText = JavaScriptUtils.executeJavaScriptAndWaitForResult(view, viewClient, sb.toString());
Assert.assertFalse("Failed to retrieve bounds for " + nodeId, jsonText.trim().equalsIgnoreCase("null"));
JsonReader jsonReader = new JsonReader(new StringReader(jsonText));
int[] bounds = new int[4];
try {
jsonReader.beginArray();
int i = 0;
while (jsonReader.hasNext()) {
bounds[i++] = jsonReader.nextInt();
}
jsonReader.endArray();
Assert.assertEquals("Invalid bounds returned.", 4, i);
jsonReader.close();
} catch (IOException exception) {
Assert.fail("Failed to evaluate JavaScript: " + jsonText + "\n" + exception);
}
return new Rect(bounds[0], bounds[1], bounds[0] + bounds[2], bounds[1] + bounds[3]);
}Example 36
| Project: ComicBook-master File: JSDebuggerWebSocketClient.java View source code |
@Override
public void onMessage(ResponseBody response) throws IOException {
if (response.contentType() != WebSocket.TEXT) {
FLog.w(TAG, "Websocket received unexpected message with payload of type " + response.contentType());
return;
}
Integer replyID = null;
try {
JsonReader reader = new JsonReader(response.charStream());
String result = null;
reader.beginObject();
while (reader.hasNext()) {
String field = reader.nextName();
if (JsonToken.NULL == reader.peek()) {
reader.skipValue();
continue;
}
if ("replyID".equals(field)) {
replyID = reader.nextInt();
} else if ("result".equals(field)) {
result = reader.nextString();
} else if ("error".equals(field)) {
String error = reader.nextString();
abort(error, new JavascriptException(error));
}
}
if (replyID != null) {
triggerRequestSuccess(replyID, result);
}
} catch (IOException e) {
if (replyID != null) {
triggerRequestFailure(replyID, e);
} else {
abort("Parsing response message from websocket failed", e);
}
} finally {
response.close();
}
}Example 37
| Project: detlef-master File: Utils.java View source code |
public static String getJsonStringValue(Reader in, String key) {
JsonReader json = new JsonReader(in);
try {
try {
json.beginObject();
while (json.hasNext()) {
if (json.nextName().equals(key)) {
return json.nextString();
} else {
json.skipValue();
}
}
json.endObject();
} finally {
json.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}Example 38
| Project: Earmouse-master File: Module.java View source code |
/**
* Loads this Module's properties and data from the JSON data of the given Reader
* @param r The Reader from which to read the JSON data
* @throws IOException
*/
private void initModuleFromJson(Reader r) throws IOException {
JsonReader reader = new JsonReader(r);
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
switch(name) {
case "moduleId":
this.id = reader.nextInt();
break;
case "title":
this.title = reader.nextString();
break;
case "description":
this.description = reader.nextString();
break;
case "shortDescription":
this.shortDescription = reader.nextString();
break;
case "lowestNote":
this.lowestNote = reader.nextInt();
break;
case "highestNote":
this.highestNote = reader.nextInt();
break;
case "difficulty":
this.difficulty = reader.nextInt();
break;
case "version":
this.toolVersion = reader.nextString();
break;
case "moduleVersion":
this.moduleVersion = reader.nextInt();
break;
case "exerciseList":
reader.beginArray();
for (int i = 0; reader.hasNext(); i++) {
this.exerciseList.add(new Exercise());
reader.beginArray();
for (int j = 0; reader.hasNext(); j++) {
this.exerciseList.get(i).exerciseUnits.add(new ArrayList<Integer>());
reader.beginArray();
while (reader.hasNext()) {
this.exerciseList.get(i).exerciseUnits.get(j).add(reader.nextInt());
}
reader.endArray();
}
reader.endArray();
}
reader.endArray();
break;
case "answerList":
reader.beginArray();
while (reader.hasNext()) {
this.answerList.add(reader.nextString());
}
reader.endArray();
break;
default:
reader.skipValue();
break;
}
}
reader.endObject();
reader.close();
}Example 39
| Project: link-bubble-master File: HttpsEverywhere.java View source code |
private void ParseJSONObject(InputStream in) {
try {
JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
readJSON(reader);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}Example 40
| Project: query-builder-master File: BuiltInSerializers.java View source code |
/**
* A generic deserializer for string collections.
*
* @param serialized JSON representation of a string collection.
* @param collectionClass Concrete, instantiatable collection class, e.g. {@code ArrayList.class}.
* @param <C> A concrete collection class, e.g. {@code ArrayList<String>}.
* @return A collection instance retrieved from {@code serialized}.
*/
@NonNull
public static <C extends Collection<String>> C deserializeStringCollection(@NonNull String serialized, @NonNull Class<?> collectionClass) {
C collection = createCollection(collectionClass);
StringReader reader = new StringReader(serialized);
JsonReader jsonReader = new JsonReader(reader);
try {
jsonReader.beginArray();
while (jsonReader.hasNext()) {
if (jsonReader.peek() == JsonToken.NULL) {
jsonReader.nextNull();
collection.add(null);
} else {
collection.add(jsonReader.nextString());
}
}
jsonReader.endArray();
jsonReader.close();
return collection;
} catch (IOException e) {
return collection;
}
}Example 41
| Project: SealBrowser-master File: DOMUtils.java View source code |
/**
* Returns the rect boundaries for a node by its id.
*/
public static Rect getNodeBounds(final ContentView view, TestCallbackHelperContainer viewClient, String nodeId) throws InterruptedException, TimeoutException {
StringBuilder sb = new StringBuilder();
sb.append("(function() {");
sb.append(" var node = document.getElementById('" + nodeId + "');");
sb.append(" if (!node) return null;");
sb.append(" var width = node.offsetWidth;");
sb.append(" var height = node.offsetHeight;");
sb.append(" var x = -window.scrollX;");
sb.append(" var y = -window.scrollY;");
sb.append(" do {");
sb.append(" x += node.offsetLeft;");
sb.append(" y += node.offsetTop;");
sb.append(" } while (node = node.offsetParent);");
sb.append(" return [ x, y, width, height ];");
sb.append("})();");
String jsonText = JavaScriptUtils.executeJavaScriptAndWaitForResult(view, viewClient, sb.toString());
Assert.assertFalse("Failed to retrieve bounds for " + nodeId, jsonText.trim().equalsIgnoreCase("null"));
JsonReader jsonReader = new JsonReader(new StringReader(jsonText));
int[] bounds = new int[4];
try {
jsonReader.beginArray();
int i = 0;
while (jsonReader.hasNext()) {
bounds[i++] = jsonReader.nextInt();
}
jsonReader.endArray();
Assert.assertEquals("Invalid bounds returned.", 4, i);
jsonReader.close();
} catch (IOException exception) {
Assert.fail("Failed to evaluate JavaScript: " + jsonText + "\n" + exception);
}
return new Rect(bounds[0], bounds[1], bounds[0] + bounds[2], bounds[1] + bounds[3]);
}Example 42
| Project: the-blue-alliance-android-master File: PitLocationHelper.java View source code |
/**
* Finds a specified team in the pit location json file and caches it if found.
*
* The file should be in the following format:
*
* {"locations": { "frc111": {"div": "Tesla", "addr": "Q16"}, "frc254": {...}, ...} }
*
* In the future, the root object may contain additional properties.
*
* @param teamKey the team key to search for in the locations dict (frcXXXX)
* @return the location object if one was found
*/
private static TeamPitLocation readTeamLocationFromJson(Context context, String teamKey) {
// Load the resource into our file if we haven't done so yet
populateLocationsFileFromPackagedResourceIfNeeded(context);
JsonReader reader = null;
try {
reader = new JsonReader(new FileReader(getLocationsFile(context)));
reader.beginObject();
while (reader.hasNext()) {
String section = reader.nextName();
if (!section.equals("locations")) {
reader.skipValue();
continue;
}
reader.beginObject();
while (reader.hasNext()) {
String currentTeamKey = reader.nextName();
TbaLogger.d("reading team: " + currentTeamKey);
if (!currentTeamKey.equals(teamKey)) {
reader.skipValue();
} else {
// We found the team!
reader.beginObject();
String location = null, division = null;
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("div")) {
division = reader.nextString();
} else if (name.equals("loc")) {
location = reader.nextString();
} else {
reader.skipValue();
}
}
if (location != null && division != null) {
TeamPitLocation loc = new TeamPitLocation(division, location);
sTeamLocationCache.put(currentTeamKey, loc);
return loc;
}
}
}
reader.endObject();
}
reader.endObject();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}Example 43
| Project: YourPhotosWatch-master File: PicasaSelectActivity.java View source code |
@Override
protected List<? extends PhotoListEntry> doInBackground(String... params) {
try {
HttpURLConnection connection = (HttpURLConnection) new URL(params[0]).openConnection();
String token = PreferenceManager.getDefaultSharedPreferences(PicasaSelectActivity.this).getString("token", "");
connection.setRequestProperty("Authorization", "Bearer " + token);
connection.connect();
int code = connection.getResponseCode();
if (code == HttpURLConnection.HTTP_UNAUTHORIZED || code == HttpURLConnection.HTTP_FORBIDDEN) {
// Token cleared and forgotten.
Editor editor = settings.edit();
editor.remove("token");
editor.commit();
GoogleAuthUtil.clearToken(PicasaSelectActivity.this, token);
authenticateFromEmailAndFetch();
return null;
}
final List<PicasaPhotoListEntry> entries = new ArrayList<>();
final InputStream inputStream = connection.getInputStream();
JsonReader reader = new JsonReader(new InputStreamReader(inputStream));
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
switch(name) {
case "feed":
reader.beginObject();
while (reader.hasNext()) {
name = reader.nextName();
switch(name) {
case "entry":
reader.beginArray();
while (reader.hasNext()) {
PicasaPhotoListEntry entry = new PicasaPhotoListEntry(reader, entries.size());
if (entry.isValid())
entries.add(entry);
}
reader.endArray();
break;
default:
reader.skipValue();
}
}
reader.endObject();
break;
default:
reader.skipValue();
}
}
reader.endObject();
final int sortOrder = getIntent().getIntExtra("sort", R.id.oldest_first);
Collections.sort(entries, new Comparator<PicasaPhotoListEntry>() {
@Override
public int compare(PicasaPhotoListEntry lhs, PicasaPhotoListEntry rhs) {
if (sortOrder == R.id.oldest_first)
return lhs.getPublishDate().compareTo(rhs.getPublishDate());
else
return rhs.getPublishDate().compareTo(lhs.getPublishDate());
}
});
return entries;
} catch (IOExceptionGoogleAuthException | ReaderException | e) {
e.printStackTrace();
return null;
}
}Example 44
| Project: analytics-android-master File: Cartographer.java View source code |
/** Reads the next value in the {@link JsonReader}. */
private static Object readValue(JsonReader reader) throws IOException {
JsonToken token = reader.peek();
switch(token) {
case BEGIN_OBJECT:
return readerToMap(reader);
case BEGIN_ARRAY:
return readerToList(reader);
case BOOLEAN:
return reader.nextBoolean();
case NULL:
// consume the null token
reader.nextNull();
return null;
case NUMBER:
return reader.nextDouble();
case STRING:
return reader.nextString();
default:
throw new IllegalStateException("Invalid token " + token);
}
}Example 45
| Project: give-me-coinsMonitoringApp-master File: GMCPoolService.java View source code |
@Override
public void run() {
if (DEBUG)
Log.d(TAG, "Connecting to website: " + url_string);
try {
url = new URL(url_string);
} catch (MalformedURLException e1) {
e1.printStackTrace();
Log.e(TAG, "MalformedURLException");
}
try {
inputStream = url.openStream();
} catch (IOException e1) {
e1.printStackTrace();
Log.e(TAG, "InputStream IOException");
cancel();
}
if (DEBUG)
Log.d(TAG, "Connection should be open by now");
try {
// json is UTF-8 by default
reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
if (DEBUG)
Log.d(TAG, "Connected and reading JSON");
} catch (Exception e) {
Log.e(TAG, "Connecting failed!");
cancel();
}
if (jsonAll == null) {
try {
jsonAll = new JsonReader(reader);
} catch (NullPointerException e) {
Log.e(TAG, "JsonReader NullPointerException");
cancel();
}
}
//now lets parse the output form give-me-coins
if (DEBUG)
Log.d(TAG, "Parsing json");
//we need a way to figure out if it is CloudFlare 521 site (which is not json
if (jsonAll == null) {
cancel();
return;
}
try {
while (jsonAll.hasNext()) {
try {
switch(jsonAll.peek()) {
case BEGIN_OBJECT:
jsonAll.beginObject();
if (DEBUG)
Log.d(TAG, "JSON beginObject");
break;
case END_OBJECT:
jsonAll.endObject();
if (DEBUG)
Log.d(TAG, "JSON endObject");
break;
case NAME:
if (DEBUG)
Log.d(TAG, "Main NAME");
String name = jsonAll.nextName();
if ("hashrate".equals(name)) {
MainScreen.pool_total_hashrate = jsonAll.nextString();
} else if ("workers".equals(name)) {
MainScreen.pool_workers = jsonAll.nextString();
} else if ("shares_this_round".equals(name)) {
MainScreen.pool_round_shares = jsonAll.nextString();
} else if ("last_block".equals(name)) {
MainScreen.pool_last_block = jsonAll.nextString();
} else if (name.equals("last_block_shares")) {
MainScreen.pool_last_block_shares = jsonAll.nextString();
} else if (name.equals("last_block_finder")) {
MainScreen.pool_last_block_finder = jsonAll.nextString();
} else if (name.equals("last_block_reward")) {
MainScreen.pool_last_block_reward = jsonAll.nextString();
} else if ("difficulty".equals(name)) {
MainScreen.pool_difficulty = jsonAll.nextString();
} else {
jsonAll.skipValue();
}
break;
case NULL:
jsonAll.skipValue();
default:
jsonAll.skipValue();
if (DEBUG)
Log.d(TAG, "peek value main not valid as it is " + jsonAll.peek());
}
} catch (IllegalStateException e) {
Log.w(TAG, "IllegalStateException: " + e);
break;
} catch (IOException e) {
e.printStackTrace();
Log.w(TAG, "JSON MAIN IOException: " + e);
break;
} catch (NullPointerException e) {
Log.w(TAG, "NullPointerException: " + e);
break;
}
}
} catch (IOException e) {
e.printStackTrace();
Log.w(TAG, "JSON MAIN hasNext failed!");
}
if (DEBUG)
Log.d(TAG, "Total hashrate: " + MainScreen.pool_total_hashrate + " |Workers: " + MainScreen.pool_workers + " |Last round shares: " + MainScreen.pool_round_shares + " |last block: " + MainScreen.pool_last_block + " |Difficulty" + MainScreen.pool_difficulty);
//Pack the data for other activity to use/get
Message msg = mHandler.obtainMessage(MainScreen.POOL_DATA_READY);
mHandler.sendMessage(msg);
cancel();
}Example 46
| Project: TestingStuff-master File: LibraryManager.java View source code |
private void copyCoverMagazineFromResources(Context context, String magazineForCopying) {
final int BUFFER_SIZE = 1024 * 256;
try {
byte[] buffer = new byte[BUFFER_SIZE];
AssetManager aManager = context.getAssets();
// copy cover
String destinationFilePath = libraryPath(context) + File.separator + magazineForCopying;
String coverDestinationFilePath = libraryPath(context) + File.separator + magazineForCopying + Constants.MAGAZINE_COVER_SUFFIX;
File coverDestinationFile = new File(coverDestinationFilePath);
FileOutputStream coverDestinationStream = new FileOutputStream(coverDestinationFile);
InputStream coverSourceStream = aManager.open(magazineForCopying + Constants.MAGAZINE_COVER_SUFFIX);
int len = 0;
while ((len = coverSourceStream.read(buffer)) > 0) {
coverDestinationStream.write(buffer, 0, len);
}
coverSourceStream.close();
coverDestinationStream.close();
// mark as copied
createMagazineCopiedMark(context, magazineForCopying);
// title for journals
String title = null;
String id = null;
boolean isDownloaded = false;
try {
//try to load json file
JsonReader issuesConfigJSONFileReader = new JsonReader(new InputStreamReader(aManager.open(magazineForCopying + Constants.MAGAZINE_JSON_SUFFIX), "UTF-8"));
issuesConfigJSONFileReader.beginObject();
while (issuesConfigJSONFileReader.hasNext()) {
String name = issuesConfigJSONFileReader.nextName();
if (name.equals(Constants.ISSUE_METADATA_ATTRIBUTE_ID_ID)) {
id = issuesConfigJSONFileReader.nextString();
} else if (name.equals(Constants.ISSUE_METADATA_ATTRIBUTE_TITLE_ID)) {
title = issuesConfigJSONFileReader.nextString();
} else {
issuesConfigJSONFileReader.skipValue();
}
}
issuesConfigJSONFileReader.endObject();
} catch (Exception e) {
Log.e("Magazine Reader", "Problem loading json file for pre installed issue" + e.getMessage());
e.printStackTrace();
}
//we set the title of the installed issue only if we have not got the value from the json file
if (magazineForCopying.equalsIgnoreCase("default_magazine.epub") && (title == null)) {
title = "Sample Issue";
}
//
/*if(!ApplicationUtils.getPrefPropertyBoolean(context, "issueFromResourcesWasCopied", false)){
copyOneMagazineFromResources(context, magazineForCopying);
isDownloaded = true;
}*/
///
// add journal to db
addNewMagazine(context, destinationFilePath, coverDestinationFilePath, title, null, isDownloaded, Constants.MAGAZINE_TYPE_FROM_RESOURCES, id, null);
} catch (Exception e) {
e.printStackTrace();
}
}Example 47
| Project: CookMe-master File: JSONHelper.java View source code |
@Override
protected String doInBackground(final String... args) {
SQLiteDatabase db = database.getWritableDatabase();
db.beginTransaction();
JsonReader jsonReader = null;
String jsonName;
String jsonIngredients;
String jsonUrl;
final String NAME = "name";
final String INGREDIENTS = "ingredients";
final String URL = "url";
int lineProgress = 0;
long oldTime = System.nanoTime();
final String comma = ",";
final short MIN_INGREDIENTS_LENGTH = 5;
SQLiteStatement st = db.compileStatement("INSERT INTO " + recipesTable + " (" + recName + comma + recIngredients + comma + recURL + ") VALUES (?,?,?);");
try {
jsonReader = new JsonReader(new BufferedReader(new FileReader(fileNew)));
jsonReader.beginArray();
while (jsonReader.hasNext()) {
jsonName = null;
jsonIngredients = null;
jsonUrl = null;
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String name = jsonReader.nextName();
if (name.equals(NAME)) {
jsonName = jsonReader.nextString().replace("&", "&");
} else if (name.equals(INGREDIENTS)) {
jsonIngredients = jsonReader.nextString().replace("&", "&").trim();
if (jsonIngredients.length() < MIN_INGREDIENTS_LENGTH)
jsonIngredients = null;
else {
int lineBreak = jsonIngredients.indexOf("\n");
if (lineBreak == -1)
lineBreak = jsonIngredients.length();
if (jsonIngredients.substring(0, (lineBreak / 2)).equals(jsonIngredients.substring((lineBreak / 2) + 1, lineBreak)))
jsonIngredients = null;
}
} else if (name.equals(URL)) {
jsonUrl = jsonReader.nextString();
} else {
jsonReader.skipValue();
}
}
lineProgress++;
if (System.nanoTime() - oldTime > 1e9) {
// update every second
oldTime = System.nanoTime();
publishProgress((int) (lineProgress));
}
jsonReader.endObject();
if (jsonName != null && jsonIngredients != null && !jsonIngredients.isEmpty() && jsonUrl != null) {
st.bindString(1, jsonName);
st.bindString(2, jsonIngredients);
st.bindString(3, jsonUrl);
st.executeInsert();
st.clearBindings();
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
db.setTransactionSuccessful();
db.endTransaction();
db.close();
try {
jsonReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}Example 48
| Project: ExoPlayer-master File: SampleChooserActivity.java View source code |
@Override
protected List<SampleGroup> doInBackground(String... uris) {
List<SampleGroup> result = new ArrayList<>();
Context context = getApplicationContext();
String userAgent = Util.getUserAgent(context, "ExoPlayerDemo");
DataSource dataSource = new DefaultDataSource(context, null, userAgent, false);
for (String uri : uris) {
DataSpec dataSpec = new DataSpec(Uri.parse(uri));
InputStream inputStream = new DataSourceInputStream(dataSource, dataSpec);
try {
readSampleGroups(new JsonReader(new InputStreamReader(inputStream, "UTF-8")), result);
} catch (Exception e) {
Log.e(TAG, "Error loading sample list: " + uri, e);
sawError = true;
} finally {
Util.closeQuietly(dataSource);
}
}
return result;
}Example 49
| Project: mobile-master File: Realm.java View source code |
/**
* Creates a Realm object for each object in a JSON array. This must be done within a transaction.
* JSON properties with unknown properties will be ignored. If a {@link RealmObject} field is not present in the
* JSON object the {@link RealmObject} field will be set to the default value for that type.
* <p>
* This API is only available in API level 11 or later.
*
* @param clazz type of Realm objects created.
* @param inputStream the JSON array as a InputStream. All objects in the array must be of the specified class.
* @throws RealmException if mapping from JSON fails.
* @throws IllegalArgumentException if the JSON object doesn't have a primary key property but the corresponding
* {@link RealmObjectSchema} has a {@link io.realm.annotations.PrimaryKey} defined.
* @throws IOException if something was wrong with the input stream.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public <E extends RealmModel> void createAllFromJson(Class<E> clazz, InputStream inputStream) throws IOException {
if (clazz == null || inputStream == null) {
return;
}
checkIfValid();
JsonReader reader = new JsonReader(new InputStreamReader(inputStream, "UTF-8"));
try {
reader.beginArray();
while (reader.hasNext()) {
configuration.getSchemaMediator().createUsingJsonStream(clazz, this, reader);
}
reader.endArray();
} finally {
reader.close();
}
}Example 50
| Project: realm-java-master File: Realm.java View source code |
/**
* Creates a Realm object for each object in a JSON array. This must be done within a transaction.
* JSON properties with unknown properties will be ignored. If a {@link RealmObject} field is not present in the
* JSON object the {@link RealmObject} field will be set to the default value for that type.
* <p>
* This API is only available in API level 11 or later.
*
* @param clazz type of Realm objects created.
* @param inputStream the JSON array as a InputStream. All objects in the array must be of the specified class.
* @throws RealmException if mapping from JSON fails.
* @throws IllegalArgumentException if the JSON object doesn't have a primary key property but the corresponding
* {@link RealmObjectSchema} has a {@link io.realm.annotations.PrimaryKey} defined.
* @throws IOException if something was wrong with the input stream.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public <E extends RealmModel> void createAllFromJson(Class<E> clazz, InputStream inputStream) throws IOException {
if (clazz == null || inputStream == null) {
return;
}
checkIfValid();
JsonReader reader = new JsonReader(new InputStreamReader(inputStream, "UTF-8"));
try {
reader.beginArray();
while (reader.hasNext()) {
configuration.getSchemaMediator().createUsingJsonStream(clazz, this, reader);
}
reader.endArray();
} finally {
reader.close();
}
}Example 51
| Project: ZhihuPaper-master File: NewsDetailFragment.java View source code |
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public void onReceiveValue(String s) {
JsonReader reader = new JsonReader(new StringReader(s));
// Must set lenient to parse single values
reader.setLenient(true);
try {
if (reader.peek() != JsonToken.NULL) {
if (reader.peek() == JsonToken.STRING) {
String msg = reader.nextString();
if (msg != null) {
// Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
}
}
}
} catch (IOException e) {
Log.e("TAG", "MainActivity: IOException", e);
} finally {
try {
reader.close();
} catch (IOException e) {
}
}
}Example 52
| Project: android-sotm-master File: Db.java View source code |
private void initCards(Context context) throws IOException {
InputStream in = null;
try {
in = context.getAssets().open(CARD_FILE);
JsonReader reader = new JsonReader(new InputStreamReader(in));
// Read through top level objects
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("sets")) {
reader.beginArray();
while (reader.hasNext()) {
mTeams.clear();
CardSet set = readSet(reader);
mCardSets.add(set);
for (Card card : set.getCards()) {
mCards.put(card.getId(), card);
mReverseCardSetCache.put(card, set);
}
for (Card card : mTeams.keySet()) {
Card team = mCards.get(mTeams.get(card));
team.addTeamMember(card);
}
}
reader.endArray();
} else if (name.equals("alternates")) {
readAlternates(reader);
} else {
reader.skipValue();
}
}
reader.endObject();
} finally {
in.close();
}
}Example 53
| Project: blindr-master File: Server.java View source code |
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
Log.i(TAG, "User pictures response: " + result);
List<String> pictures = new ArrayList<String>();
StringReader in = new StringReader(result);
JsonReader reader = new JsonReader(in);
reader.beginArray();
while (reader.hasNext()) {
for (String s : reader.nextString().split(",")) {
pictures.add(s);
}
}
reader.endArray();
reader.close();
in.close();
for (FacebookProfileListener listener : profileListeners) {
listener.onSlideshowPicturesReceived(pictures);
}
} catch (IOException e) {
Log.i(TAG, "Something went wrong when fetching the pictures.");
e.printStackTrace();
} catch (Exception e) {
Log.i(TAG, "Something went wrong when fetching the pictures.");
e.printStackTrace();
}
}Example 54
| Project: android-15-master File: JsonReader.java View source code |
/**
* Returns the type of the next token without consuming it.
*/
public JsonToken peek() throws IOException {
if (token != null) {
return token;
}
switch(peekStack()) {
case EMPTY_DOCUMENT:
replaceTop(JsonScope.NONEMPTY_DOCUMENT);
JsonToken firstToken = nextValue();
if (!lenient && token != JsonToken.BEGIN_ARRAY && token != JsonToken.BEGIN_OBJECT) {
throw new IOException("Expected JSON document to start with '[' or '{' but was " + token);
}
return firstToken;
case EMPTY_ARRAY:
return nextInArray(true);
case NONEMPTY_ARRAY:
return nextInArray(false);
case EMPTY_OBJECT:
return nextInObject(true);
case DANGLING_NAME:
return objectValue();
case NONEMPTY_OBJECT:
return nextInObject(false);
case NONEMPTY_DOCUMENT:
try {
JsonToken token = nextValue();
if (lenient) {
return token;
}
throw syntaxError("Expected EOF");
} catch (EOFException e) {
return token = JsonToken.END_DOCUMENT;
}
case CLOSED:
throw new IllegalStateException("JsonReader is closed");
default:
throw new AssertionError();
}
}Example 55
| Project: cnAndroidDocs-master File: JsonReader.java View source code |
/**
* Returns the type of the next token without consuming it.
*/
public JsonToken peek() throws IOException {
if (token != null) {
return token;
}
switch(peekStack()) {
case EMPTY_DOCUMENT:
replaceTop(JsonScope.NONEMPTY_DOCUMENT);
JsonToken firstToken = nextValue();
if (!lenient && token != JsonToken.BEGIN_ARRAY && token != JsonToken.BEGIN_OBJECT) {
throw new IOException("Expected JSON document to start with '[' or '{' but was " + token);
}
return firstToken;
case EMPTY_ARRAY:
return nextInArray(true);
case NONEMPTY_ARRAY:
return nextInArray(false);
case EMPTY_OBJECT:
return nextInObject(true);
case DANGLING_NAME:
return objectValue();
case NONEMPTY_OBJECT:
return nextInObject(false);
case NONEMPTY_DOCUMENT:
try {
JsonToken token = nextValue();
if (lenient) {
return token;
}
throw syntaxError("Expected EOF");
} catch (EOFException e) {
return token = JsonToken.END_DOCUMENT;
}
case CLOSED:
throw new IllegalStateException("JsonReader is closed");
default:
throw new AssertionError();
}
}Example 56
| Project: frameworks_base_disabled-master File: JsonReader.java View source code |
/**
* Returns the type of the next token without consuming it.
*/
public JsonToken peek() throws IOException {
if (token != null) {
return token;
}
switch(peekStack()) {
case EMPTY_DOCUMENT:
replaceTop(JsonScope.NONEMPTY_DOCUMENT);
JsonToken firstToken = nextValue();
if (!lenient && token != JsonToken.BEGIN_ARRAY && token != JsonToken.BEGIN_OBJECT) {
throw new IOException("Expected JSON document to start with '[' or '{' but was " + token);
}
return firstToken;
case EMPTY_ARRAY:
return nextInArray(true);
case NONEMPTY_ARRAY:
return nextInArray(false);
case EMPTY_OBJECT:
return nextInObject(true);
case DANGLING_NAME:
return objectValue();
case NONEMPTY_OBJECT:
return nextInObject(false);
case NONEMPTY_DOCUMENT:
try {
JsonToken token = nextValue();
if (lenient) {
return token;
}
throw syntaxError("Expected EOF");
} catch (EOFException e) {
return token = JsonToken.END_DOCUMENT;
}
case CLOSED:
throw new IllegalStateException("JsonReader is closed");
default:
throw new AssertionError();
}
}Example 57
| Project: mecha-master File: JsonReader.java View source code |
/**
* Returns the type of the next token without consuming it.
*/
public JsonToken peek() throws IOException {
if (token != null) {
return token;
}
switch(peekStack()) {
case EMPTY_DOCUMENT:
replaceTop(JsonScope.NONEMPTY_DOCUMENT);
JsonToken firstToken = nextValue();
if (!lenient && token != JsonToken.BEGIN_ARRAY && token != JsonToken.BEGIN_OBJECT) {
throw new IOException("Expected JSON document to start with '[' or '{' but was " + token);
}
return firstToken;
case EMPTY_ARRAY:
return nextInArray(true);
case NONEMPTY_ARRAY:
return nextInArray(false);
case EMPTY_OBJECT:
return nextInObject(true);
case DANGLING_NAME:
return objectValue();
case NONEMPTY_OBJECT:
return nextInObject(false);
case NONEMPTY_DOCUMENT:
try {
JsonToken token = nextValue();
if (lenient) {
return token;
}
throw syntaxError("Expected EOF");
} catch (EOFException e) {
return token = JsonToken.END_DOCUMENT;
}
case CLOSED:
throw new IllegalStateException("JsonReader is closed");
default:
throw new AssertionError();
}
}Example 58
| Project: mechanoid-master File: JsonReader.java View source code |
/**
* Returns the type of the next token without consuming it.
*/
public JsonToken peek() throws IOException {
if (token != null) {
return token;
}
switch(peekStack()) {
case EMPTY_DOCUMENT:
replaceTop(JsonScope.NONEMPTY_DOCUMENT);
JsonToken firstToken = nextValue();
if (!lenient && token != JsonToken.BEGIN_ARRAY && token != JsonToken.BEGIN_OBJECT) {
throw new IOException("Expected JSON document to start with '[' or '{' but was " + token);
}
return firstToken;
case EMPTY_ARRAY:
return nextInArray(true);
case NONEMPTY_ARRAY:
return nextInArray(false);
case EMPTY_OBJECT:
return nextInObject(true);
case DANGLING_NAME:
return objectValue();
case NONEMPTY_OBJECT:
return nextInObject(false);
case NONEMPTY_DOCUMENT:
try {
JsonToken token = nextValue();
if (lenient) {
return token;
}
throw syntaxError("Expected EOF");
} catch (EOFException e) {
return token = JsonToken.END_DOCUMENT;
}
case CLOSED:
throw new IllegalStateException("JsonReader is closed");
default:
throw new AssertionError();
}
}Example 59
| Project: platform_packages_providers_telephonyprovider-master File: TelephonyBackupAgent.java View source code |
private void doRestoreFile(String fileName, FileDescriptor fd) throws IOException {
if (DEBUG) {
Log.i(TAG, "Restoring file " + fileName);
}
try (JsonReader jsonReader = getJsonReader(fd)) {
if (fileName.endsWith(SMS_BACKUP_FILE_SUFFIX)) {
if (DEBUG) {
Log.i(TAG, "Restoring SMS");
}
putSmsMessagesToProvider(jsonReader);
} else if (fileName.endsWith(MMS_BACKUP_FILE_SUFFIX)) {
if (DEBUG) {
Log.i(TAG, "Restoring text MMS");
}
putMmsMessagesToProvider(jsonReader);
} else {
if (DEBUG) {
Log.e(TAG, "Unknown file to restore:" + fileName);
}
}
}
}Example 60
| Project: property-db-master File: JsonReader.java View source code |
/**
* Returns the type of the next token without consuming it.
*/
public JsonToken peek() throws IOException {
if (token != null) {
return token;
}
switch(peekStack()) {
case EMPTY_DOCUMENT:
replaceTop(JsonScope.NONEMPTY_DOCUMENT);
JsonToken firstToken = nextValue();
if (!lenient && token != JsonToken.BEGIN_ARRAY && token != JsonToken.BEGIN_OBJECT) {
throw new IOException("Expected JSON document to start with '[' or '{' but was " + token);
}
return firstToken;
case EMPTY_ARRAY:
return nextInArray(true);
case NONEMPTY_ARRAY:
return nextInArray(false);
case EMPTY_OBJECT:
return nextInObject(true);
case DANGLING_NAME:
return objectValue();
case NONEMPTY_OBJECT:
return nextInObject(false);
case NONEMPTY_DOCUMENT:
try {
JsonToken token = nextValue();
if (lenient) {
return token;
}
throw syntaxError("Expected EOF");
} catch (EOFException e) {
return token = JsonToken.END_DOCUMENT;
}
case CLOSED:
throw new IllegalStateException("JsonReader is closed");
default:
throw new AssertionError();
}
}Example 61
| Project: XobotOS-master File: JsonReader.java View source code |
/**
* Returns the type of the next token without consuming it.
*/
public JsonToken peek() throws IOException {
if (token != null) {
return token;
}
switch(peekStack()) {
case EMPTY_DOCUMENT:
replaceTop(JsonScope.NONEMPTY_DOCUMENT);
JsonToken firstToken = nextValue();
if (!lenient && token != JsonToken.BEGIN_ARRAY && token != JsonToken.BEGIN_OBJECT) {
throw new IOException("Expected JSON document to start with '[' or '{' but was " + token);
}
return firstToken;
case EMPTY_ARRAY:
return nextInArray(true);
case NONEMPTY_ARRAY:
return nextInArray(false);
case EMPTY_OBJECT:
return nextInObject(true);
case DANGLING_NAME:
return objectValue();
case NONEMPTY_OBJECT:
return nextInObject(false);
case NONEMPTY_DOCUMENT:
try {
JsonToken token = nextValue();
if (lenient) {
return token;
}
throw syntaxError("Expected EOF");
} catch (EOFException e) {
return token = JsonToken.END_DOCUMENT;
}
case CLOSED:
throw new IllegalStateException("JsonReader is closed");
default:
throw new AssertionError();
}
}Example 62
| Project: robolectric-master File: ShadowJsonReaderTest.java View source code |
@Test
public void shouldWork() throws Exception {
JsonReader jsonReader = new JsonReader(new StringReader("{\"abc\": \"def\"}"));
jsonReader.beginObject();
assertThat(jsonReader.nextName()).isEqualTo("abc");
assertThat(jsonReader.nextString()).isEqualTo("def");
jsonReader.endObject();
}Example 63
| Project: google-http-java-client-master File: AndroidJsonFactory.java View source code |
@Override
public JsonParser createJsonParser(Reader reader) {
return new AndroidJsonParser(this, new JsonReader(reader));
}