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   Source Code and License 9 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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;
}
 
Example 41
Project: logistimo-web-service   File: DashboardConfig.java   Source Code and License 5 votes vote down vote up
public JSONObject toJSONObject() throws JSONException {
  JSONObject json = new JSONObject();
  json.put(DEFAULT_MATERIAL_TAG, dmtg);
  json.put(DEFAULT_INV_MATERIAL_TAG, dimtg);
  json.put(DEFAULT_ENTITY_TAG, detg);
  json.put(DEFAULT_TRANSACTION_TYPE, dtt);
  json.put(ATD_DISABLED, atdd);
  json.put(ENABLE_DASHBOARD_MANAGERS, edm);
  json.put(EXCLUDE_ENTITY_TAG, exet);
  json.put(EXCLUDE_TEMP_STATUS_TAG, exts);
  json.put(ACTIVITY_PERIOD, aper);
  json.put(DISABLE_BY_USER_TAG, dutg);
  return json;
}
 
Example 42
Project: homunculus   File: Supportiety.java   Source Code and License 5 votes vote down vote up
private JSONObject asTrace(Throwable t) {
    JSONObject res = new JSONObject();
    try {
        insert(res, t);
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    return res;
}
 
Example 43
Project: EARLGREY   File: Properties.java   Source Code and License 5 votes vote down vote up
private void setFile(){
	this.config = new File("kernel/properties/config.properties");
	// EN CASO DE QUE NO EXISTA DEBE SER CREADO
	log.Info("Cargando Archivo de configuraciones de properties");
	try {
		if(!this.config.exists()){
			this.config.createNewFile();
			this.setDefault();
		}
		else
		{
			log.Info("Verificando integridad de archivo de configuraciones");
			FileReader fr = new FileReader(this.config);
			BufferedReader br = new BufferedReader(fr);
			String linea = br.readLine();
			if(linea != null){
				try {
					JSONObject conf = new JSONObject(linea);
					this.config_obj = conf;
					// VERIFICAMOS MODIFICACIONES
					this.checkPropertieFileAndFix();
			    } catch (JSONException ex) {
			    	this.log.Critic("El archivo de configuraciones esta corrupto, verifique su confguracion", Error700.FILE_DAMAGE_ERROR);
			    }
			}
			else{
				this.log.Critic("El archivo de configuraciones esta vacio, restaurando la copia", Error700.FILE_EMPTY_ERROR);
				this.setDefault();
			}
		}
		
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	log.Info("Archivo de configuración de properties, cargado.");
	this.selectEnv();
}
 
Example 44
Project: chat-sdk-android-push-firebase   File: Response.java   Source Code and License 5 votes vote down vote up
static List<Response> createResponsesFromString(String responseString, HttpURLConnection connection,
        RequestBatch requests, boolean isFromCache) throws FacebookException, JSONException, IOException {
    JSONTokener tokener = new JSONTokener(responseString);
    Object resultObject = tokener.nextValue();

    List<Response> responses = createResponsesFromObject(connection, requests, resultObject, isFromCache);
    Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response\n  Id: %s\n  Size: %d\n  Responses:\n%s\n",
            requests.getId(), responseString.length(), responses);

    return responses;
}
 
Example 45
Project: raven   File: XingeClient.java   Source Code and License 5 votes vote down vote up
public static JSONObject pushTagAndroid(long accessId, String secretKey, String title, String content, String tag) throws JSONException
{
	Message message = new Message();
	message.setType(Message.TYPE_NOTIFICATION);
	message.setTitle(title);
	message.setContent(content);
	
	XingeClient xinge = new XingeClient(accessId, secretKey);	
	List<String> tagList = new ArrayList<String>();
	tagList.add(tag);
	JSONObject ret = xinge.pushTags(0, tagList, "OR", message);
	return (ret);
}
 
Example 46
Project: localcloud_fe   File: CordovaActivity.java   Source Code and License 5 votes vote down vote up
/**
 * Called by the system when the user grants permissions
 *
 * @param requestCode
 * @param permissions
 * @param grantResults
 */
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[],
                                       int[] grantResults) {
    try
    {
        cordovaInterface.onRequestPermissionResult(requestCode, permissions, grantResults);
    }
    catch (JSONException e)
    {
        LOG.d(TAG, "JSONException: Parameters fed into the method are not valid");
        e.printStackTrace();
    }

}
 
Example 47
Project: ConnectU   File: NotasRequest.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 48
Project: raven   File: XGMessagePusher.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 49
Project: AliZhiBoHao   File: WebActivity.java   Source Code and License 5 votes vote down vote up
@JavascriptInterface
public void openCamera(String liveId, String json) {
    //清空自己的直播间的商品
    if (pList.size() != 0) pList.clear();
    //邀约直播的参数
    Intent in = new Intent(WebActivity.this, PushParamsActivity.class);
    try {
        JSONObject jsonObject = new JSONObject(json);
        String pushUrl = jsonObject.getString("rtmp");
        String memberLevel = jsonObject.getString("memberlevel");
        String openId = jsonObject.getString("deleid");
        String goods = jsonObject.getString("goods");
        JSONArray object_goods = new JSONArray(goods);
        for (int i = 0; i < object_goods.length(); i++) {
            JSONObject object_good = object_goods.getJSONObject(i);
            products = new Products();
            products.setProducts_id(object_good.getString("id"));
            products.setProducts_name(object_good.getString("name"));
            products.setProducts_price(object_good.getString("price"));
            String baseUrl = object_good.getString("img").startsWith("//") ? "http:" : mBase;
            products.setProducts_icon(baseUrl + object_good.getString("img"));
            pList.add(products);
        }
        in.putExtra("pushurl", pushUrl);
        in.putExtra("openid", openId);
        in.putExtra("memberlevelid", memberLevel);
        in.putExtra("eventurl", lri.getEventUrl());
        in.putParcelableArrayListExtra("products_list", pList);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    shareInfo.setLiveId(liveId);
    in.putExtra("shareinfo", shareInfo);
    startActivity(in);
}
 
Example 50
Project: osumer   File: Config.java   Source Code and License 5 votes vote down vote up
public void load() throws IOException {
    File file = new File(dataFilePath + "/" + dataFileName);
    if (!file.exists()) {
        write();
        return;
    }
    FileInputStream in = new FileInputStream(file);

    String data = "";
    String line;
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    while ((line = reader.readLine()) != null) {
        data += line;
    }
    reader.close();

    /* 
     * Preferences prefs = Preferences.userRoot();
     * 
     * String data = prefs.get("com.github.mob41.osumer.configuration",
     * null);
     * 
     * if (data == null){ write(); return; }
     */

    try {
        json = new JSONObject(data);
        if (fillJson(json)) {
            write();
        }
    } catch (JSONException e) {
        throw new IOException("Invalid configuration data structure", e);
    }
}
 
Example 51
Project: kqsse17   File: MainActivity.java   Source Code and License 5 votes vote down vote up
private ResponseResult parseJSONResponse(String respJsonString) {
    ResponseResult rr = new ResponseResult();
    try {
        Log.i(TAG, "JSON : "+respJsonString);
        JSONObject jo = new JSONObject(respJsonString);
        if(jo.has(Kairos.ERRORS)) {
            String kairosError = ((JSONObject)jo.getJSONArray(Kairos.ERRORS).get(0)).getString(Kairos.MESSAGE);
            rr.setResultMessage(apiService+" : "+kairosError);
            Log.i(TAG, "kairosError : " + kairosError);
        }
        else {
            JSONObject transaction =((JSONObject)jo.getJSONArray(Kairos.IMAGES).get(0))
                    .getJSONObject(Kairos.TRANSACTION);
            String kairosStatus = transaction.getString(Kairos.STATUS);
            Log.i(TAG, "kairosStatus : " + kairosStatus);
            if(kairosStatus.equals(Kairos.SUCCESS)) {
                rr.setSuccessful(true);
                String subject = transaction.getString(Kairos.SUBJECT_ID);
                rr.setSubject(subject);
                rr.setResultMessage(apiService+" "+subject+" : "+kairosStatus);
            }
            else {
                rr.setResultMessage(apiService+" : "+kairosStatus+" - "+
                        transaction.getString(Kairos.MESSAGE_FAILURE));
            }
        }
    } catch(JSONException j) {
        Log.i(TAG, "Problem in parsing response JSON");
        j.printStackTrace();
    }
    return rr;
}
 
Example 52
Project: GitJourney   File: UserProfileAsyncTask.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 53
Project: messenger   File: ServerProtocol.java   Source Code and License 5 votes vote down vote up
@NonNull
public static byte[] packCallPrepPacket(String sessionId) {
    JSONObject object = new JSONObject();
    try {
        object.put("i", sessionId);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return pack(PacketType.CALL_PREP, object.toString());
}
 
Example 54
Project: q-mail   File: XOAuth2ChallengeParser.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 55
Project: sstore-soft   File: ColumnStatistics.java   Source Code and License 5 votes vote down vote up
@Override
public void toJSONString(JSONStringer stringer) throws JSONException {
    // Read-only
    stringer.key(Members.READONLY.name()).value(this.readonly);

    // Histogram
    stringer.key(Members.HISTOGRAM.name()).object();
    this.histogram.toJSON(stringer);
    stringer.endObject();
}
 
Example 56
Project: letv   File: JSONSource.java   Source Code and License 5 votes vote down vote up
private void init(InputStream in) throws JSONException {
    if (in == null) {
        throw new NullPointerException("input stream cannot be null!");
    }
    this.mInput = in;
    init(IOUtils.getString(this.mInput));
}
 
Example 57
Project: browser   File: BookmarkManager.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 58
Project: Amazing   File: WSTestActivity.java   Source Code and License 5 votes vote down vote up
private String getWrapper(String message) {
    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject.putOpt("action", Action.DESC_ACTION);
        jsonObject.putOpt("desc", message);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return jsonObject.toString();
}
 
Example 59
Project: hyperrail-for-android   File: IrailApiParser.java   Source Code and License 5 votes vote down vote up
public RouteResult parseRouteResult(JSONObject json, Station origin, Station destination, DateTime searchTime, RouteTimeDefinition timeDefinition) throws JSONException {
    JSONArray routesObject = json.getJSONArray("connection");
    Route[] routes = new Route[routesObject.length()];
    for (int i = 0; i < routesObject.length(); i++) {
        routes[i] = parseRoute(routesObject.getJSONObject(i));
    }
    return new RouteResult(origin, destination, searchTime, timeDefinition, routes);
}
 
Example 60
Project: GitHub   File: GetJSONApiTest.java   Source Code and License 5 votes vote down vote up
public void testJSONArrayGetRequest() throws InterruptedException {

        server.enqueue(new MockResponse().setBody("[{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}]"));

        final AtomicReference<String> firstNameRef = new AtomicReference<>();
        final AtomicReference<String> lastNameRef = new AtomicReference<>();
        final CountDownLatch latch = new CountDownLatch(1);

        AndroidNetworking.get(server.url("/").toString())
                .build()
                .getAsJSONArray(new JSONArrayRequestListener() {
                    @Override
                    public void onResponse(JSONArray response) {
                        try {
                            JSONObject jsonObject = response.getJSONObject(0);
                            firstNameRef.set(jsonObject.getString("firstName"));
                            lastNameRef.set(jsonObject.getString("lastName"));
                            latch.countDown();
                        } catch (JSONException e) {
                            assertTrue(false);
                        }
                    }

                    @Override
                    public void onError(ANError anError) {
                        assertTrue(false);
                    }
                });

        assertTrue(latch.await(2, SECONDS));

        assertEquals("Amit", firstNameRef.get());
        assertEquals("Shekhar", lastNameRef.get());
    }