Java Examples for org.json.JSONArray
The following java examples will help you to understand the usage of org.json.JSONArray. These source code samples are taken from different open source projects.
Example 1
| Project: Web-Karma-master File: RefreshWorksheetCommandFactory.java View source code |
@Override
public Command createCommand(HttpServletRequest request, Workspace workspace) {
String worksheetId = request.getParameter(Arguments.worksheetId.name());
String updates = request.getParameter(Arguments.updates.name());
JSONArray updatesArr = new org.json.JSONArray(updates);
String selectionName = request.getParameter(Arguments.selectionName.name());
return new RefreshWorksheetCommand(getNewId(workspace), Command.NEW_MODEL, worksheetId, updatesArr, selectionName);
}Example 2
| Project: RipplePower-master File: GatewayItem.java View source code |
public void copyFrom(JSONObject result) {
this.json = result;
if (result != null) {
name = result.optString("name");
account = result.optString("account");
featured = result.optBoolean("featured");
JSONArray arrays = result.optJSONArray("assets");
if (arrays != null && arrays.length() > 0) {
for (int i = 0; i < arrays.length(); i++) {
assets.add(arrays.optString(i));
}
}
startdate = result.optString("start_date");
}
}Example 3
| Project: WordsDetection-master File: GetStatusesCount.java View source code |
public static void main(String[] args) throws JSONException {
String access_token = args[0];
String ids = args[1];
Timeline tm = new Timeline(access_token);
try {
JSONArray json = tm.getStatusesCount(ids);
for (int i = 0; i < json.length(); i++) {
Log.logInfo(json.getString(i));
}
} catch (WeiboException e) {
e.printStackTrace();
}
}Example 4
| Project: NIM_Android_Demo-master File: ExtensionHelper.java View source code |
private static Map<String, Object> recursiveParseJsonObject(org.json.JSONObject json) throws org.json.JSONException {
if (json == null) {
return null;
}
Map<String, Object> map = new HashMap<>(json.length());
String key;
Object value;
Iterator<String> i = json.keys();
while (i.hasNext()) {
key = i.next();
value = json.get(key);
if (value instanceof org.json.JSONArray) {
map.put(key, recursiveParseJsonArray((org.json.JSONArray) value));
} else if (value instanceof org.json.JSONObject) {
map.put(key, recursiveParseJsonObject((org.json.JSONObject) value));
} else {
map.put(key, value);
}
}
return map;
}Example 5
| Project: bocai_android-master File: JSONUtils.java View source code |
@SuppressWarnings("rawtypes")
public static Map toMap(JSONObject jsonObject) throws JSONException {
HashMap<String, Object> hashMap = new HashMap<String, Object>();
for (Iterator iterator = jsonObject.keys(); iterator.hasNext(); ) {
String key = (String) iterator.next();
Object obj = jsonObject.get(key);
if (obj.getClass().getName().equalsIgnoreCase("org.json.JSONObject")) {
Map map = toMap((JSONObject) obj);
hashMap.put(key, map);
} else if (obj.getClass().getName().equalsIgnoreCase("org.json.JSONArray")) {
ArrayList<Object> arraylist = new ArrayList<Object>();
JSONArray jsonArray = (JSONArray) obj;
int index = 0;
int length = jsonArray.length();
while (index < length) {
Object element = jsonArray.get(index);
if (element instanceof JSONObject) {
Map tempMap = toMap((JSONObject) element);
arraylist.add(tempMap);
} else {
arraylist.add(element);
}
index++;
}
hashMap.put(key, arraylist);
} else {
hashMap.put(key, obj);
}
}
return hashMap;
}Example 6
| Project: RESTful_Java-master File: View.java View source code |
public JSONArray generateJSON() throws JSONException { JSONArray jsonResult = new JSONArray(); JSONObject jsonObj = new JSONObject(); for (Object i : this.result) { Phone cel = (Phone) i; try { jsonObj.put("price", cel.getPrice()); jsonObj.put("color", cel.getColor()); jsonObj.put("OS", cel.getOS()); jsonObj.put("brand", cel.getSpec().getBrand()); jsonObj.put("model", cel.getSpec().getModel()); jsonResult.put(jsonObj); } catch (JSONException e) { e.printStackTrace(); } } return jsonResult; }
Example 7
| Project: aDoubanReader-master File: UserParser.java View source code |
private void parseImage(User user, JSONObject jsonObject) throws JSONException, IOException {
JSONArray linkArray = jsonObject.getJSONArray("link");
for (int i = 0; i < linkArray.length(); i++) {
JSONObject linkJson = linkArray.getJSONObject(i);
if (linkJson.getString("@rel").equals("icon")) {
String imageUrl = linkJson.getString("@href");
user.setImageDrawable(new BitmapDrawable(BitmapFactory.decodeStream(new URL(imageUrl).openStream())));
}
}
}Example 8
| Project: androiddevice.info-master File: PackageSigProperty.java View source code |
@Override
public Object getProperty() {
try {
JSONArray result = new JSONArray();
PackageInfo packageInfo = Application.getContext().getPackageManager().getPackageInfo("android", PackageManager.GET_SIGNATURES);
for (Signature item : Arrays.asList(packageInfo.signatures)) {
MessageDigest digest = null;
try {
digest = MessageDigest.getInstance("SHA-256");
digest.update(item.toCharsString().getBytes());
result.put(byteToHexString(digest.digest()));
} catch (NoSuchAlgorithmException e) {
}
}
return result;
} catch (PackageManager.NameNotFoundException e) {
return JSONObject.NULL;
}
}Example 9
| Project: apiman-plugins-master File: JsonToXmlTransformer.java View source code |
@Override
public String transform(String json) {
String ROOT = null;
JSONObject jsonObject = null;
if (//$NON-NLS-1$
json.trim().startsWith("{")) {
jsonObject = new JSONObject(json);
if (jsonObject.length() > 1) {
//$NON-NLS-1$
ROOT = "root";
}
} else {
JSONArray jsonArray = new JSONArray(json);
jsonObject = new JSONObject().put(ELEMENT, jsonArray);
//$NON-NLS-1$
ROOT = "root";
}
return XML.toString(jsonObject, ROOT);
}Example 10
| Project: AppAssit-master File: AbsConvertModel.java View source code |
@Override
public ArrayList<T> newArray(JSONArray jArray) {
// TODO Auto-generated method stub
if (jArray == null) {
return null;
}
ArrayList<T> list = new ArrayList<T>();
int length = jArray.length();
for (int i = 0; i < length; i++) {
JSONObject jObj = jArray.optJSONObject(i);
if (jObj == null) {
continue;
}
T t = createFromJson(jObj);
if (t == null) {
continue;
}
list.add(t);
}
return list;
}Example 11
| Project: atlas-master File: JsonUtils.java View source code |
static float valueFromObject(Object object) {
if (object instanceof Float) {
return (float) object;
} else if (object instanceof Integer) {
return (Integer) object;
} else if (object instanceof Double) {
return (float) (double) object;
} else if (object instanceof JSONArray) {
return (float) ((JSONArray) object).optDouble(0);
} else {
return 0;
}
}Example 12
| Project: Autoshkolla-master File: ExamsLayer.java View source code |
@Override public void onSuccess(int statusCode, Header[] headers, JSONArray response) { // List<Exam> examsList = new ArrayList<Exam>(); // // If the response is JSONObject instead of expected JSONArray // for (int i = 0; i < response.length(); i++) { // try { // JSONObject exam = response.getJSONObject(i); // //create model from object // Exam e = Exam.createFromJSON(exam); // if (e != null) { // examsList.add(e); // Log.e("Exam", e.name); // } // } catch (JSONException e) { // continue; // } // } // r.onSuccess(examsList); }
Example 13
| Project: CodeComb.Mobile.Android-master File: JsonUtil.java View source code |
public static String convertToString(JSONArray jsonArray) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < jsonArray.length(); i++) {
try {
builder.append(jsonArray.getString(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
return builder.toString().trim();
}Example 14
| Project: FingerColoring-Android-master File: TranslateUtil.java View source code |
public static String translateByBaiduAPI(String h1) {
MyHttpClient myHttpClient = new MyHttpClient();
String getrest = MyApplication.BAIDUTRANSLATEAPI + "q=" + h1 + "&from=auto&to=auto";
try {
String ret = myHttpClient.executeGetRequest(getrest);
if (ret != null) {
JSONObject jsonObject = new JSONObject(ret);
JSONArray jsonArray = jsonObject.getJSONArray("trans_result");
return jsonArray.getJSONObject(0).getString("dst");
} else {
return h1;
}
} catch (Exception e) {
L.e(e.getMessage());
return h1;
}
}Example 15
| Project: hplookball-master File: PlayersRatingByUserListResp.java View source code |
@Override
public void paser(JSONObject json) throws Exception {
json = json.optJSONObject(KEY_RESULT);
profile = new PlayerRatingEntity();
profile.paser(json.optJSONObject("profile"));
JSONArray array = json.optJSONArray(KEY_DATA);
int size = 0;
if (array != null && (size = array.length()) > 0) {
mList = new ArrayList<PlayerRatingByUserEntity>();
PlayerRatingByUserEntity player;
for (int i = 0; i < size; i++) {
player = new PlayerRatingByUserEntity();
player.paser(array.getJSONObject(i));
mList.add(player);
}
}
hasMore = json.optInt("nextDataExists", 0) == 0 ? false : true;
}Example 16
| Project: IPCPlayer-master File: ParseSample.java View source code |
public void parseJson() {
try {
JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
String query = object.getString("query");
System.out.println("query: " + query);
JSONArray locations = object.getJSONArray("locations");
System.out.println("locations: " + locations);
for (int i = 0; i < locations.length(); i++) {
int location = locations.getInt(i);
System.out.println("location: " + location);
}
} catch (Exception e) {
e.printStackTrace();
}
}Example 17
| Project: liquid-sdk-android-master File: InappMessageParser.java View source code |
public static ArrayList<LQInAppMessage> parse(JSONArray array) {
ArrayList<LQInAppMessage> list = new ArrayList<>();
int length = array.length();
for (int i = 0; i < length; ++i) {
try {
JSONObject inapp = array.getJSONObject(i);
list.add(new LQInAppMessage(inapp));
} catch (JSONException e) {
LQLog.error("Error parsing inapp message " + array);
}
}
return list;
}Example 18
| Project: lottie-android-master File: JsonUtils.java View source code |
static float valueFromObject(Object object) {
if (object instanceof Float) {
return (float) object;
} else if (object instanceof Integer) {
return (Integer) object;
} else if (object instanceof Double) {
return (float) (double) object;
} else if (object instanceof JSONArray) {
return (float) ((JSONArray) object).optDouble(0);
} else {
return 0;
}
}Example 19
| Project: monaca-framework-android-master File: MonacaSplashPlugin.java View source code |
@Override
public PluginResult execute(String action, JSONArray args, String callbackId) {
// push
if (action.equals("show")) {
getMonacaPageActivity().showMonacaSplash();
return new PluginResult(PluginResult.Status.OK);
}
// push
if (action.equals("hide")) {
getMonacaPageActivity().removeMonacaSplash();
return new PluginResult(PluginResult.Status.OK);
}
return new PluginResult(Status.INVALID_ACTION);
}Example 20
| Project: WordPress-Android-master File: ReaderSimplePostList.java View source code |
public static ReaderSimplePostList fromJsonPosts(@NonNull JSONArray jsonPosts) {
ReaderSimplePostList posts = new ReaderSimplePostList();
for (int i = 0; i < jsonPosts.length(); i++) {
JSONObject jsonRelatedPost = jsonPosts.optJSONObject(i);
if (jsonRelatedPost != null) {
ReaderSimplePost relatedPost = ReaderSimplePost.fromJson(jsonRelatedPost);
if (relatedPost != null) {
posts.add(relatedPost);
}
}
}
return posts;
}Example 21
| Project: SimplifyReader-master File: JsonArrayRequest.java View source code |
@Override protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) { try { String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET)); return Response.success(new JSONArray(jsonString), HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } catch (JSONException je) { return Response.error(new ParseError(je)); } }
Example 22
| Project: activiti-webapp-rest-generic-master File: ProcessInstancesObjectBuilder.java View source code |
@SuppressWarnings("unchecked")
public JSONObject createJsonObject(Object modelObject) throws JSONException {
Map<String, Object> model = getModelAsMap(modelObject);
JSONObject result = new JSONObject();
JSONUtil.putPagingInfo(result, model);
List<HistoricProcessInstance> definitions = (List<HistoricProcessInstance>) model.get("processInstances");
JSONArray dataArray = JSONUtil.putNewArray(result, "data");
for (HistoricProcessInstance processDefinition : definitions) {
JSONObject jsonTask = converter.getJSONObject(processDefinition);
dataArray.put(jsonTask);
}
return result;
}Example 23
| Project: AndroidSnooper-master File: JsonResponseFormatter.java View source code |
@Override
public String format(String response) {
try {
Object json = new JSONTokener(response).nextValue();
if (json instanceof JSONObject) {
return new JSONObject(response).toString(INDENT_SPACES);
} else if (json instanceof JSONArray) {
return new JSONArray(response).toString(INDENT_SPACES);
}
} catch (JSONException e) {
e.printStackTrace();
Log.d(TAG, e.getMessage(), e);
}
return "";
}Example 24
| Project: Android_Example_Projects-master File: Legs.java View source code |
private void parseSteps(JSONObject leg) {
try {
if (!leg.isNull("steps")) {
JSONArray step = leg.getJSONArray("steps");
for (int i = 0; i < step.length(); i++) {
JSONObject obj = step.getJSONObject(i);
Log.d("Step", String.valueOf(i));
steps.add(new Steps(obj));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}Example 25
| Project: ATT_APIPlatform_SampleApps-master File: DeltaResponse.java View source code |
public static DeltaResponse valueOf(JSONObject jobj) {
JSONObject jdeltaResponse = jobj.getJSONObject("deltaResponse");
String state = jdeltaResponse.getString("state");
JSONArray jdelta = jdeltaResponse.getJSONArray("delta");
Delta[] delta = new Delta[jdelta.length()];
for (int i = 0; i < jdelta.length(); ++i) delta[i] = Delta.valueOf(jdelta.getJSONObject(i));
return new DeltaResponse(state, delta);
}Example 26
| Project: betsy-master File: CamundaApiBasedProcessInstanceOutcomeChecker.java View source code |
private boolean isProcessDeployed(String key) {
JSONArray result = JsonHelper.getJsonArray(restURL + "/process-definition", 200);
for (int i = 0; i < result.length(); i++) {
try {
if ((key + ".bpmn").equals(result.getJSONObject(i).get("resource"))) {
return true;
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
return false;
}Example 27
| Project: BioWiki-master File: ReaderUserList.java View source code |
/*
* passed json is response from getting likes for a post
*/
public static ReaderUserList fromJsonLikes(JSONObject json) {
ReaderUserList users = new ReaderUserList();
if (json == null)
return users;
JSONArray jsonLikes = json.optJSONArray("likes");
if (jsonLikes != null) {
for (int i = 0; i < jsonLikes.length(); i++) users.add(ReaderUser.fromJson(jsonLikes.optJSONObject(i)));
}
return users;
}Example 28
| Project: CanvasAPI-master File: VimeoSynchronousAPI.java View source code |
/**
* getVimeoThumbnail is a method used to get a thumbnail url for a given vimeo video id.
* @param vimeoId
* @param context
* @return
*/
public static String getVimeoThumbnail(String vimeoId, Context context) {
try {
String url = "http://vimeo.com/api/v2/video/" + vimeoId + ".json";
String response = HttpHelpers.externalHttpGet(context, url).responseBody;
JSONArray a = new JSONArray(response);
JSONObject json = a.getJSONObject(0);
if (json.has("thumbnail_small"))
return json.getString("thumbnail_small");
else
return json.getString("thumbnail");
} catch (Exception E) {
return "default_video_poster.png";
}
}Example 29
| Project: CarpoolBackend-master File: UserSearchHistoryResource.java View source code |
@Get
public Representation getUserSearchHistory() {
int userId = -1;
ArrayList<SearchRepresentation> searchHistory = new ArrayList<SearchRepresentation>();
JSONArray resultArr = new JSONArray();
try {
userId = Integer.parseInt(this.getAttribute("id"));
searchHistory = AwsMain.getUserSearchHistory(userId);
resultArr = JSONFactory.toJSON(searchHistory);
} catch (Exception e) {
return this.doException(e);
}
Representation response = new JsonRepresentation(resultArr);
addCORSHeader();
return response;
}Example 30
| Project: CiAN-master File: AppVersion.java View source code |
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
try {
if (action.equals("getVersionNumber")) {
PackageManager packageManager = this.cordova.getActivity().getPackageManager();
callbackContext.success(packageManager.getPackageInfo(this.cordova.getActivity().getPackageName(), 0).versionName);
return true;
}
return false;
} catch (NameNotFoundException e) {
callbackContext.success("N/A");
return true;
}
}Example 31
| Project: ciandt_tt-master File: AppVersion.java View source code |
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
try {
if (action.equals("getVersionNumber")) {
PackageManager packageManager = this.cordova.getActivity().getPackageManager();
callbackContext.success(packageManager.getPackageInfo(this.cordova.getActivity().getPackageName(), 0).versionName);
return true;
}
return false;
} catch (NameNotFoundException e) {
callbackContext.success("N/A");
return true;
}
}Example 32
| Project: cordova-plugin-baidu-geolocation-master File: MessageBuilder.java View source code |
public JSONArray build() { Position result = new Position().setTimestamp(System.currentTimeMillis()).setCoords(new Coordinates().setLatitude(location.getLatitude()).setLongitude(location.getLongitude()).setAccuracy(location.getRadius()).setHeading(location.getDirection()).setSpeed(location.getSpeed()).setAltitude(location.getAltitude())); JSONObject extra = new JSONObject(); try { extra.put("type", location.getLocType()); } catch (JSONException e) { e.printStackTrace(); } JSONArray message = new JSONArray(); message.put(result.toJSON()); message.put(extra); return message; }
Example 33
| Project: discord.jar-master File: UserUpdatePoll.java View source code |
@Override
public void process(JSONObject content, JSONObject rawRequest, Server server) {
JSONObject user = content.getJSONObject("user");
JSONArray rolesArray = content.getJSONArray("roles");
GroupUser gUser = server.getGroupUserById(user.getString("id"));
((UserImpl) gUser.getUser()).setUsername(user.getString("username"));
((UserImpl) gUser.getUser()).setAvatarId(user.getString("avatar"));
((UserImpl) gUser.getUser()).setAvatar("https://cdn.discordapp.com/avatars/" + api.getSelfInfo().getId() + "/" + (user.isNull("avatar") ? "" : user.getString("avatar")) + ".jpg");
for (int i = 0; i < rolesArray.length(); i++) {
JSONObject roleObj = rolesArray.getJSONObject(i);
gUser.setRole(roleObj.getString("name"));
}
}Example 34
| Project: DroidTranslate-master File: JsonUtil.java View source code |
public static String getTranslatedTextFromJson(String jsonString) {
try {
JSONObject root = new JSONObject(jsonString);
JSONObject data = root.getJSONObject(DATA);
JSONArray translations = data.getJSONArray(TRANSLATIONS);
JSONObject translatedText = translations.getJSONObject(0);
return translatedText.getString(TRANSLATED_TEXT);
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
return null;
}Example 35
| Project: evercam.java-master File: SnapshotsWithPaging.java View source code |
/**
* Return the model list, it will be an empty list if no model exists.
*/
public ArrayList<Snapshot> getSnapshotsList() {
ArrayList<Snapshot> snapshotList = new ArrayList<Snapshot>();
JSONArray snapshotJsonArray = jsonObject.getJSONArray("snapshots");
if (snapshotJsonArray.length() > 0) {
for (int index = 0; index < snapshotJsonArray.length(); index++) {
JSONObject snapshotJsonObject = snapshotJsonArray.getJSONObject(index);
snapshotList.add(new Snapshot(snapshotJsonObject));
}
}
return snapshotList;
}Example 36
| Project: FineDay-master File: CityJsonUtils.java View source code |
public List<CityModel> readJson(String jsonStr) throws Exception {
if (TextUtils.isEmpty(jsonStr))
return null;
jsonStr = toJson(jsonStr);
JSONArray array = new JSONArray(jsonStr);
for (int i = 0; i < array.length(); i++) {
JSONArray ja = array.getJSONArray(i);
CityModel model = new CityModel();
model.setCityId(ja.getString(1));
model.setCityName(ja.getString(0));
models.add(model);
}
return models;
}Example 37
| Project: gaia-master File: ContactParser.java View source code |
@Override
public Collection<ContactType> parser(JSONArray jsonArray) {
ArrayList<ContactType> contactlist = new ArrayList<ContactType>();
try {
for (int i = 0; i < jsonArray.length(); i++) {
contactlist.add(parser((JSONObject) jsonArray.get(i)));
}
return contactlist;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}Example 38
| Project: GCA-Android-master File: JSONReader.java View source code |
public static JSONArray parseStream(InputStream stream) throws IOException, JSONException { InputStreamReader isr = new InputStreamReader(stream); BufferedReader jsonReader = new BufferedReader(isr); StringBuilder jsonBuilder = new StringBuilder(); for (String line = null; (line = jsonReader.readLine()) != null; ) { jsonBuilder.append(line).append("\n"); } JSONTokener tokener = new JSONTokener(jsonBuilder.toString()); return new JSONArray(tokener); }
Example 39
| Project: glide-master File: PhotoJsonStringParser.java View source code |
List<Photo> parse(String response) throws JSONException {
JSONObject searchResults = new JSONObject(response.substring(FLICKR_API_PREFIX_LENGTH, response.length() - 1));
JSONArray photos = searchResults.getJSONObject("photos").getJSONArray("photo");
List<Photo> results = new ArrayList<>(photos.length());
for (int i = 0, size = photos.length(); i < size; i++) {
results.add(new Photo(photos.getJSONObject(i)));
}
return results;
}Example 40
| Project: goodnews-master File: ItemReferenceJsonAdapter.java View source code |
@Override
public ItemReference read(JSONObject json) throws JSONException {
final ItemReference ref = create();
ref.setId(Long.parseLong(json.getString("id")));
ref.setTimestampUSec(Long.parseLong(json.getString("timestampUsec")));
final JSONArray jsonDirectStreamIds = json.getJSONArray("directStreamIds");
final List<ElementId> directStreamIds = new ArrayList<ElementId>(jsonDirectStreamIds.length());
for (int i = 0; i < jsonDirectStreamIds.length(); ++i) {
directStreamIds.add(new ElementId(jsonDirectStreamIds.getString(i)));
}
ref.setDirectStreamIds(directStreamIds);
return ref;
}Example 41
| Project: jsmodify-plugin-master File: ProgramPoint.java View source code |
public String getTraceRecord(JSONArray data) throws JSONException { StringBuffer result = new StringBuffer(); result.append(name + "::" + lineNo + "\n"); for (int i = 0; i < data.length(); i++) { JSONArray item = data.getJSONArray(i); for (int j = 0; j < item.length(); j++) result.append(item.get(j) + "::"); } result.append("\n"); result.append("================================================"); result.append("\n"); return result.toString(); }
Example 42
| Project: KadecotCore-master File: WampUnsubscribedMessageImplTestCase.java View source code |
public void testCtor() {
JSONArray msg = new JSONArray();
msg.put(WampMessageType.UNSUBSCRIBED);
int requestId = 1;
msg.put(requestId);
int subscriptionId = 2;
msg.put(subscriptionId);
WampUnsubscribedMessageImpl unsubscribed = new WampUnsubscribedMessageImpl(msg);
assertNotNull(unsubscribed);
assertTrue(unsubscribed.isUnsubscribedMessage());
assertTrue(unsubscribed.getRequestId() == requestId);
}Example 43
| Project: kanqiu_letv-master File: VideoListParser.java View source code |
@Override
public VideoList parse(JSONObject data) throws Exception {
if (data != null) {
JSONArray array = getJSONArray(data, "videoInfo");
if (array != null && array.length() > 0) {
VideoParser parser = new VideoParser();
VideoList list = new VideoList();
for (int i = 0; i < array.length(); i++) {
JSONObject object = getJSONObject(array, i);
list.add(parser.parse(object));
}
if (has(data, "pagenum")) {
list.setPagenum(getInt(data, "pagenum"));
}
if (has(data, "videoPosition")) {
list.setVideoPosition(getInt(data, "videoPosition"));
}
return list;
}
}
return null;
}Example 44
| Project: Logg-master File: JsonPrinter.java View source code |
@Override
public void printer(Type type, String tag, String object) {
String json;
try {
if (object.startsWith("{")) {
JSONObject jsonObject = new JSONObject(object);
json = jsonObject.toString(JSON_INDENT);
} else if (object.startsWith("{")) {
JSONArray jsonArray = new JSONArray(object);
json = jsonArray.toString(JSON_INDENT);
} else {
json = object;
}
} catch (JSONException e) {
json = object;
}
super.printer(type, tag, json);
}Example 45
| Project: magpi-android-master File: PebbleNotifier.java View source code |
public static void notify(Context ctx, String title, String body) {
final Intent i = new Intent("com.getpebble.action.SEND_NOTIFICATION");
final Map data = new HashMap();
data.put("title", title);
data.put("body", body);
final JSONObject jsonData = new JSONObject(data);
final String notificationData = new JSONArray().put(jsonData).toString();
i.putExtra("messageType", "PEBBLE_ALERT");
i.putExtra("sender", "The MagPi");
i.putExtra("notificationData", notificationData);
ctx.sendBroadcast(i);
}Example 46
| Project: MaterialQQLite-master File: GetSignResult.java View source code |
public boolean parse(byte[] bytData) {
try {
reset();
if (bytData == null || bytData.length <= 0)
return false;
String strData = new String(bytData, "UTF-8");
System.out.println(strData);
JSONObject json = new JSONObject(strData);
m_nRetCode = json.optInt("retcode");
JSONArray json2 = json.optJSONArray("result");
json = json2.optJSONObject(0);
m_nQQUin = json.optInt("uin");
m_strSign = json.optString("lnick");
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}Example 47
| Project: MeGov-master File: ComplaintCommentsActivity.java View source code |
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_complaint_comments);
try {
jsonarycomments = new JSONArray(getIntent().getExtras().getString("comments"));
_loadCommentsListview(jsonarycomments);
} catch (JSONException e) {
e.printStackTrace();
}
}Example 48
| Project: MiBandDecompiled-master File: c.java View source code |
public JSONArray a() { JSONArray jsonarray; try { jsonarray = new JSONArray("[{\"app_name\": \"com.example.android_for_test\",\"servers\": [{\"server_name\": \"xiaomi\", \"app_id\": \"Example\"}],\"items\": [{\"id_regex\": \".*\", \"policy\": \"normal\"}]}]"); } catch (JSONException jsonexception) { jsonexception.printStackTrace(); return null; } return jsonarray; }
Example 49
| Project: MIT-Mobile-for-Android-master File: ImageParser.java View source code |
//parsing functions
@Override
public NewsImage parseObject(JSONObject obj) {
NewsImage im = null;
try {
im = new NewsImage();
if (obj.has("description"))
im.setDescription(obj.getString("description"));
if (obj.has("credits"))
im.setCredits(obj.getString("credits"));
ArrayList<NewsImageRepresentation> reps = null;
JSONArray ar = obj.getJSONArray("representations");
if (ar != null) {
ImageRepresentationParser irDS = new ImageRepresentationParser();
reps = irDS.parseObjectArray(ar);
}
im.setRepresentations(reps);
} catch (JSONException e) {
e.printStackTrace();
im = null;
}
return im;
}Example 50
| Project: murex-coding-dojo-master File: BooksJsonParser.java View source code |
public static List<Book> parseJsonStringIntoBooksList(String jsonString) {
ArrayList<Book> booksListFromJson = new ArrayList<Book>();
try {
JSONObject jsonStringAsObject = new JSONObject(jsonString);
JSONArray itemsJsonArray = jsonStringAsObject.getJSONArray("items");
for (int i = 0; i < itemsJsonArray.length(); i++) {
JSONObject volumeInfoObject = itemsJsonArray.getJSONObject(i).getJSONObject("volumeInfo");
String bookTitle = volumeInfoObject.getString("title");
JSONObject imageLinksObject = volumeInfoObject.getJSONObject("imageLinks");
String imageUrl = imageLinksObject.getString("thumbnail");
Book book = new Book(bookTitle, imageUrl);
booksListFromJson.add(book);
}
} catch (JSONException ex) {
Log.d("JSON Exception", ex.getMessage());
}
return booksListFromJson;
}Example 51
| Project: Paperwork-Android-master File: TagSync.java View source code |
public static List<Tag> parseTags(String jsonStr) throws JSONException {
List<Tag> tags = new ArrayList<>();
JSONObject jsonData = new JSONObject(jsonStr);
JSONArray jsonTags = jsonData.getJSONArray("response");
for (int i = 0; i < jsonTags.length(); i++) {
JSONObject tagJson = jsonTags.getJSONObject(i);
String id = tagJson.getString("id");
String title = tagJson.getString("title");
Tag tag = new Tag(id);
tag.setTitle(title);
tags.add(tag);
}
return tags;
}Example 52
| Project: player-sdk-native-android-master File: KProxyConfig.java View source code |
public JSONObject toJson() {
if (!mFilters.isEmpty()) {
try {
JSONObject obj = new JSONObject();
JSONObject flavorAssets = new JSONObject();
JSONObject filters = new JSONObject();
JSONObject include = new JSONObject();
JSONArray formats = new JSONArray();
for (String filter : mFilters) {
formats.put(filter);
}
include.put("Format", formats);
filters.put("include", include);
flavorAssets.put("filters", filters);
obj.put("flavorassets", flavorAssets);
return obj;
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}Example 53
| Project: playground-master File: BookHttp.java View source code |
public static List<Book> getEditoraFromJson(String json) throws JSONException {
List<Book> books = new ArrayList<>();
Gson gson = new Gson();
JSONObject jsonResult = new JSONObject(json);
JSONArray jsonItems = jsonResult.getJSONArray("items");
for (int i = 0; i < jsonItems.length(); i++) {
JSONObject jsonBook = jsonItems.getJSONObject(i);
JSONObject jsonVolumeInfo = jsonBook.getJSONObject("volumeInfo");
Book book = gson.fromJson(jsonVolumeInfo.toString(), Book.class);
books.add(book);
}
return books;
}Example 54
| Project: QuleZhihuRead-master File: ReadResponseMsg.java View source code |
public void deserialize(String jsonStr) {
try {
JSONArray result = new JSONArray(jsonStr);
int length = result.length();
for (int i = 0; i < length; i++) {
Read tempRead = new Read((JSONArray) result.get(i));
reads.add(tempRead.getRead());
}
} catch (JSONException e) {
Log.e(TAG, "- deserialize Error - " + e);
}
}Example 55
| Project: sciencetoolkit-master File: RemoteJsonAction.java View source code |
public final void result(int request, String result) {
JSONObject jobj = null;
JSONArray jarray = null;
try {
jobj = new JSONObject(result);
} catch (JSONException ignored) {
}
try {
jarray = new JSONArray(result);
} catch (JSONException ignored) {
}
if (jobj == null && jarray == null) {
Log.e("stk remote", result);
this.error(request, "There was a problem connecting to the server.");
} else {
this.result(request, jobj, jarray);
}
}Example 56
| Project: SecurityShepherd-master File: GetJson.java View source code |
public static JSONArray getJssonArrayFromPost(BufferedReader reader) { StringBuffer jb = new StringBuffer(); String line = null; //Buffer entire JSON array try { while ((line = reader.readLine()) != null) jb.append(line); } catch (Exception e) { log.error("Unable to buffer JSON array from request."); } try { JSONArray jsonArray = new JSONArray(jb.toString()); return jsonArray; } catch (Exception e) { log.error("Unable to Extract or Parse JSONObject from JSON Buffer"); } return null; }
Example 57
| Project: simple_weather-master File: CityJsonUtils.java View source code |
public List<CityModel> readJson(String jsonStr) throws Exception {
if (TextUtils.isEmpty(jsonStr))
return null;
jsonStr = toJson(jsonStr);
JSONArray array = new JSONArray(jsonStr);
for (int i = 0; i < array.length(); i++) {
JSONArray ja = array.getJSONArray(i);
CityModel model = new CityModel();
model.setCityId(ja.getString(1));
model.setCityName(ja.getString(0));
models.add(model);
}
return models;
}Example 58
| Project: smartly-master File: BeanUtilsTest.java View source code |
// ------------------------------------------------------------------------
// p r i v a t e
// ------------------------------------------------------------------------
@Test
public void testGetValueIfAny() throws Exception {
JSONArray array = new JSONArray();
array.put("test");
array.put("foo");
Object result = BeanUtils.getValueIfAny(array, "test");
assertNotNull(result);
result = BeanUtils.getValueIfAny(array, "undefined");
assertNull(result);
JSONObject json = new JSONObject();
json.putOpt("test", "hello");
result = BeanUtils.getValueIfAny(json, "test");
assertEquals("hello", result);
}Example 59
| Project: tekapp-master File: AppVersion.java View source code |
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
try {
if (action.equals("getVersionNumber")) {
PackageManager packageManager = this.cordova.getActivity().getPackageManager();
callbackContext.success(packageManager.getPackageInfo(this.cordova.getActivity().getPackageName(), 0).versionName);
return true;
}
if (action.equals("getVersionCode")) {
PackageManager packageManager = this.cordova.getActivity().getPackageManager();
callbackContext.success(packageManager.getPackageInfo(this.cordova.getActivity().getPackageName(), 0).versionCode);
return true;
}
return false;
} catch (NameNotFoundException e) {
callbackContext.success("N/A");
return true;
}
}Example 60
| Project: TMinus-master File: WikiImageHandler.java View source code |
public static String processImage(final JSONObject response) {
String rocketThumbnailUrl = null;
Log.d(TAG, "Received wiki IMAGE data, parsing...");
if (response != null) {
try {
JSONObject parse = response.getJSONObject("query");
JSONArray pageIdsArray = parse.getJSONArray("pageids");
if (pageIdsArray.length() == 1) {
final String pageId = pageIdsArray.getString(0);
JSONObject pages = parse.getJSONObject("pages");
JSONObject rocketPage = pages.getJSONObject(pageId);
JSONObject rocketThumbnail = rocketPage.getJSONObject("thumbnail");
rocketThumbnailUrl = rocketThumbnail.getString("source");
}
} catch (final JSONException e) {
Log.d(TAG, "No Wiki image found");
rocketThumbnailUrl = null;
}
}
return rocketThumbnailUrl;
}Example 61
| Project: traffic-balance-master File: JSONMessageComposer.java View source code |
@Override
public String composeLocationDataMessage(List<Location> locations) {
JSONArray array = new JSONArray();
try {
for (Location loc : locations) {
JSONObject object = new JSONObject();
object.put("lon", loc.getLongitude());
object.put("lat", loc.getLatitude());
object.put("time", loc.getTime());
object.put("speed", loc.getSpeed());
object.put("acc", loc.getAccuracy());
object.put("course", loc.getBearing());
array.put(object);
}
} catch (JSONException e) {
Log.e("JSONComposer", e.toString());
}
return array.toString();
}Example 62
| Project: uberpay-wallet-master File: ResultMessage.java View source code |
public JSONArray getResult() { if (has("result")) { if (opt("result") instanceof JSONArray) { try { return getJSONArray("result"); } catch (JSONException e) { throw new RuntimeException(e); } } else { JSONArray result = new JSONArray(); try { result.put(get("result")); } catch (JSONException e) { throw new RuntimeException(e); } return result; } } else { return new JSONArray(); } }
Example 63
| Project: wsandroid-master File: FeedbackJsonParser.java View source code |
public ArrayList<Feedback> getFeedback() {
ArrayList<Feedback> feedback = new ArrayList<Feedback>();
try {
JSONArray recommendations = mJSONObj.getJSONArray("recommendations");
for (int i = 0; i < recommendations.length(); i++) {
JSONObject recommendation = recommendations.getJSONObject(i);
feedback.add(Feedback.CREATOR.parse(recommendation.getJSONObject("recommendation")));
}
} catch (Exception e) {
throw new HttpException(e);
}
return feedback;
}Example 64
| Project: yibo-library-master File: FanfouIDsAdaptor.java View source code |
public static List<String> createIdsList(String jsonString) throws LibException {
try {
if ("[]".equals(jsonString) || "{}".equals(jsonString)) {
return new ArrayList<String>(0);
}
JSONArray idsJsonArray = new JSONArray(jsonString);
int size = idsJsonArray.length();
List<String> ids = new ArrayList<String>(size);
for (int i = 0; i < size; i++) {
ids.add(idsJsonArray.getString(i));
}
return ids;
} catch (JSONException e) {
throw new LibException(ExceptionCode.JSON_PARSE_ERROR, e);
}
}Example 65
| Project: YiBo-master File: FanfouIDsAdaptor.java View source code |
public static List<String> createIdsList(String jsonString) throws LibException {
try {
if ("[]".equals(jsonString) || "{}".equals(jsonString)) {
return new ArrayList<String>(0);
}
JSONArray idsJsonArray = new JSONArray(jsonString);
int size = idsJsonArray.length();
List<String> ids = new ArrayList<String>(size);
for (int i = 0; i < size; i++) {
ids.add(idsJsonArray.getString(i));
}
return ids;
} catch (JSONException e) {
throw new LibException(LibResultCode.JSON_PARSE_ERROR, e);
}
}Example 66
| Project: Yts-master File: GData.java View source code |
public static ArrayList<VideoItem> getGData(String url) {
ArrayList<VideoItem> result = new ArrayList<VideoItem>();
try {
String jsonData = Utils.doZIPHttp(url);
JSONObject jsonObj = new JSONObject(jsonData);
JSONArray itemsArr = jsonObj.getJSONArray("items");
for (int i = 0; i < itemsArr.length(); i++) {
VideoItem vItem = new VideoItem();
JSONObject item = itemsArr.getJSONObject(i);
JSONObject id = item.getJSONObject("id");
vItem.setVideoId(id.getString("videoId"));
JSONObject snippet = item.getJSONObject("snippet");
vItem.setTitle(snippet.getString("title"));
vItem.setIconUrl(snippet.getJSONObject("thumbnails").getJSONObject("medium").getString("url"));
result.add(vItem);
}
} catch (Exception e) {
}
return result;
}Example 67
| Project: ytsdk-master File: GData.java View source code |
public static ArrayList<VideoItem> getGData(String url) {
ArrayList<VideoItem> result = new ArrayList<VideoItem>();
try {
String jsonData = Utils.doZIPHttp(url);
JSONObject jsonObj = new JSONObject(jsonData);
JSONArray itemsArr = jsonObj.getJSONArray("items");
for (int i = 0; i < itemsArr.length(); i++) {
VideoItem vItem = new VideoItem();
JSONObject item = itemsArr.getJSONObject(i);
JSONObject id = item.getJSONObject("id");
vItem.setVideoId(id.getString("videoId"));
JSONObject snippet = item.getJSONObject("snippet");
vItem.setTitle(snippet.getString("title"));
vItem.setIconUrl(snippet.getJSONObject("thumbnails").getJSONObject("medium").getString("url"));
result.add(vItem);
}
} catch (Exception e) {
}
return result;
}Example 68
| Project: zhong-master File: RingUtil.java View source code |
// TODO since it is all run on UI thread, we can use a buffer List
public static List getJsonArrayFromUrl(String url, long expire) {
JSONArray entries = Util.getJsonArrayFromUrl(url, expire);
if (entries != null && entries.length() > 0) {
int len = entries.length();
List list = new ArrayList(len);
for (int i = 0; i < len; i++) {
try {
JSONObject o = entries.getJSONObject(i);
if (o != null)
list.add(o);
} catch (JSONException e) {
}
}
return list;
}
return null;
}Example 69
| Project: android-http-lib-based-on-volley-master File: JsonArrayRequest.java View source code |
@Override public Response<JSONArray> parseNetworkResponse(NetworkResponse response) { try { String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); return Response.success(new JSONArray(jsonString), HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new HttpErrorCollection.ParseError(e)); } catch (JSONException je) { return Response.error(new HttpErrorCollection.ParseError(je)); } }
Example 70
| Project: appinventor-sources-master File: ServerJsonParser.java View source code |
@Override
public JSONValue parse(String source) {
if (source.isEmpty()) {
return null;
}
try {
switch(source.charAt(0)) {
default:
throw new IllegalArgumentException();
case '{':
return new ServerJsonObject(new org.json.JSONObject(source));
case '[':
return new ServerJsonArray(new org.json.JSONArray(source));
}
} catch (JSONException e) {
throw new AssertionError(e);
}
}Example 71
| Project: AppJone-master File: JsonArrayRequest.java View source code |
@Override protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) { try { String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); return Response.success(new JSONArray(jsonString), HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } catch (JSONException je) { return Response.error(new ParseError(je)); } }
Example 72
| Project: Dreamer-master File: JsonArrayRequest.java View source code |
@Override protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) { try { String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); return Response.success(new JSONArray(jsonString), HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } catch (JSONException je) { return Response.error(new ParseError(je)); } }
Example 73
| Project: foursquared-dz-master File: GroupParser.java View source code |
/**
* When we encounter a JSONObject in a GroupParser, we expect one attribute
* named 'type', and then another JSONArray attribute.
*/
public Group<FoursquareType> parse(JSONObject json) throws JSONException {
Group<FoursquareType> group = new Group<FoursquareType>();
Iterator<String> it = (Iterator<String>) json.keys();
while (it.hasNext()) {
String key = it.next();
if (key.equals("type")) {
group.setType(json.getString(key));
} else {
Object obj = json.get(key);
if (obj instanceof JSONArray) {
parse(group, (JSONArray) obj);
} else {
throw new JSONException("Could not parse data.");
}
}
}
return group;
}Example 74
| Project: JSONassert-master File: JSONParser.java View source code |
/**
* Takes a JSON string and returns either a {@link org.json.JSONObject} or {@link org.json.JSONArray},
* depending on whether the string represents an object or an array.
*
* @param s Raw JSON string to be parsed
* @return JSONObject or JSONArray
* @throws JSONException JSON parsing error
*/
public static Object parseJSON(final String s) throws JSONException {
if (s.trim().startsWith("{")) {
return new JSONObject(s);
} else if (s.trim().startsWith("[")) {
return new JSONArray(s);
} else if (s.trim().startsWith("\"") || s.trim().matches(NUMBER_REGEX)) {
return new JSONString() {
@Override
public String toJSONString() {
return s;
}
};
}
throw new JSONException("Unparsable JSON string: " + s);
}Example 75
| Project: mobilevideo-master File: JsonArrayRequest.java View source code |
@Override protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) { try { String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); return Response.success(new JSONArray(jsonString), HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } catch (JSONException je) { return Response.error(new ParseError(je)); } }
Example 76
| Project: MyCC98-master File: JsonArrayRequest.java View source code |
@Override protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) { try { String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); return Response.success(new JSONArray(jsonString), HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } catch (JSONException je) { return Response.error(new ParseError(je)); } }
Example 77
| Project: okulus-master File: JsonArrayRequest.java View source code |
@Override protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) { try { String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); return Response.success(new JSONArray(jsonString), HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } catch (JSONException je) { return Response.error(new ParseError(je)); } }
Example 78
| Project: phonegap-essencial-master File: MacAddressPlugin.java View source code |
/*
* (non-Javadoc)
*
* @see org.apache.cordova.api.Plugin#execute(java.lang.String,
* org.json.JSONArray, java.lang.String)
*/
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
if (action.equals("getMacAddress")) {
String macAddress = this.getMacAddress();
if (macAddress != null) {
JSONObject JSONresult = new JSONObject();
try {
JSONresult.put("mac", macAddress);
PluginResult r = new PluginResult(PluginResult.Status.OK, JSONresult);
callbackContext.success(macAddress);
r.setKeepCallback(true);
callbackContext.sendPluginResult(r);
return true;
} catch (JSONException jsonEx) {
PluginResult r = new PluginResult(PluginResult.Status.JSON_EXCEPTION);
callbackContext.error("error");
r.setKeepCallback(true);
callbackContext.sendPluginResult(r);
return true;
}
}
}
return false;
}Example 79
| Project: QsbkApp-master File: JsonArrayRequest.java View source code |
@Override protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) { try { String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); return Response.success(new JSONArray(jsonString), HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } catch (JSONException je) { return Response.error(new ParseError(je)); } }
Example 80
| Project: TNetwork-master File: JsonArrayRequest.java View source code |
@Override protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) { try { String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); return Response.success(new JSONArray(jsonString), HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } catch (JSONException je) { return Response.error(new ParseError(je)); } }
Example 81
| Project: trending-round-android-master File: JsonArrayRequest.java View source code |
@Override protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) { try { String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); return Response.success(new JSONArray(jsonString), HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } catch (JSONException je) { return Response.error(new ParseError(je)); } }
Example 82
| Project: neembuunow-master File: HttpResponse.java View source code |
/* Error */ public JSONArray asJSONArray() throws twitter4j.TwitterException { // Byte code: // 0: aload_0 // 1: getfield 43 twitter4j/internal/http/HttpResponse:jsonArray Ltwitter4j/internal/org/json/JSONArray; // 4: ifnonnull +74 -> 78 // 7: aconst_null // 8: astore_1 // 9: aload_0 // 10: getfield 37 twitter4j/internal/http/HttpResponse:responseAsString Ljava/lang/String; // 13: ifnonnull +70 -> 83 // 16: aload_0 // 17: invokevirtual 70 twitter4j/internal/http/HttpResponse:asReader ()Ljava/io/Reader; // 20: astore_1 // 21: aload_0 // 22: new 72 twitter4j/internal/org/json/JSONArray // 25: dup // 26: new 74 twitter4j/internal/org/json/JSONTokener // 29: dup // 30: aload_1 // 31: invokespecial 77 twitter4j/internal/org/json/JSONTokener:<init> (Ljava/io/Reader;)V // 34: invokespecial 80 twitter4j/internal/org/json/JSONArray:<init> (Ltwitter4j/internal/org/json/JSONTokener;)V // 37: putfield 43 twitter4j/internal/http/HttpResponse:jsonArray Ltwitter4j/internal/org/json/JSONArray; // 40: aload_0 // 41: getfield 51 twitter4j/internal/http/HttpResponse:CONF Ltwitter4j/internal/http/HttpClientConfiguration; // 44: invokeinterface 86 1 0 // 49: ifeq +118 -> 167 // 52: getstatic 32 twitter4j/internal/http/HttpResponse:logger Ltwitter4j/internal/logging/Logger; // 55: aload_0 // 56: getfield 43 twitter4j/internal/http/HttpResponse:jsonArray Ltwitter4j/internal/org/json/JSONArray; // 59: iconst_1 // 60: invokevirtual 90 twitter4j/internal/org/json/JSONArray:toString (I)Ljava/lang/String; // 63: invokevirtual 94 twitter4j/internal/logging/Logger:debug (Ljava/lang/String;)V // 66: aload_1 // 67: ifnull +7 -> 74 // 70: aload_1 // 71: invokevirtual 99 java/io/Reader:close ()V // 74: aload_0 // 75: invokespecial 101 twitter4j/internal/http/HttpResponse:disconnectForcibly ()V // 78: aload_0 // 79: getfield 43 twitter4j/internal/http/HttpResponse:jsonArray Ltwitter4j/internal/org/json/JSONArray; // 82: areturn // 83: aload_0 // 84: new 72 twitter4j/internal/org/json/JSONArray // 87: dup // 88: aload_0 // 89: getfield 37 twitter4j/internal/http/HttpResponse:responseAsString Ljava/lang/String; // 92: invokespecial 103 twitter4j/internal/org/json/JSONArray:<init> (Ljava/lang/String;)V // 95: putfield 43 twitter4j/internal/http/HttpResponse:jsonArray Ltwitter4j/internal/org/json/JSONArray; // 98: goto -58 -> 40 // 101: astore 4 // 103: getstatic 32 twitter4j/internal/http/HttpResponse:logger Ltwitter4j/internal/logging/Logger; // 106: invokevirtual 106 twitter4j/internal/logging/Logger:isDebugEnabled ()Z // 109: ifeq +102 -> 211 // 112: new 62 twitter4j/TwitterException // 115: dup // 116: new 108 java/lang/StringBuilder // 119: dup // 120: invokespecial 109 java/lang/StringBuilder:<init> ()V // 123: aload 4 // 125: invokevirtual 113 twitter4j/internal/org/json/JSONException:getMessage ()Ljava/lang/String; // 128: invokevirtual 117 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder; // 131: ldc 119 // 133: invokevirtual 117 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder; // 136: aload_0 // 137: getfield 37 twitter4j/internal/http/HttpResponse:responseAsString Ljava/lang/String; // 140: invokevirtual 117 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder; // 143: invokevirtual 121 java/lang/StringBuilder:toString ()Ljava/lang/String; // 146: aload 4 // 148: invokespecial 124 twitter4j/TwitterException:<init> (Ljava/lang/String;Ljava/lang/Throwable;)V // 151: athrow // 152: astore_2 // 153: aload_1 // 154: ifnull +7 -> 161 // 157: aload_1 // 158: invokevirtual 99 java/io/Reader:close ()V // 161: aload_0 // 162: invokespecial 101 twitter4j/internal/http/HttpResponse:disconnectForcibly ()V // 165: aload_2 // 166: athrow // 167: getstatic 32 twitter4j/internal/http/HttpResponse:logger Ltwitter4j/internal/logging/Logger; // 170: astore 5 // 172: aload_0 // 173: getfield 37 twitter4j/internal/http/HttpResponse:responseAsString Ljava/lang/String; // 176: ifnull +19 -> 195 // 179: aload_0 // 180: getfield 37 twitter4j/internal/http/HttpResponse:responseAsString Ljava/lang/String; // 183: astore 7 // 185: aload 5 // 187: aload 7 // 189: invokevirtual 94 twitter4j/internal/logging/Logger:debug (Ljava/lang/String;)V // 192: goto -126 -> 66 // 195: aload_0 // 196: getfield 43 twitter4j/internal/http/HttpResponse:jsonArray Ltwitter4j/internal/org/json/JSONArray; // 199: invokevirtual 125 twitter4j/internal/org/json/JSONArray:toString ()Ljava/lang/String; // 202: astore 6 // 204: aload 6 // 206: astore 7 // 208: goto -23 -> 185 // 211: new 62 twitter4j/TwitterException // 214: dup // 215: aload 4 // 217: invokevirtual 113 twitter4j/internal/org/json/JSONException:getMessage ()Ljava/lang/String; // 220: aload 4 // 222: invokespecial 124 twitter4j/TwitterException:<init> (Ljava/lang/String;Ljava/lang/Throwable;)V // 225: athrow // 226: astore 8 // 228: goto -154 -> 74 // 231: astore_3 // 232: goto -71 -> 161 // Local variable table: // start length slot name signature // 0 235 0 this HttpResponse // 8 150 1 localReader Reader // 152 14 2 localObject1 Object // 231 1 3 localIOException1 IOException // 101 120 4 localJSONException twitter4j.internal.org.json.JSONException // 170 16 5 localLogger Logger // 202 3 6 str String // 183 24 7 localObject2 Object // 226 1 8 localIOException2 IOException // Exception table: // from to target type // 9 66 101 twitter4j/internal/org/json/JSONException // 83 98 101 twitter4j/internal/org/json/JSONException // 167 204 101 twitter4j/internal/org/json/JSONException // 9 66 152 finally // 83 98 152 finally // 103 152 152 finally // 167 204 152 finally // 211 226 152 finally // 70 74 226 java/io/IOException // 157 161 231 java/io/IOException }
Example 83
| Project: seqware-master File: SampleHierarchyResource.java View source code |
@Override
public void handle(Request request, Response response) {
authenticate(request.getChallengeResponse().getIdentifier());
if (request.getMethod().compareTo(Method.GET) == 0) {
List<SampleHierarchy> shs;
try {
shs = DBAccess.get().executeQuery("select sample_id, parent_id from sample_hierarchy", new ResultSetHandler<List<SampleHierarchy>>() {
@Override
public List<SampleHierarchy> handle(ResultSet rs) throws SQLException {
List<SampleHierarchy> shs = new ArrayList<>();
while (rs.next()) {
SampleHierarchy sh = new SampleHierarchy();
sh.setSampleId(rs.getInt("sample_id"));
if (null == rs.getString("parent_id")) {
sh.setParentId(-1);
} else {
sh.setParentId(rs.getInt("parent_id"));
}
shs.add(sh);
}
return shs;
}
});
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
DBAccess.close();
}
SampleHierarchies ret = new SampleHierarchies();
ret.setSampleHierarchies(shs);
Representation rep = new JsonRepresentation(ret);
response.setEntity(rep);
} else if (request.getMethod().compareTo(Method.PUT) == 0) {
Representation entity = request.getEntity();
try {
JsonRepresentation represent = new JsonRepresentation(entity);
JSONObject obj = represent.getJsonObject();
org.json.JSONArray array = (org.json.JSONArray) obj.get("sampleHierarchies");
String insertSql = this.jsonArrayToSql(array);
// delete all rows in db, then insert them again
String deleteAll = "delete from sample_hierarchy";
DBAccess.get().executeUpdate(deleteAll);
DBAccess.get().executeUpdate(insertSql);
} catch (IOExceptionJSONException | SQLException | ex) {
Logger.getLogger(SampleHierarchyResource.class.getName()).log(Level.SEVERE, null, ex);
} finally {
DBAccess.close();
}
}
}Example 84
| Project: aceim-master File: VkChat.java View source code |
public long[] getUsers() {
try {
JSONArray arr = getJSONObject().optJSONArray("users");
long[] result = new long[arr.length()];
for (int i = 0; i < arr.length(); i++) {
try {
result[i] = arr.getLong(i);
} catch (JSONException e) {
Logger.log(e);
}
}
return result;
} catch (Exception e) {
Logger.log(e);
}
return new long[0];
}Example 85
| Project: AirPlayer-master File: FetchArtistPictureActivity.java View source code |
@Override
public ArrayList<Picture> onDecodeJson(String response) {
ArrayList<Picture> list = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray musicArray = jsonObject.getJSONArray("data");
for (int i = 0; i < musicArray.length() - 1; i++) {
JSONObject musicObject = musicArray.getJSONObject(i);
String objUrl = musicObject.getString("objURL");
String thumbUrl = musicObject.getString("thumbURL");
Picture picture = new Picture(thumbUrl, objUrl);
list.add(picture);
}
return list;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}Example 86
| Project: Android-Carbon-Forum-master File: JSONUtil.java View source code |
// JSONå—符串转List
public static List<Map<String, Object>> jsonObject2List(JSONObject jsonObject, String keyName) {
List<Map<String, Object>> list = new ArrayList<>();
if (null != jsonObject) {
try {
JSONArray jsonArray = jsonObject.getJSONArray(keyName);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject2 = jsonArray.getJSONObject(i);
Map<String, Object> map = new HashMap<>();
Iterator<String> iterator = jsonObject2.keys();
while (iterator.hasNext()) {
String key = iterator.next();
Object value = jsonObject2.get(key);
map.put(key, value);
}
list.add(map);
}
return list;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
} else {
return null;
}
}Example 87
| Project: android-discourse-master File: CustomField.java View source code |
@Override
public void load(JSONObject object) throws JSONException {
super.load(object);
name = getString(object, "name");
required = !object.getBoolean("allow_blank");
predefinedValues = new ArrayList<String>();
if (object.has("possible_values")) {
JSONArray values = object.getJSONArray("possible_values");
for (int i = 0; i < values.length(); i++) {
JSONObject value = values.getJSONObject(i);
predefinedValues.add(getString(value, "value"));
}
}
}Example 88
| Project: android-reddit-master File: ListingFactory.java View source code |
public Listing<T> createThing() throws ThingFactoryException {
Listing<T> listing = new Listing<T>();
List<T> children = new ArrayList<T>();
try {
JSONObject data = json.getJSONObject("data");
JSONArray jsonChildren = data.getJSONArray("children");
for (int i = 0; i < jsonChildren.length(); i++) {
JsonToThingConverter<T> converter = new JsonToThingConverter<T>();
T thing = converter.convert(jsonChildren.getJSONObject(i));
children.add(thing);
}
listing.setChildren(children);
listing.setAfter(data.getString("after"));
listing.setBefore(data.getString("before"));
} catch (JSONException e) {
throw new ThingFactoryException("Failed parsing JSON object into Thing.", e);
}
return listing;
}Example 89
| Project: android-socket.io-demo-master File: HasBinary.java View source code |
private static boolean _hasBinary(Object obj) {
if (obj == null)
return false;
if (obj instanceof byte[]) {
return true;
}
if (obj instanceof JSONArray) {
JSONArray _obj = (JSONArray) obj;
int length = _obj.length();
for (int i = 0; i < length; i++) {
Object v;
try {
v = _obj.isNull(i) ? null : _obj.get(i);
} catch (JSONException e) {
return false;
}
if (_hasBinary(v)) {
return true;
}
}
} else if (obj instanceof JSONObject) {
JSONObject _obj = (JSONObject) obj;
Iterator keys = _obj.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
Object v;
try {
v = _obj.get(key);
} catch (JSONException e) {
return false;
}
if (_hasBinary(v)) {
return true;
}
}
}
return false;
}Example 90
| Project: Android-Wallet-2-App-master File: Status.java View source code |
/**
* Parse the data supplied to this instance.
*
*/
public void parse() {
try {
JSONObject jsonObject = new JSONObject(strData);
if (jsonObject != null) {
isMaintenance = jsonObject.getBoolean("maintenance");
}
JSONArray servers = jsonObject.getJSONArray("bitcoind_servers");
if (servers != null) {
nbServers = servers.length();
}
} catch (JSONException je) {
;
}
}Example 91
| Project: AndroidAsync-master File: EventEmitter.java View source code |
void onEvent(String event, JSONArray arguments, Acknowledge acknowledge) {
List<EventCallback> list = callbacks.get(event);
if (list == null)
return;
Iterator<EventCallback> iter = list.iterator();
while (iter.hasNext()) {
EventCallback cb = iter.next();
cb.onEvent(arguments, acknowledge);
if (cb instanceof OnceCallback)
iter.remove();
}
}Example 92
| Project: AndroidFunctionalTester-master File: ScenarioTestCase.java View source code |
public JSONObject toJson() {
JSONObject jsonObject = new JSONObject();
try {
// Mandatory
jsonObject.put("name", name);
jsonObject.put("status", status);
// Optional
if (duration > 0) {
jsonObject.put("duration", duration);
}
if (message != null) {
jsonObject.put("message", message);
}
//}
if (!actionTestCases.isEmpty()) {
JSONArray actions = new JSONArray();
for (ActionTestCase action : actionTestCases) {
actions.put(action.toJson());
}
jsonObject.put("actions", actions);
}
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}Example 93
| Project: androidperformance-master File: Ipdv.java View source code |
public JSONObject toJSON() {
// TODO Auto-generated method stub
JSONObject obj = new JSONObject();
try {
JSONArray array = new JSONArray();
for (IpdvUnit entry : ipdvlist) {
array.put(entry.toJSON());
}
obj.put("ipdvlist", array);
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}Example 94
| Project: AndroidPirataEs-master File: CtrlJson.java View source code |
public SortedSet<StrRss> getRSS() {
SortedSet<StrRss> ssRss = new TreeSet<StrRss>(new MyComparator_pubDate());
try {
String content = CtrlFile.getInstance().readFile("rss");
JSONObject json = new JSONObject(content);
JSONArray entry = json.toJSONArray(json.names());
for (int i = 0; i < entry.length(); i++) {
StrRss rss = new StrRss();
rss.id = entry.getJSONObject(i).getInt("id");
rss.link = entry.getJSONObject(i).getString("link");
rss.pubDate = entry.getJSONObject(i).getString("pubDate");
rss.title = entry.getJSONObject(i).getString("title");
ssRss.add(rss);
}
} catch (JSONException e) {
e.printStackTrace();
}
return ssRss;
}Example 95
| Project: AndroidSDK-RecipeBook-master File: Recipe023.java View source code |
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String json = "";
json += "{\"recipe\": {";
json += " \"people\": [";
json += " {\"id\": \"1\", \"name\": \"gabu\"},";
json += " {\"id\": \"2\", \"name\": \"hoge\"},";
json += " {\"id\": \"3\", \"name\": \"fuga\"}";
json += "]}}";
try {
JSONObject jObject = new JSONObject(json);
JSONObject recipe = jObject.getJSONObject("recipe");
JSONArray people = recipe.getJSONArray("people");
for (int i = 0; i < people.length(); i++) {
JSONObject person = people.getJSONObject(i);
int id = person.getInt("id");
String name = person.getString("name");
Log.d(TAG, "id=" + id + ", name=" + name);
}
} catch (JSONException e) {
e.printStackTrace();
}
}Example 96
| Project: Android_App_OpenSource-master File: PlaylistFunctions.java View source code |
public static PlaylistRemote[] getPlaylists(JSONArray jsonArrayReviews) throws JSONException {
int n = jsonArrayReviews.length();
PlaylistRemote[] playlists = new PlaylistRemote[n];
PlaylistBuilder playlistBuilder = new PlaylistBuilder();
for (int i = 0; i < n; i++) {
playlists[i] = playlistBuilder.build(jsonArrayReviews.getJSONObject(i));
}
return playlists;
}Example 97
| Project: android_news_app-master File: NewsList.java View source code |
public static NewsList parse(String jsonString) {
if (TextUtils.isEmpty(jsonString)) {
return null;
}
NewsList newsList = new NewsList();
try {
JSONObject jsonObject = new JSONObject(jsonString);
newsList.success = jsonObject.optBoolean("success");
if (newsList.success) {
JSONArray jsonArray = jsonObject.getJSONArray("yi18");
if (jsonArray != null && jsonArray.length() > 0) {
newsList.newsList = new ArrayList<News>(jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
newsList.newsList.add(News.parse(jsonArray.getJSONObject(i)));
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return newsList;
}Example 98
| Project: appcan-android-master File: DataHelper.java View source code |
/**
* 转��适�阅读的Json
*/
public static String toPrettyJson(String json) {
try {
json = json.trim();
if (json.startsWith("{")) {
JSONObject jsonObject = new JSONObject(json);
return jsonObject.toString(4);
}
if (json.startsWith("[")) {
JSONArray jsonArray = new JSONArray(json);
return jsonArray.toString(4);
}
} catch (JSONException e) {
if (BDebug.DEBUG) {
e.printStackTrace();
}
}
return json;
}Example 99
| Project: apps-android-wikipedia-master File: PageInfoUnmarshaller.java View source code |
private static DisambigResult[] parseDisambigJson(WikiSite wiki, JSONArray array) throws JSONException {
if (array == null) {
return null;
}
DisambigResult[] stringArray = new DisambigResult[array.length()];
for (int i = 0; i < array.length(); i++) {
stringArray[i] = new DisambigResult(wiki.titleForInternalLink(decodeURL(array.getString(i))));
}
return stringArray;
}Example 100
| Project: APS-master File: BroadcastMbgs.java View source code |
public void handleNewMbg(JSONArray mbgs, Context context, boolean isDelta) {
Bundle bundle = new Bundle();
bundle.putString("mbgs", mbgs.toString());
bundle.putBoolean("delta", isDelta);
Intent intent = new Intent(Intents.ACTION_NEW_MBG);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
List<ResolveInfo> x = context.getPackageManager().queryBroadcastReceivers(intent, 0);
log.debug("MBG " + x.size() + " receivers");
}Example 101
| Project: Arad-master File: JsonLog.java View source code |
public static void printJson(String tag, String msg, String headString) {
String message;
try {
if (msg.startsWith("{")) {
JSONObject jsonObject = new JSONObject(msg);
message = jsonObject.toString(KLog.JSON_INDENT);
} else if (msg.startsWith("[")) {
JSONArray jsonArray = new JSONArray(msg);
message = jsonArray.toString(KLog.JSON_INDENT);
} else {
message = msg;
}
} catch (JSONException e) {
message = msg;
}
Util.printLine(tag, true);
message = headString + KLog.LINE_SEPARATOR + message;
String[] lines = message.split(KLog.LINE_SEPARATOR);
for (String line : lines) {
Log.d(tag, "â•‘ " + line);
}
Util.printLine(tag, false);
}