Java Code Examples for org.json.JSONException

The following are top voted examples for showing how to use org.json.JSONException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: browser   File: JSONUtil.java   View source code 8 votes vote down vote up
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;

}
 
Example 2
Project: RNLearn_Project1   File: ViewHierarchyDumper.java   View source code 7 votes vote down vote up
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;
}
 
Example 3
Project: CodeMania   File: parser.java   View source code 7 votes vote down vote up
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;
}
 
Example 4
Project: localcloud_fe   File: Device.java   View source code 7 votes vote down vote up
/**
 * 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;
}
 
Example 5
Project: amap   File: VedioCenterSeviceImpl.java   View source code 6 votes vote down vote up
/**
 * 
 * 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);
}
 
Example 6
Project: localcloud_fe   File: FileUtils.java   View source code 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example 7
Project: Lantern-sdk   File: ShallowDumpData.java   View source code 6 votes vote down vote up
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;
}
 
Example 8
Project: siiMobilityAppKit   File: SplashScreen.java   View source code 6 votes vote down vote up
@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;
}
 
Example 9
Project: amap   File: NotePadSeviceImpl.java   View source code 6 votes vote down vote up
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);
}
 
Example 10
Project: RxAndroidTBP   File: MDnsHelper.java   View source code 6 votes vote down vote up
@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();
		}
	}
}
 
Example 11
Project: s-store   File: QueryStatistics.java   View source code 6 votes vote down vote up
@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
}
 
Example 12
Project: cordova-plugin-firebase-authentication   File: FirebaseAuthenticationPlugin.java   View source code 6 votes vote down vote up
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());
                            }
                        }
                    });
            }
        }
    });
}
 
Example 13
Project: amap   File: SchedueSeviceImpl.java   View source code 6 votes vote down vote up
/**
 * 
 * 确认预约日程
 * 
 * @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);
}
 
Example 14
Project: localcloud_fe   File: HotCodePushPlugin.java   View source code 6 votes vote down vote up
@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;
}
 
Example 15
Project: MovieGuide   File: JSONUtils.java   View source code 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example 16
Project: siiMobilityAppKit   File: Calendar.java   View source code 6 votes vote down vote up
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());
  }
}
 
Example 17
Project: nxtpush-cordova-plugin   File: NXTPushPlugin.java   View source code 6 votes vote down vote up
@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;
}
 
Example 18
Project: exchange-apis   File: BitFinexParser.java   View source code 6 votes vote down vote up
/**
 * 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());
    }
}
 
Example 19
Project: Accessibility   File: InstallAccessibility.java   View source code 6 votes vote down vote up
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();
            }
        }
    }
}
 
Example 20
Project: homescreenarcade   File: JSONUtils.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 21
Project: GitHub   File: EventTests.java   View source code 6 votes vote down vote up
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);
}
 
Example 22
Project: AndroidBackendlessChat   File: Request.java   View source code 6 votes vote down vote up
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());
    }
}
 
Example 23
Project: HappyWeather   File: Utility.java   View source code 6 votes vote down vote up
/**
 * 解析和处理服务器返回的县级数据
 */
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;
}
 
Example 24
Project: wcs-android-sdk   File: FileUploader.java   View source code 6 votes vote down vote up
/**
 * 格式: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;
}
 
Example 25
Project: zodiva   File: InAppBrowser.java   View source code 6 votes vote down vote up
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");
    }
}
 
Example 26
Project: sstu_schedule   File: ParserSSU.java   View source code 6 votes vote down vote up
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;
}
 
Example 27
Project: Sound.je   File: JSONUtilTest.java   View source code 6 votes vote down vote up
@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());
}
 
Example 28
Project: logistimo-web-service   File: LocationConfigServlet.java   View source code 6 votes vote down vote up
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;
}
 
Example 29
Project: exchange-apis   File: BitFinexParser.java   View source code 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example 30
Project: Nearby   File: ManageSymptomActivity.java   View source code 5 votes vote down vote up
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();


    }
 
Example 31
Project: GitHub   File: EventTests.java   View source code 5 votes vote down vote up
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);
}
 
Example 32
Project: GitHub   File: JsonStrSource.java   View source code 5 votes vote down vote up
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);
}
 
Example 33
Project: li-android-sdk-core   File: LiAuthorizationException.java   View source code 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 34
Project: solo-spring   File: TagMgmtService.java   View source code 5 votes vote down vote up
/**
 * Decrements reference count of every tag of an published article specified
 * by the given article id.
 *
 * @param articleId
 *            the given article id
 * @throws JSONException
 *             json exception
 * @throws RepositoryException
 *             repository exception
 */
public void decTagPublishedRefCount(final String articleId) throws JSONException, RepositoryException {
	final List<JSONObject> tags = tagDao.getByArticleId(articleId);

	for (final JSONObject tag : tags) {
		final String tagId = tag.getString(Keys.OBJECT_ID);
		final int refCnt = tag.getInt(Tag.TAG_REFERENCE_COUNT);

		tag.put(Tag.TAG_REFERENCE_COUNT, refCnt);
		final int publishedRefCnt = tag.getInt(Tag.TAG_PUBLISHED_REFERENCE_COUNT);

		tag.put(Tag.TAG_PUBLISHED_REFERENCE_COUNT, publishedRefCnt - 1);
		tagDao.update(tagId, tag);
	}
}
 
Example 35
Project: Blockly   File: DownloadActivity.java   View source code 5 votes vote down vote up
/**
 * 用于请求删除后端数据库保存的文件 AndrDelete
 */
public void delete() {
    RequestQueue requestQueue = MyApplication.getRequestQueue();
    userId = sharedPreferences.getString("email", "");
    token = sharedPreferences.getString("token", "");
    JSONObject jsonObject = new JSONObject();
    try {

        jsonObject.put("fileId", deleteId);
        jsonObject.put("userId", userId);
        jsonObject.put("token", token);

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


    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url_delete, jsonObject, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {

            String status;
            String errMsg;
            deleteReceive deleteReceive = new deleteReceive();
            deleteReceive.setStatus(response.optString("status"));
            deleteReceive.setErrMsg(response.optString("errMsg"));
            deleteReceive.setJsonObject(response.optJSONObject("jsonStr"));//此处获取的Json对象暂时不用,为以后做扩展做准备
            Log.d("delete_Response", response.toString());

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("Delete_Error", error.toString(), error);
        }
    });
    requestQueue.add(jsonObjectRequest);
}
 
Example 36
Project: Zmap_test   File: LoginAccount.java   View source code 5 votes vote down vote up
@Override
public boolean handleMessage(Message msg) {
    switch (msg.what) {
        case SHOW_RESPONSE:
            String Response=msg.obj.toString();
            if(!TextUtils.isEmpty(Response)){
                resp_user=new Users();
                try {
                    JSONObject userObject = new JSONObject(Response);
                    resp_user.setUser_id(userObject.getInt("id"));
                    resp_user.setUsername(userObject.getString("username"));
                    resp_user.setId_head(userObject.getInt("id_head"));
                    resp_user.setStatusCode(userObject.getInt("statusCode"));
                    if(resp_user.getUser_id() !=0){
                        Toast.makeText(LoginAccount.this,"登陆成功",Toast.LENGTH_SHORT).show();
                        resp_user.save();
                        sendRequestWithHttpClient_history();

                        finish();

                    } else {
                        Toast.makeText(LoginAccount.this,"账号密码错误",Toast.LENGTH_SHORT).show();
                        password.setText("");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            break;
        default:
            break;
    }
    return true;
}
 
Example 37
Project: cordova-plugin-radar   File: RadarCordovaUtils.java   View source code 5 votes vote down vote up
private static JSONObject jsonObjectForUserInsightsState(RadarUserInsightsState state) throws JSONException {
    if (state == null)
        return null;

    JSONObject obj = new JSONObject();
    obj.put("home", state.getHome());
    obj.put("office", state.getOffice());
    obj.put("traveling", state.getTraveling());
    return obj;
}
 
Example 38
Project: rapid-io-android   File: Message.java   View source code 5 votes vote down vote up
@Override
protected void parseJsonBody(@NonNull JSONObject jsonBody) {
	super.parseJsonBody(jsonBody);
	mSubscriptionId = jsonBody.optString(ATTR_SUB_ID);
	try {
		mChannelId = jsonBody.getString(ATTR_CHANNEL_ID);
		mNameIsPrefix = false;
	} catch(JSONException e) {
		JSONObject channelId = jsonBody.optJSONObject(ATTR_CHANNEL_ID);
		if(channelId != null) {
			mChannelId = channelId.optString(ATTR_CHANNEL_PREFIX);
			mNameIsPrefix = true;
		}
	}
}
 
Example 39
Project: amap   File: XXZXServiceImpl.java   View source code 5 votes vote down vote up
/**
 * 删除聊天项
 * 
 * @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);
}
 
Example 40
Project: GeekZone   File: BaseRequest.java   View source code 5 votes vote down vote up
private JSONObject toJsonObject(Map<String, String> headers) throws JSONException {
    JSONObject responseHeadersJson = new JSONObject();
    for (String key : headers.keySet()) {
        responseHeadersJson.put(key, headers.get(key));
    }
    return responseHeadersJson;
}