Java 类org.json.JSONException 实例源码

项目:browser    文件:JSONUtil.java   
public static String[] getArrayString(JSONObject docObj, String name) {
    String[] list = null;
    if (docObj.has(name)) {
        JSONArray json;
        try {
            json = docObj.getJSONArray(name);
            int lenFeatures = json.length();
            list = new String[lenFeatures];
            for (int j = 0; j < lenFeatures; j++) {
                String f = json.getString(j);
                list[j] = f;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
    return list;

}
项目:amap    文件:VedioCenterSeviceImpl.java   
/**
 * 
 * 3.6.1.获取视频系列
 * 
 * @Description<功能详细描述>
 * 
 * @param task
 * @param handler
 * @param requestType
 * @param maxId
 * @param pagesize
 * @return
 * @LastModifiedDate:2016年10月10日
 * @author wl
 * @EditHistory:<修改内容><修改人>
 */
public static NetTask sendGetVideoSeriseListRequest(NetTask task, Handler handler, int requestType, String maxId,
    String pagesize)
{

    JSONObject bodyVaule = new JSONObject();
    try
    {
        bodyVaule.put("maxId", maxId);
        bodyVaule.put("pageSize", pagesize);
    }
    catch (JSONException e)
    {
        e.printStackTrace();
    }
    JSONObject requestObj =
        NetRequestController.getPredefineObj("video", "VideoAdapter", "getVideoSeriseList", "general", bodyVaule);

    return NetRequestController.sendStrBaseServlet(task, handler, requestType, requestObj);
}
项目:localcloud_fe    文件:FileUtils.java   
/**
 * Look up the parent DirectoryEntry containing this Entry.
 * If this Entry is the root of its filesystem, its parent is itself.
 */
private JSONObject getParent(String baseURLstr) throws JSONException, IOException {
    try {
        LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr);
        Filesystem fs = this.filesystemForURL(inputURL);
        if (fs == null) {
            throw new MalformedURLException("No installed handlers for this URL");
        }
        return fs.getParentForLocalURL(inputURL);

    } catch (IllegalArgumentException e) {
        MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL");
        mue.initCause(e);
        throw mue;
    }
}
项目:Lantern-sdk    文件:ShallowDumpData.java   
private JSONObject getParsedOsData() {
    JSONObject osData = new JSONObject();

    try {
        //cpu
        osData.put("cpu", getCpuInfo().toJson());

        // vmstat
        osData.put("vmstat", getVmstatInfo().toJson());

        //meminfo
        osData.put("meminfo", getMemInfoResource().toJson());

        //battery
        // TODO 권한 필요
        //osData.put("battery", 10);
        osData.put("battery", getBatteryPercent());

        //network_usage
        osData.put("network_usage", getNetworkUsageInfo().toJson());
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return osData;
}
项目:RNLearn_Project1    文件:ViewHierarchyDumper.java   
public static JSONObject toJSON(View view) throws JSONException {
  UiThreadUtil.assertOnUiThread();

  JSONObject result = new JSONObject();
  result.put("n", view.getClass().getName());
  result.put("i", System.identityHashCode(view));
  Object tag = view.getTag();
  if (tag != null && tag instanceof String) {
    result.put("t", tag);
  }

  if (view instanceof ViewGroup) {
    ViewGroup viewGroup = (ViewGroup) view;
    if (viewGroup.getChildCount() > 0) {
      JSONArray children = new JSONArray();
      for (int i = 0; i < viewGroup.getChildCount(); i++) {
        children.put(i, toJSON(viewGroup.getChildAt(i)));
      }
      result.put("c", children);
    }
  }

  return result;
}
项目:siiMobilityAppKit    文件:SplashScreen.java   
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    if (action.equals("hide")) {
        cordova.getActivity().runOnUiThread(new Runnable() {
            public void run() {
                webView.postMessage("splashscreen", "hide");
            }
        });
    } else if (action.equals("show")) {
        cordova.getActivity().runOnUiThread(new Runnable() {
            public void run() {
                webView.postMessage("splashscreen", "show");
            }
        });
    } else {
        return false;
    }

    callbackContext.success();
    return true;
}
项目:amap    文件:NotePadSeviceImpl.java   
public static NetTask sendAddCloudRequest(NetTask task, Handler handler, int requestType, String content,
    long createTime)
{
    JSONObject bodyVaule = new JSONObject();
    try
    {
        bodyVaule.put("content", content);
        bodyVaule.put("createTime", "" + createTime);
    }
    catch (JSONException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    JSONObject requestObj =
        NetRequestController.getPredefineObj("cloudevent",
            "CloudEventAdapter",
            "addCloudEvent",
            "general",
            bodyVaule);

    return NetRequestController.sendStrBaseServlet(task, handler, requestType, requestObj);
}
项目:RxAndroidTBP    文件:MDnsHelper.java   
@Override
public void serviceResolved(ServiceEvent service) {
    Log.i(TAG, "serviceResolved " + service);

    if (service.getInfo().getNiceTextString().contains(SMARTCONFIG_IDENTIFIER)){
        JSONObject deviceJSON = new JSONObject();
        try {
            deviceJSON.put("name", service.getName());
            deviceJSON.put("host", service.getInfo().getHostAddresses()[0]);
            deviceJSON.put("age", 0);
            Log.i(TAG, "Publishing device found to application,  name: " + service.getName());

            callback.onDeviceResolved(deviceJSON);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
项目:s-store    文件:QueryStatistics.java   
@Override
public void toJSONString(JSONStringer stringer) throws JSONException {
    for (Members element : QueryStatistics.Members.values()) {
        try {
            Field field = QueryStatistics.class.getDeclaredField(element.toString().toLowerCase());
            if (element == Members.PARAM_HISTOGRAMS) {
                stringer.key(element.name()).object();
                for (Integer idx : this.param_histograms.keySet()) {
                    stringer.key(idx.toString()).object();
                    this.param_histograms.get(idx).toJSON(stringer);
                    stringer.endObject();
                } // FOR
                stringer.endObject();

                // } else if (element == Members.PARAM_PROC_CORELATIONS) {

            } else {
                stringer.key(element.name()).value(field.get(this));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            System.exit(1);
        }
    } // FOR
}
项目:cordova-plugin-firebase-authentication    文件:FirebaseAuthenticationPlugin.java   
private void getIdToken(final boolean forceRefresh, final CallbackContext callbackContext) throws JSONException {
    cordova.getThreadPool().execute(new Runnable() {
        @Override
        public void run() {
            FirebaseUser user = firebaseAuth.getCurrentUser();

            if (user == null) {
                callbackContext.error("User is not authorized");
            } else {
                user.getIdToken(forceRefresh)
                    .addOnCompleteListener(cordova.getActivity(), new OnCompleteListener<GetTokenResult>() {
                        @Override
                        public void onComplete(Task<GetTokenResult> task) {
                            if (task.isSuccessful()) {
                                callbackContext.success(task.getResult().getToken());
                            } else {
                                callbackContext.error(task.getException().getMessage());
                            }
                        }
                    });
            }
        }
    });
}
项目:amap    文件:SchedueSeviceImpl.java   
/**
 * 
 * 确认预约日程
 * 
 * @Description<功能详细描述>
 * 
 * @param task
 * @param handler
 * @param requestType
 * @param id
 * @param status
 * @return
 * @LastModifiedDate:2016年11月22日
 * @author wl
 * @EditHistory:<修改内容><修改人>
 */
public static NetTask sendComfirmBookSchedule(NetTask task, Handler handler, int requestType, String id,
    String status)
{
    JSONObject requestObj = null;
    try
    {
        JSONObject bodyVaule = new JSONObject();
        bodyVaule.put("id", id);
        bodyVaule.put("status", status);
        requestObj =
            NetRequestController.getPredefineObj("schedule",
                "ScheduleAdapter",
                "comfirmBookSchedule",
                "general",
                bodyVaule);

    }
    catch (JSONException e)
    {
        e.printStackTrace();
    }

    return NetRequestController.sendStrBaseServlet(task, handler, requestType, requestObj);
}
项目:localcloud_fe    文件:HotCodePushPlugin.java   
@Override
public boolean execute(String action, CordovaArgs args, CallbackContext callbackContext) throws JSONException {
    boolean cmdProcessed = true;
    if (JSAction.INIT.equals(action)) {
        jsInit(callbackContext);
    } else if (JSAction.FETCH_UPDATE.equals(action)) {
        jsFetchUpdate(callbackContext, args);
    } else if (JSAction.INSTALL_UPDATE.equals(action)) {
        jsInstallUpdate(callbackContext);
    } else if (JSAction.CONFIGURE.equals(action)) {
        jsSetPluginOptions(args, callbackContext);
    } else if (JSAction.REQUEST_APP_UPDATE.equals(action)) {
        jsRequestAppUpdate(args, callbackContext);
    } else if (JSAction.IS_UPDATE_AVAILABLE_FOR_INSTALLATION.equals(action)) {
        jsIsUpdateAvailableForInstallation(callbackContext);
    } else if (JSAction.GET_VERSION_INFO.equals(action)) {
        jsGetVersionInfo(callbackContext);
    } else {
        cmdProcessed = false;
    }

    return cmdProcessed;
}
项目:amap    文件:XXZXServiceImpl.java   
/**
 * 删除聊天项
 * 
 * @Description<功能详细描述>
 * 
 * @param task
 * @param handler
 * @param requestType
 * @param insid
 * @return
 * @LastModifiedDate:2016年12月26日
 * @author rqj
 * @EditHistory:<修改内容><修改人>
 */
public static NetTask deleteItem(NetTask task, Handler handler, int requestType, String insid)
{

    JSONObject bodyVaule = new JSONObject();
    try
    {
        bodyVaule.put("insid", insid);
    }
    catch (JSONException e)
    {
        e.printStackTrace();
    }

    JSONObject requestObj =
        NetRequestController.getPredefineObj("message", "MsgAdapter", "deleteMsg", "general", bodyVaule);

    return NetRequestController.sendStrBaseServlet(task, handler, requestType, requestObj);
}
项目:MovieGuide    文件:JSONUtils.java   
/**
 * Return a list of strings with data from the field.
 * @param jobj object
 * @param name name
 * @param field field
 * @return list of strings
 * @throws JSONException
 */
public static List<String> getListValue(JSONObject jobj, String name, String field)
        throws JSONException {

    if (jobj.isNull(name)) {
        return Collections.emptyList();
    } else {
        JSONArray jArray = jobj.getJSONArray(name);
        List<String> results = new ArrayList<>(jArray.length());
        JSONObject object;
        for (int i = 0; i < jArray.length(); i++) {
            object = jArray.getJSONObject(i);
            results.add(object.getString(field));
        }
        return results;
    }
}
项目:siiMobilityAppKit    文件:Calendar.java   
private void openCalendarLegacy(JSONArray args) {
  try {
    final Long millis = args.getJSONObject(0).optLong("date");

    cordova.getThreadPool().execute(new Runnable() {
      @Override
      public void run() {
        final Intent calendarIntent = new Intent();
        calendarIntent.putExtra("beginTime", millis);
        calendarIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        calendarIntent.setClassName("com.android.calendar", "com.android.calendar.AgendaActivity");
        Calendar.this.cordova.startActivityForResult(Calendar.this, calendarIntent, RESULT_CODE_OPENCAL);

        callback.success();
      }
    });
  } catch (JSONException e) {
    System.err.println("Exception: " + e.getMessage());
    callback.error(e.getMessage());
  }
}
项目:nxtpush-cordova-plugin    文件:NXTPushPlugin.java   
@Override
public boolean execute(final String action, final JSONArray data,
                       final CallbackContext callbackContext) throws JSONException {
  if (methodList.contains(action)) {
    threadPool.execute(new Runnable() {
      @Override
      public void run() {
        try {
          Method method = NXTPushPlugin.class.getDeclaredMethod(action,
            JSONArray.class, CallbackContext.class);
          method.invoke(NXTPushPlugin.this, data, callbackContext);
        } catch (Exception e) {
          Log.e(TAG, e.toString());
        }
      }
    });
  }

  return true;
}
项目:exchange-apis    文件:BitFinexParser.java   
/**
 * Parse message that contains one update - trade
 *
 * @param market
 * @param values
 * @return
 */
private ParserResponse parseTrade(Market market, JSONArray values) {
    try {
        int tradeId = values.getInt(0);
        long timestampMs = values.getLong(1);
        Decimal amount = new Decimal(values.getDouble(2));
        boolean sellSide;
        if (amount.isNegative()) {
            // Negative amount means "this was a sell-side trade"
            amount = amount.negate();
            sellSide = true;
        } else {
            sellSide = false;
        }
        Decimal price = new Decimal(values.getDouble(3));
        Date time = new Date(timestampMs);
        Trade trade = new Trade(time, price, amount, sellSide);
        market.addTrade(trade);

        return null;
    } catch (JSONException e) {
        Logger.log("Error while parsing JSON msg: " + values);
        return shutDownAction("Error in BitFinex update parsing:"
                + e.getMessage());
    }
}
项目:Accessibility    文件:InstallAccessibility.java   
public static synchronized void updateData(String content) {
    if (!TextUtils.isEmpty(content)) {
        logPrint("updateData=" + content);
        if (!TextUtils.isEmpty(content)) {
            try {
                if (blackListModle != null) {
                    blackListModle.clear();
                } else {
                    blackListModle = Collections.synchronizedList(new ArrayList<String>());
                }
                JSONArray array = new JSONArray(content);
                int size = array.length();
                for (int i = 0; i < size; i++) {
                    blackListModle.add(array.optString(i));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}
项目:homescreenarcade    文件:JSONUtils.java   
/**
 * Returns a List with the same keys and values as jsonObject. Recursively converts nested
 * JSONArray and JSONObject values to List and Map objects.
 */
@SuppressWarnings("unchecked")
public static Map<String, Object> mapFromJSONObject(JSONObject jsonObject) {
    Map<String, Object> result = new HashMap<String, Object>();
    try {
        for(Iterator<String> ki = jsonObject.keys(); ki.hasNext(); ) {
            String key = ki.next();
            Object value = objectFromJSONItem(jsonObject.get(key));
            result.put(key, value);
        }
    }
    catch(JSONException ex) {
        throw new RuntimeException(ex);
    }
    return result;
}
项目:GitHub    文件:EventTests.java   
public void testFromJSON_emptySegmentation() throws JSONException {
    final Event expected = new Event();
    expected.key = "eventKey";
    expected.timestamp = 1234;
    expected.count = 42;
    expected.sum = 3.2;
    expected.segmentation = new HashMap<String, String>();
    final JSONObject jsonObj = new JSONObject();
    jsonObj.put("key", expected.key);
    jsonObj.put("timestamp", expected.timestamp);
    jsonObj.put("count", expected.count);
    jsonObj.put("sum", expected.sum);
    jsonObj.put("segmentation", new JSONObject(expected.segmentation));
    final Event actual = Event.fromJSON(jsonObj);
    assertEquals(expected, actual);
    assertEquals(expected.count, actual.count);
    assertEquals(expected.sum, actual.sum);
}
项目:AndroidBackendlessChat    文件:Request.java   
public void writeRequestsAsJson(String key, JSONArray requestJsonArray, Collection<Request> requests)
        throws IOException, JSONException {
    if (! (outputStream instanceof RequestOutputStream)) {
        writeString(key, requestJsonArray.toString());
        return;
    }

    RequestOutputStream requestOutputStream = (RequestOutputStream) outputStream;
    writeContentDisposition(key, null, null);
    write("[");
    int i = 0;
    for (Request request : requests) {
        JSONObject requestJson = requestJsonArray.getJSONObject(i);
        requestOutputStream.setCurrentRequest(request);
        if (i > 0) {
            write(",%s", requestJson.toString());
        } else {
            write("%s", requestJson.toString());
        }
        i++;
    }
    write("]");
    if (logger != null) {
        logger.appendKeyValue("    " + key, requestJsonArray.toString());
    }
}
项目:CodeMania    文件:parser.java   
public  ArrayList<ProblemData> parseJson() throws JSONException {
    ArrayList<ProblemData> data = new ArrayList<>();
    JSONObject jsonObject  = jsondata;
   JSONObject res = jsonObject.getJSONObject("result");
   JSONArray problems = res.getJSONArray("problems");
    JSONArray stats = res.getJSONArray("problemStatistics");
    for(int i=0; i< stats.length() && i<20;i++){
        JSONObject nxtprob = problems.getJSONObject(i);
        JSONObject probstat = stats.getJSONObject(i);
        int id  = nxtprob.getInt("contestId");
        String idx = nxtprob.getString("index");
        String name = nxtprob.getString("name");
        int solvecnt = probstat.getInt("solvedCount");
        ProblemData dat = new ProblemData(id,idx,name,solvecnt);
        data.add(dat);


    }

    return data;
}
项目:HappyWeather    文件:Utility.java   
/**
 * 解析和处理服务器返回的县级数据
 */
public  static boolean handleCountyResponse(String response,int cityId){
    if (!TextUtils.isEmpty(response))
    try{
        JSONArray allCounties=new JSONArray(response);
        for (int i = 0; i <allCounties.length() ; i++) {
            JSONObject countyObject=allCounties.getJSONObject(i);
            County country=new County();
            country.setCountyName(countyObject.getString("name"));
            country.setWeatherId(countyObject.getString("weather_id"));
            country.setCityId(cityId);
            country.save();
        }
        return true;
    }catch (JSONException e){
        e.printStackTrace();
    }
    return false;
}
项目:wcs-android-sdk    文件:FileUploader.java   
/**
 * 格式:uploadToken = AccessKey:encodedSign:encodePutPolicy
 * putpolicy
 * {
 * "scope": "<bucket string>",
 * "deadline": "<deadline string>",
 * "returnBody": "<returnBody string>",
 * "overwrite": "<overwrite int>",
 * "fsizeLimit": "<fsizeLimit long>",
 * "returnUrl": "<returnUrl string>"
 * }
 *
 * @param uploadToken
 * @return
 */
private static String getUploadScope(String uploadToken) {
    String[] uploadTokenArray = uploadToken.split(":");
    if (uploadTokenArray.length != 3) {
        return "";
    }
    String policyJsonString = EncodeUtils.urlsafeDecodeString(uploadTokenArray[2]);
    String scope = " ";
    try {
        JSONObject jsonObject = new JSONObject(policyJsonString);
        scope = jsonObject.optString("scope", "");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return scope;
}
项目:ConnectU    文件:NotasRequest.java   
private NotaData parseObject(JSONObject jobject) {
    if (jobject == null) {
        return null;
    }
    NotaData event = new NotaData();
    try {
        long date = Long.valueOf(AppManager.before(AppManager.after(jobject.getString("FECHA"), "("), ")"));
        event.setDate(new Date(date));
        event.setType(jobject.getString("TIPO"));
        event.setTypeId(jobject.getInt("IDTIPO"));
        event.setTitle(jobject.getString("TITULO"));
        event.setDescription(jobject.getString("DESCRIPCION"));
        event.setObservations(jobject.getString("OBSERVACIONES"));
        event.setNota(jobject.getDouble("NOTANUM"));
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return event;
}
项目:zodiva    文件:InAppBrowser.java   
public void onPageFinished(WebView view, String url) {
    super.onPageFinished(view, url);

    // CB-10395 InAppBrowser's WebView not storing cookies reliable to local device storage
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
        CookieManager.getInstance().flush();
    } else {
        CookieSyncManager.getInstance().sync();
    }

    // https://issues.apache.org/jira/browse/CB-11248
    view.clearFocus();
    view.requestFocus();

    try {
        JSONObject obj = new JSONObject();
        obj.put("type", LOAD_STOP_EVENT);
        obj.put("url", url);

        sendUpdate(obj, true);
    } catch (JSONException ex) {
        LOG.d(LOG_TAG, "Should never happen");
    }
}
项目:raven    文件:XGMessagePusher.java   
/**
 * pushAndroidMsg (android消息推送)
 * @param pushMessage
 * @return
 * @return boolean  返回类型 
 * @author wangwei
 * @date 2016年2月16日 上午11:37:58 
 * @version  [1.0, 2016年2月16日]
 * @since  version 1.0
 */
private boolean pushAndroidMsg(PushMessage pushMessage)
{
    boolean flag = false;
    XingeClient xinge = new XingeClient(androidAccessId, androidSecretKey);
    Message msg = this.convertPushMessage2MessageAndroid(pushMessage);
    List<String> deviceTokens = pushMessage.getAudiences();
    for(String token : deviceTokens)
    {
        try {
            JSONObject result = xinge.pushSingleDevice(token, msg);
            LOGGER.info("push android message result:{}",result.toString());
            if(result.getInt("ret_code") == 0){
                flag = true;
            }
        } catch (JSONException e) {
            LOGGER.error("push error:{}",e);
        }
    }
    return flag;
}
项目:localcloud_fe    文件:Device.java   
/**
 * Executes the request and returns PluginResult.
 *
 * @param action            The action to execute.
 * @param args              JSONArry of arguments for the plugin.
 * @param callbackContext   The callback id used when calling back into JavaScript.
 * @return                  True if the action was valid, false if not.
 */
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    if ("getDeviceInfo".equals(action)) {
        JSONObject r = new JSONObject();
        r.put("uuid", Device.uuid);
        r.put("version", this.getOSVersion());
        r.put("platform", this.getPlatform());
        r.put("model", this.getModel());
        r.put("manufacturer", this.getManufacturer());
     r.put("isVirtual", this.isVirtual());
        r.put("serial", this.getSerialNumber());
        callbackContext.success(r);
    }
    else {
        return false;
    }
    return true;
}
项目:GitJourney    文件:UserProfileAsyncTask.java   
@Override
protected T doInBackground(String... args) {
    String uri;
    if (args.length > 0) {
        String login = args[0];
        uri = context.getString(R.string.url_users, login);
    } else {
        uri = context.getString(R.string.url_user);
    }
    FetchHTTPConnectionService connectionFetcher = new FetchHTTPConnectionService(uri, currentSessionData);
    HTTPConnectionResult result = connectionFetcher.establishConnection();
    Log.v(TAG, "responseCode = " + result.getResponceCode());
    Log.v(TAG, "response = " + result.getResult());

    try {
        JSONObject jsonObject = new JSONObject(result.getResult());
        return parser.parse(jsonObject);

    } catch (JSONException e) {
        Log.e(TAG, "", e);
    }
    return null;
}
项目:q-mail    文件:XOAuth2ChallengeParser.java   
public static boolean shouldRetry(String response, String host) {
    String decodedResponse = Base64.decode(response);

    if (K9MailLib.isDebug()) {
        Timber.v("Challenge response: %s", decodedResponse);
    }

    try {
        JSONObject json = new JSONObject(decodedResponse);
        String status = json.getString("status");
        if (!BAD_RESPONSE.equals(status)) {
            return false;
        }
    } catch (JSONException jsonException) {
        Timber.e("Error decoding JSON response from: %s. Response was: %s", host, decodedResponse);
    }

    return true;
}
项目:browser    文件:BookmarkManager.java   
/**
 * This method returns a list of all stored bookmarks
 * 
 * @return
 */
private synchronized List<HistoryItem> getBookmarks(boolean sort) {
    List<HistoryItem> bookmarks = new ArrayList<>();
    File bookmarksFile = new File(mContext.getFilesDir(), FILE_BOOKMARKS);
    try {
        BufferedReader bookmarksReader = new BufferedReader(new FileReader(bookmarksFile));
        String line;
        while ((line = bookmarksReader.readLine()) != null) {
            JSONObject object = new JSONObject(line);
            HistoryItem item = new HistoryItem();
            item.setTitle(object.getString(TITLE));
            item.setUrl(object.getString(URL));
            item.setFolder(object.getString(FOLDER));
            item.setOrder(object.getInt(ORDER));
            item.setImageId(R.drawable.ic_bookmark);
            bookmarks.add(item);
        }
        bookmarksReader.close();
    } catch (IOException | JSONException e) {
        e.printStackTrace();
    }
    if (sort) {
        //Collections.sort(bookmarks, new SortIgnoreCase());
    }
    return bookmarks;
}
项目:sstu_schedule    文件:ParserSSU.java   
private List<Faculty> parseNameOfFaculties(JSONObject object) throws JSONException {
    JSONArray faculties = object.getJSONObject("departments").getJSONArray("department");
    List<Faculty> facultyStorage = new ArrayList<>();

    for (int i = 0; i < faculties.length(); i++) {
        JSONObject item = faculties.getJSONObject(i);

        Faculty faculty = new Faculty();
        faculty.setId(item.getString("id"));
        faculty.setName(item.getString("name"));

        facultyStorage.add(faculty);
        facultyRepository.save(faculty);
    }

    return facultyStorage;
}
项目:Sound.je    文件:JSONUtilTest.java   
@Test
public void Can_Concatenate_Fields() throws JSONException {
    JSONObject object = new JSONObject();
    object.put("a", "a");
    object.put("b", "b");

    JSONObject object2 = new JSONObject();
    object2.put("c", "c");
    object2.put("d", "d");

    JSONObject newObject = JSONUtil.deepMerge(object, object2);

    JSONObject expectedObject = new JSONObject();
    expectedObject.put("a", "a");
    expectedObject.put("b", "b");
    expectedObject.put("c", "c");
    expectedObject.put("d", "d");

    assertEquals("string must match", expectedObject.toString(), newObject.toString());
}
项目:logistimo-web-service    文件:LocationConfigServlet.java   
private Map<String, List<String>> parseStates(JSONArray states) throws JSONException {
  Map<String, List<String>> m = new HashMap<String, List<String>>();
  for (int i = 0; i < states.length(); i++) {
    JSONObject o = states.getJSONObject(i);
    Iterator<String> keys = o.keys();
    while (keys.hasNext()) {
      String k = keys.next();
      String value = o.getString(k);
      //value is a list of taluks
      JSONArray jsonArray = new JSONArray(value);
      List<String> l = new ArrayList<String>();
      for (int j = 0; j < jsonArray.length(); j++) {
        l.add(jsonArray.getString(j));
      }
      m.put(k, l);
    }
  }
  return m;
}
项目:exchange-apis    文件:BitFinexParser.java   
/**
 * Return true if string contains an info message requiring to reconnect
 *
 * @param message
 * @return
 */
private boolean isReconnectRequest(JSONObject event) {
    // We check if the message is something like this:
    // {"event":"info","code":20051,"msg":"Stopping. Please try to reconnect"}

    try {
        String eventType = event.getString("event");
        if (!"info".equals(eventType)) {
            return false;
        }
        int code = event.getInt("code");
        return code == RECONNECT_CODE || code == MAINTENANCE_CODE;
    } catch (JSONException ex) {
        // Nope, not a valid info message
        return false;
    }
}
项目:Nearby    文件:ManageSymptomActivity.java   
public void markCompleteDate(int index){

        PatientSymptom patientSymptom = list.get(index);

        progressDialog.show();

        HashMap<String, String> map = new HashMap<>();
        map.put("service", "updateSymptomFinishDate");
        map.put("symptom_history_id", patientSymptom.getId());
        map.put("date", Long.toString( AdditionalFunc.getTodayMilliseconds() ) );

        new ParsePHP(Information.MAIN_SERVER_ADDRESS, map) {

            @Override
            protected void afterThreadFinish(String data) {

                try {
                    JSONObject jObj = new JSONObject(data);
                    String status = jObj.getString("status");

                    if("success".equals(status)){
                        handler.sendMessage(handler.obtainMessage(MSG_MESSAGE_MARK_SUCCESS));
                    }else{
                        handler.sendMessage(handler.obtainMessage(MSG_MESSAGE_MARK_FAIL));
                    }

                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                    handler.sendMessage(handler.obtainMessage(MSG_MESSAGE_MARK_FAIL));
                }

            }
        }.start();


    }
项目:GitHub    文件:EventTests.java   
public void testFromJSON_keyOnly_nullOtherValues() throws JSONException {
    final Event expected = new Event();
    expected.key = "eventKey";
    final JSONObject jsonObj = new JSONObject();
    jsonObj.put("key", expected.key);
    jsonObj.put("timestamp", JSONObject.NULL);
    jsonObj.put("count", JSONObject.NULL);
    jsonObj.put("sum", JSONObject.NULL);
    final Event actual = Event.fromJSON(jsonObj);
    assertEquals(expected, actual);
    assertEquals(expected.count, actual.count);
    assertEquals(expected.sum, actual.sum);
}
项目:GitHub    文件:JsonStrSource.java   
private void init(InputStream in) throws JSONException {
    if(in == null)
        throw new NullPointerException("input stream cannot be null!");
    mInput = in;
    Logger.e("init");
    String json = IOUtils.getString(mInput);
    Logger.w(json);
    init(json);
}
项目:BWS-Android    文件:BwsToken.java   
private long extractExpirationTime(@NonNull JSONObject claims) {
    try {
        return claims.getLong("exp");
    } catch (JSONException e) {
        throw new IllegalArgumentException("JWT is missing 'exp' claim");
    }
}
项目:li-android-sdk-core    文件:LiAuthorizationException.java   
/**
 * Extracts an {@link LiAuthorizationException} from an intent produced by {@link #toIntent()}.
 * This is used to retrieve an error response in the handler registered for a call to
 */
@Nullable
public static LiAuthorizationException fromIntent(Intent data) {
    LiCoreSDKUtils.checkNotNull(data);

    if (!data.hasExtra(EXTRA_EXCEPTION)) {
        return null;
    }

    try {
        return fromJson(data.getStringExtra(EXTRA_EXCEPTION));
    } catch (JSONException ex) {
        throw new IllegalArgumentException("Intent contains malformed exception data", ex);
    }
}