List of usage examples for org.json JSONObject getString
public String getString(String key) throws JSONException
From source file:org.indigo.cdmi.backend.radosgw.JsonResponseTranlator.java
/** * Basing on passed profileInfo, creates object of type BackendCapability. * // ww w . j a v a 2 s . c om * @param profileInfo Profile described in JSOSObject. * @return Object of BackendCapability derived from passed profileInfo. */ private BackendCapability createBackedCapability(JSONObject profileInfo) { /* * determine value of name parameter to be used with BackendCapability */ String profileName = profileInfo.getString(JSON_KEY_NAME); /* * determine value of type attribute to be used with BackendCapability */ BackendCapability.CapabilityType type = null; String typeAsString = profileInfo.getString(JSON_KEY_TYPE); switch (typeAsString) { case CDMI_OBJECT_TYPE_CONTAINER: type = BackendCapability.CapabilityType.CONTAINER; break; case CDMI_OBJECT_TYPE_DATAOBJECT: type = BackendCapability.CapabilityType.DATAOBJECT; break; default: throw new RuntimeException("Unknown capability type"); } /* * create new instance of BackendCapability * (it is empty for now, the metadata and capabilities properties have to be created, * populated and passed to the BackendCapability object) */ final BackendCapability returnBackendCapability = new BackendCapability(profileName, type); /* * create capabilities object (to be populated and injected into returned BackendCapability) */ Map<String, Object> capabilities = new HashMap<>(); /* * Add always present capabilities */ capabilities.put("cdmi_capabilities_templates", "true"); capabilities.put("cdmi_capabilities_exact_inherit", "true"); /* * create metadata object (to be populated and injected into returned BackendCapability) */ Map<String, Object> metadata = new HashMap<>(); /* * iterate through metadata in profileInfo and populate capabilities and * metadata in BackendCapability object */ JSONObject metadataObj = profileInfo.getJSONObject(JSON_KEY_METADATA); log.debug("Processing metadata array from profile returned by BackendGateway"); Iterator<?> keys = metadataObj.keys(); while (keys.hasNext()) { /* * get key name for current item in metadata array */ String key = (String) keys.next(); /* * get value assigned to the current key, and convert the value to String * NOTE: The convention is required because returned value can be for example of array type * or of another JSONObject, it not necessary has to be String, so usage of * metadataObj.getString(key) would be wrong */ Object valueObj = metadataObj.get(key); log.debug("Current metadata key: {}", key); log.debug("Current metadata value: {}", valueObj); log.debug("Metadata value class/type is: {}", valueObj.getClass()); /* * Create key and value to be added to capabilities. * Separate variables for key and value objects are introduced deliberately * to note that in future or in case of any special values, an additional * logic / calculation can be required to obtain key and value to be used * with capabilities map */ String cdmiCapabilityKey = key; String cdmiCapabilityValue = "true"; /* * add "calculated" key and value to the capabilities map */ capabilities.put(cdmiCapabilityKey, cdmiCapabilityValue); /* * see above comments for capabilities related keys and values */ String cdmiMetadataKey = key; Object cdmiMetadataValue = valueObj; /* * add "calculated" key and value to the metadata map */ metadata.put(cdmiMetadataKey, cdmiMetadataValue); } // while() //capabilities.put("cdmi_capabilities_allowed", "true"); /* * process allowed profiles */ try { JSONArray allowedProfiles = profileInfo.getJSONArray(JSON_KEY_ALLOWED_PROFILES); String profilesUris = profilesToUris(allowedProfiles, retriveObjectTypeAsString(profileInfo)); log.debug("allowedProfiles: {}", allowedProfiles); log.debug("profilesURIs: {}", profilesUris); metadata.put("cdmi_capabilities_allowed", profilesUris); } catch (JSONException ex) { log.debug("No {} key in processed JSON document", JSON_KEY_ALLOWED_PROFILES); } // try{} returnBackendCapability.setCapabilities(capabilities); returnBackendCapability.setMetadata(metadata); return returnBackendCapability; }
From source file:org.indigo.cdmi.backend.radosgw.JsonResponseTranlator.java
/** * Basing on passed JSON in String format, creates object of CdmiObjecStatus. * (Translates JSON in String format into CdmiObjectStatus) *//*from w ww. jav a 2 s.com*/ @Override public CdmiObjectStatus getCdmiObjectStatus(String gatewayResponse) { //log.debug("Translate {} to CdmiObjectStatus", gatewayResponse); Map<String, Object> monitoredAttributes = new HashMap<>(); JSONObject profile = new JSONObject(gatewayResponse); //log.debug("profile: {}", profile); JSONObject metadataProvided = profile.getJSONObject("metadata_provided"); //log.debug("metadata_provided: {}", metadataProvided); Iterator<?> keys = metadataProvided.keys(); while (keys.hasNext()) { /* * get key name for current item in metadata array */ String key = (String) keys.next(); //log.debug("key: {}", key); Object metadataProvidedAsObj = metadataProvided.get(key); //String metadataProvidedAsString = metadataProvidedAsObj.toString(); //monitoredAttributes.put(key, metadataProvidedAsString); monitoredAttributes.put(key, metadataProvidedAsObj); } String profileName = profile.getString("name"); String type = profile.getString("type"); String currentCapabilitiesUri = "/cdmi_capabilities/" + type + "/" + profileName; return new CdmiObjectStatus(monitoredAttributes, currentCapabilitiesUri, null); }
From source file:com.intel.xdk.device.Device.java
public void getRemoteDataExt(JSONObject obj) { String requestUrl;//w w w . ja v a 2 s.com String id; String method; String body; String headers; try { //Request url requestUrl = obj.getString("url"); //ID that correlates the request to the event id = obj.getString("id"); //Request method method = obj.getString("method"); //Request body body = obj.getString("body"); //Request header headers = obj.getString("headers"); String js = null; if (method == null || method.length() == 0) method = "GET"; HttpURLConnection connection = (HttpURLConnection) new URL(requestUrl).openConnection(); boolean forceUTF8 = false; try { if (headers.length() > 0) { String[] headerArray = headers.split("&"); //Set request header for (String header : headerArray) { String[] headerPair = header.split("="); if (headerPair.length == 2) { String field = headerPair[0]; String value = headerPair[1]; if (field != null && value != null) { if (!"content-length".equals(field.toLowerCase())) {//skip Content-Length - causes error because it is managed by the request connection.setRequestProperty(field, value); } field = field.toLowerCase(); value = value.toLowerCase(); if (field.equals("content-type") && value.indexOf("charset") > -1 && value.indexOf("utf-8") > -1) { forceUTF8 = true; } } } } } if ("POST".equalsIgnoreCase(method)) { connection.setRequestMethod(method); connection.setDoOutput(true); connection.setFixedLengthStreamingMode(body.length()); DataOutputStream dStream = new DataOutputStream(connection.getOutputStream()); dStream.writeBytes(body); dStream.flush(); dStream.close(); } //inject response int statusCode = connection.getResponseCode(); final StringBuilder response = new StringBuilder(); try { InputStream responseStream = connection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(responseStream)); String line; while ((line = br.readLine()) != null) { response.append(line); } br.close(); } catch (Exception e) { } String responseBody = null; // how to handle UTF8 without EntityUtils? // if (forceUTF8) { // responseBody = EntityUtils.toString(entity, "UTF-8"); // } else { // responseBody = EntityUtils.toString(entity); // } responseBody = response.toString(); String responseMessage = connection.getResponseMessage(); char[] bom = { 0xef, 0xbb, 0xbf }; //check for BOM characters, then strip if present if (responseBody.length() >= 3 && responseBody.charAt(0) == bom[0] && responseBody.charAt(1) == bom[1] && responseBody.charAt(2) == bom[2]) { responseBody = responseBody.substring(3); } //escape existing backslashes responseBody = responseBody.replaceAll("\\\\", "\\\\\\\\"); //escape internal double-quotes responseBody = responseBody.replaceAll("\"", "\\\\\""); responseBody = responseBody.replaceAll("'", "\\\\'"); //replace linebreaks with \n responseBody = responseBody.replaceAll("\\r\\n|\\r|\\n", "\\\\n"); StringBuilder extras = new StringBuilder("{"); extras.append(String.format("status:'%d',", statusCode)); String status = null; switch (statusCode) { case 200: status = "OK"; break; case 201: status = "CREATED"; break; case 202: status = "Accepted"; break; case 203: status = "Partial Information"; break; case 204: status = "No Response"; break; case 301: status = "Moved"; break; case 302: status = "Found"; break; case 303: status = "Method"; break; case 304: status = "Not Modified"; break; case 400: status = "Bad request"; break; case 401: status = "Unauthorized"; break; case 402: status = "PaymentRequired"; break; case 403: status = "Forbidden"; break; case 404: status = "Not found"; break; case 500: status = "Internal Error"; break; case 501: status = "Not implemented"; break; case 502: status = "Service temporarily overloaded"; break; case 503: status = "Gateway timeout"; break; } extras.append(String.format("statusText:'%s',", status)); extras.append("headers: {"); List<String> cookieData = new ArrayList<String>(); Map<String, List<String>> allHeaders = connection.getHeaderFields(); for (String key : allHeaders.keySet()) { if (key == null) { continue; } String value = connection.getHeaderField(key); value = value.replaceAll("'", "\\\\'"); if (key.toLowerCase().equals("set-cookie")) cookieData.add(value); else extras.append(String.format("'%s':'%s',", key, value)); } String concatCookies = cookieData.toString(); concatCookies = concatCookies.substring(0, concatCookies.length()); extras.append(String.format("'Set-Cookie':'%s',", concatCookies.substring(1, concatCookies.length() - 1))); String cookieArray = "["; for (int i = 0; i < cookieData.size(); i++) cookieArray += String.format("'%s',", cookieData.get(i)); cookieArray += "]"; extras.append("'All-Cookies': " + cookieArray); extras.append("} }"); js = String.format( "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.device.remote.data',true,true);e.success=true;e.id='%s';e.response='%s';e.extras=%s;document.dispatchEvent(e);", id, responseBody, extras.toString()); } catch (Exception ex) { js = String.format( "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.device.remote.data',true,true);e.success=false;e.id='%s';e.response='';e.extras={};e.error='%s';document.dispatchEvent(e);", id, ex.getMessage()); } catch (OutOfMemoryError err) { js = String.format( "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.device.remote.data',true,true);e.success=false;e.id='%s';e.response='';e.extras={};e.error='%s';document.dispatchEvent(e);", id, err.getMessage()); } finally { connection.disconnect(); } injectJS(js); } catch (Exception e) { Log.d("getRemoteDataExt", e.getMessage()); } }
From source file:com.mobile.system.db.abatis.AbatisService.java
/** * //from www .ja va 2 s . com * @param jsonStr * JSON String * @param beanClass * Bean class * @param basePackage * Base package name which includes all Bean classes * @return Object Bean * @throws Exception */ @SuppressWarnings({ "rawtypes", "unchecked" }) public Object parse(String jsonStr, Class beanClass, String basePackage) throws Exception { Object obj = null; JSONObject jsonObj = new JSONObject(jsonStr); // Check bean object if (beanClass == null) { Log.d(TAG, "Bean class is null"); return null; } // Read Class member fields Field[] props = beanClass.getDeclaredFields(); if (props == null || props.length == 0) { Log.d(TAG, "Class" + beanClass.getName() + " has no fields"); return null; } // Create instance of this Bean class obj = beanClass.newInstance(); // Set value of each member variable of this object for (int i = 0; i < props.length; i++) { String fieldName = props[i].getName(); // Skip public and static fields if (props[i].getModifiers() == (Modifier.PUBLIC | Modifier.STATIC)) { continue; } // Date Type of Field Class type = props[i].getType(); String typeName = type.getName(); // Check for Custom type if (typeName.equals("int")) { Class[] parms = { type }; Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms); m.setAccessible(true); // Set value try { m.invoke(obj, jsonObj.getInt(fieldName)); } catch (Exception ex) { Log.d(TAG, ex.getMessage()); } } else if (typeName.equals("long")) { Class[] parms = { type }; Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms); m.setAccessible(true); // Set value try { m.invoke(obj, jsonObj.getLong(fieldName)); } catch (Exception ex) { Log.d(TAG, ex.getMessage()); } } else if (typeName.equals("java.lang.String")) { Class[] parms = { type }; Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms); m.setAccessible(true); // Set value try { m.invoke(obj, jsonObj.getString(fieldName)); } catch (Exception ex) { Log.d(TAG, ex.getMessage()); } } else if (typeName.equals("double")) { Class[] parms = { type }; Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms); m.setAccessible(true); // Set value try { m.invoke(obj, jsonObj.getDouble(fieldName)); } catch (Exception ex) { Log.d(TAG, ex.getMessage()); } } else if (typeName.equals("java.util.Date")) { // modify Class[] parms = { type }; Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms); m.setAccessible(true); String dateString = jsonObj.getString(fieldName); dateString = dateString.replace(" KST", ""); SimpleDateFormat genderFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy", Locale.KOREA); // Set value try { Date afterDate = genderFormat.parse(dateString); m.invoke(obj, afterDate); } catch (Exception e) { Log.d(TAG, e.getMessage()); } } else if (type.getName().equals(List.class.getName()) || type.getName().equals(ArrayList.class.getName())) { // Find out the Generic String generic = props[i].getGenericType().toString(); if (generic.indexOf("<") != -1) { String genericType = generic.substring(generic.lastIndexOf("<") + 1, generic.lastIndexOf(">")); if (genericType != null) { JSONArray array = null; try { array = jsonObj.getJSONArray(fieldName); } catch (Exception ex) { Log.d(TAG, ex.getMessage()); array = null; } if (array == null) { continue; } ArrayList arrayList = new ArrayList(); for (int j = 0; j < array.length(); j++) { arrayList.add(parse(array.getJSONObject(j).toString(), Class.forName(genericType), basePackage)); } // Set value Class[] parms = { type }; Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms); m.setAccessible(true); m.invoke(obj, arrayList); } } else { // No generic defined generic = null; } } else if (typeName.startsWith(basePackage)) { Class[] parms = { type }; Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms); m.setAccessible(true); // Set value try { JSONObject customObj = jsonObj.getJSONObject(fieldName); if (customObj != null) { m.invoke(obj, parse(customObj.toString(), type, basePackage)); } } catch (JSONException ex) { Log.d(TAG, ex.getMessage()); } } else { // Skip Log.d(TAG, "Field " + fieldName + "#" + typeName + " is skip"); } } return obj; }
From source file:com.nginious.http.serialize.JsonSerializerTestCase.java
public void testJsonSerializer() throws Exception { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ"); SerializableBean bean = new SerializableBean(); bean.setBooleanValue(true);// ww w. j a va 2 s . c o m bean.setDoubleValue(0.451); bean.setFloatValue(1.34f); bean.setIntValue(3400100); bean.setLongValue(3400100200L); bean.setShortValue((short) 32767); bean.setStringValue("String"); bean.setDateValue(format.parse("2011-08-24T08:50:23+0200")); Date calDate = format.parse("2011-08-24T08:52:23+0200"); Calendar cal = Calendar.getInstance(); cal.setTime(calDate); bean.setCalendarValue(cal); bean.setObjectValue(TimeZone.getDefault()); InBean inBean = new InBean(); inBean.setFirst(true); inBean.setSecond(0.567d); inBean.setThird(0.342f); inBean.setFourth(100); inBean.setFifth(3400200100L); inBean.setSixth((short) 32767); inBean.setSeventh("String"); inBean.setEight(format.parse("2011-08-25T08:50:23+0200")); cal = Calendar.getInstance(); calDate = format.parse("2011-08-25T08:52:23+0200"); cal.setTime(calDate); inBean.setNinth(cal); bean.setBeanValue(inBean); List<InBean> beanList = new ArrayList<InBean>(); beanList.add(inBean); beanList.add(inBean); bean.setBeanListValue(beanList); List<String> stringList = new ArrayList<String>(); stringList.add("One"); stringList.add("Two"); stringList.add("Three"); bean.setStringListValue(stringList); ApplicationClassLoader classLoader = new ApplicationClassLoader( Thread.currentThread().getContextClassLoader()); SerializerFactoryImpl serializerFactory = new SerializerFactoryImpl(classLoader); Serializer<SerializableBean> serializer = serializerFactory.createSerializer(SerializableBean.class, "application/json"); assertEquals("application/json", serializer.getMimeType()); StringWriter strWriter = new StringWriter(); PrintWriter writer = new PrintWriter(strWriter); serializer.serialize(writer, bean); writer.flush(); JSONObject json = new JSONObject(strWriter.toString()); assertNotNull(json); assertTrue(json.has("serializableBean")); json = json.getJSONObject("serializableBean"); assertEquals(true, json.getBoolean("booleanValue")); assertEquals(0.451, json.getDouble("doubleValue")); assertEquals(1.34f, (float) json.getDouble("floatValue")); assertEquals(3400100, json.getInt("intValue")); assertEquals(3400100200L, json.getLong("longValue")); assertEquals(32767, (short) json.getInt("shortValue")); assertEquals("String", json.getString("stringValue")); assertEquals("2011-08-24T08:50:23+02:00", json.getString("dateValue")); assertEquals("2011-08-24T08:52:23+02:00", json.getString("calendarValue")); assertEquals(TimeZone.getDefault().toString(), json.getString("objectValue")); assertTrue(json.has("beanValue")); JSONObject inBeanJson = json.getJSONObject("beanValue"); assertTrue(inBeanJson.has("inBean")); inBeanJson = inBeanJson.getJSONObject("inBean"); assertEquals(true, inBeanJson.getBoolean("first")); assertEquals(0.567, inBeanJson.getDouble("second")); assertEquals(0.342f, (float) inBeanJson.getDouble("third")); assertEquals(100, inBeanJson.getInt("fourth")); assertEquals(3400200100L, inBeanJson.getLong("fifth")); assertEquals(32767, (short) inBeanJson.getInt("sixth")); assertEquals("String", inBeanJson.getString("seventh")); assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight")); assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth")); assertTrue(json.has("stringListValue")); JSONArray stringListJson = json.getJSONArray("stringListValue"); assertEquals("One", stringListJson.get(0)); assertEquals("Two", stringListJson.get(1)); assertEquals("Three", stringListJson.get(2)); assertTrue(json.has("beanListValue")); JSONArray beanListJson = json.getJSONArray("beanListValue"); inBeanJson = beanListJson.getJSONObject(0); assertTrue(inBeanJson.has("inBean")); inBeanJson = inBeanJson.getJSONObject("inBean"); assertEquals(true, inBeanJson.getBoolean("first")); assertEquals(0.567, inBeanJson.getDouble("second")); assertEquals(0.342f, (float) inBeanJson.getDouble("third")); assertEquals(100, inBeanJson.getInt("fourth")); assertEquals(3400200100L, inBeanJson.getLong("fifth")); assertEquals(32767, (short) inBeanJson.getInt("sixth")); assertEquals("String", inBeanJson.getString("seventh")); assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight")); assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth")); inBeanJson = beanListJson.getJSONObject(1); assertTrue(inBeanJson.has("inBean")); inBeanJson = inBeanJson.getJSONObject("inBean"); assertEquals(true, inBeanJson.getBoolean("first")); assertEquals(0.567, inBeanJson.getDouble("second")); assertEquals(0.342f, (float) inBeanJson.getDouble("third")); assertEquals(100, inBeanJson.getInt("fourth")); assertEquals(3400200100L, inBeanJson.getLong("fifth")); assertEquals(32767, (short) inBeanJson.getInt("sixth")); assertEquals("String", inBeanJson.getString("seventh")); assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight")); assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth")); }
From source file:com.nginious.http.serialize.JsonSerializerTestCase.java
public void testNamedJsonSerializer() throws Exception { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ"); NamedBean bean = new NamedBean(); bean.setBooleanValue(true);/*from w w w . ja v a 2s . c om*/ bean.setDoubleValue(0.451); bean.setFloatValue(1.34f); bean.setIntValue(3400100); bean.setLongValue(3400100200L); bean.setShortValue((short) 32767); bean.setStringValue("String"); bean.setDateValue(format.parse("2011-08-24T08:50:23+0200")); Date calDate = format.parse("2011-08-24T08:52:23+0200"); Calendar cal = Calendar.getInstance(); cal.setTime(calDate); bean.setCalendarValue(cal); bean.setObjectValue(TimeZone.getDefault()); InBean inBean = new InBean(); inBean.setFirst(true); inBean.setSecond(0.567d); inBean.setThird(0.342f); inBean.setFourth(100); inBean.setFifth(3400200100L); inBean.setSixth((short) 32767); inBean.setSeventh("String"); inBean.setEight(format.parse("2011-08-25T08:50:23+0200")); cal = Calendar.getInstance(); calDate = format.parse("2011-08-25T08:52:23+0200"); cal.setTime(calDate); inBean.setNinth(cal); bean.setBeanValue(inBean); List<InBean> beanList = new ArrayList<InBean>(); beanList.add(inBean); beanList.add(inBean); bean.setBeanListValue(beanList); List<String> stringList = new ArrayList<String>(); stringList.add("One"); stringList.add("Two"); stringList.add("Three"); bean.setStringListValue(stringList); ApplicationClassLoader classLoader = new ApplicationClassLoader( Thread.currentThread().getContextClassLoader()); SerializerFactoryImpl serializerFactory = new SerializerFactoryImpl(classLoader); Serializer<NamedBean> serializer = serializerFactory.createSerializer(NamedBean.class, "application/json"); assertEquals("application/json", serializer.getMimeType()); StringWriter strWriter = new StringWriter(); PrintWriter writer = new PrintWriter(strWriter); serializer.serialize(writer, bean); writer.flush(); JSONObject json = new JSONObject(strWriter.toString()); assertNotNull(json); assertTrue(json.has("testNamedBean")); json = json.getJSONObject("testNamedBean"); assertEquals(true, json.getBoolean("testBooleanValue")); assertEquals(0.451, json.getDouble("testDoubleValue")); assertEquals(1.34f, (float) json.getDouble("testFloatValue")); assertEquals(3400100, json.getInt("testIntValue")); assertEquals(3400100200L, json.getLong("testLongValue")); assertEquals(32767, (short) json.getInt("testShortValue")); assertEquals("String", json.getString("testStringValue")); assertEquals("2011-08-24T08:50:23+02:00", json.getString("testDateValue")); assertEquals("2011-08-24T08:52:23+02:00", json.getString("testCalendarValue")); assertEquals(TimeZone.getDefault().toString(), json.getString("testObjectValue")); assertTrue(json.has("testBeanValue")); JSONObject inBeanJson = json.getJSONObject("testBeanValue"); assertTrue(inBeanJson.has("inBean")); inBeanJson = inBeanJson.getJSONObject("inBean"); assertEquals(true, inBeanJson.getBoolean("first")); assertEquals(0.567, inBeanJson.getDouble("second")); assertEquals(0.342f, (float) inBeanJson.getDouble("third")); assertEquals(100, inBeanJson.getInt("fourth")); assertEquals(3400200100L, inBeanJson.getLong("fifth")); assertEquals(32767, (short) inBeanJson.getInt("sixth")); assertEquals("String", inBeanJson.getString("seventh")); assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight")); assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth")); assertTrue(json.has("testStringListValue")); JSONArray stringListJson = json.getJSONArray("testStringListValue"); assertEquals("One", stringListJson.get(0)); assertEquals("Two", stringListJson.get(1)); assertEquals("Three", stringListJson.get(2)); assertTrue(json.has("testBeanListValue")); JSONArray beanListJson = json.getJSONArray("testBeanListValue"); inBeanJson = beanListJson.getJSONObject(0); assertTrue(inBeanJson.has("inBean")); inBeanJson = inBeanJson.getJSONObject("inBean"); assertEquals(true, inBeanJson.getBoolean("first")); assertEquals(0.567, inBeanJson.getDouble("second")); assertEquals(0.342f, (float) inBeanJson.getDouble("third")); assertEquals(100, inBeanJson.getInt("fourth")); assertEquals(3400200100L, inBeanJson.getLong("fifth")); assertEquals(32767, (short) inBeanJson.getInt("sixth")); assertEquals("String", inBeanJson.getString("seventh")); assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight")); assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth")); inBeanJson = beanListJson.getJSONObject(1); assertTrue(inBeanJson.has("inBean")); inBeanJson = inBeanJson.getJSONObject("inBean"); assertEquals(true, inBeanJson.getBoolean("first")); assertEquals(0.567, inBeanJson.getDouble("second")); assertEquals(0.342f, (float) inBeanJson.getDouble("third")); assertEquals(100, inBeanJson.getInt("fourth")); assertEquals(3400200100L, inBeanJson.getLong("fifth")); assertEquals(32767, (short) inBeanJson.getInt("sixth")); assertEquals("String", inBeanJson.getString("seventh")); assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight")); assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth")); }
From source file:org.cloudfoundry.client.lib.util.JsonUtil.java
public static Map<String, Object> convertJsonToMap(JSONObject json) throws JSONException { Map<String, Object> retMap = new HashMap<String, Object>(); JSONObject jo = new JSONObject(json.toString()); for (String key : JsonUtil.keys(jo)) { if (jo.get(key.toString()) instanceof JSONObject) { retMap.put(key.toString(), convertJsonToMap(jo.getJSONObject(key.toString()))); } else {//w ww .j ava2s.co m retMap.put(key.toString(), jo.getString(key.toString())); } } return retMap; }
From source file:com.layer.atlas.messenger.AtlasIdentityProvider.java
private String[] refreshContacts(boolean requestIdentityToken, String nonce, String userName) { try {/*from w ww . j a v a 2 s . com*/ String url = "https://layer-identity-provider.herokuapp.com/apps/" + appId + "/atlas_identities"; HttpPost post = new HttpPost(url); post.setHeader("Content-Type", "application/json"); post.setHeader("Accept", "application/json"); post.setHeader("X_LAYER_APP_ID", appId); JSONObject rootObject = new JSONObject(); if (requestIdentityToken) { rootObject.put("nonce", nonce); rootObject.put("name", userName); } else { rootObject.put("name", "Web"); // name must be specified to make entiry valid } StringEntity entity = new StringEntity(rootObject.toString(), "UTF-8"); entity.setContentType("application/json"); post.setEntity(entity); HttpResponse response = (new DefaultHttpClient()).execute(post); if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode() && HttpStatus.SC_CREATED != response.getStatusLine().getStatusCode()) { StringBuilder sb = new StringBuilder(); sb.append("Got status ").append(response.getStatusLine().getStatusCode()).append(" [") .append(response.getStatusLine()).append("] when logging in. Request: ").append(url); if (requestIdentityToken) sb.append(" login: ").append(userName).append(", nonce: ").append(nonce); Log.e(TAG, sb.toString()); return new String[] { null, sb.toString() }; } String responseString = EntityUtils.toString(response.getEntity()); JSONObject jsonResp = new JSONObject(responseString); JSONArray atlasIdentities = jsonResp.getJSONArray("atlas_identities"); List<Participant> participants = new ArrayList<Participant>(atlasIdentities.length()); for (int i = 0; i < atlasIdentities.length(); i++) { JSONObject identity = atlasIdentities.getJSONObject(i); Participant participant = new Participant(); participant.firstName = identity.getString("name"); participant.userId = identity.getString("id"); participants.add(participant); } if (participants.size() > 0) { setParticipants(participants); save(); if (debug) Log.d(TAG, "refreshContacts() contacts: " + atlasIdentities); } if (requestIdentityToken) { String error = jsonResp.optString("error", null); String identityToken = jsonResp.optString("identity_token"); return new String[] { identityToken, error }; } return new String[] { null, "Refreshed " + participants.size() + " contacts" }; } catch (Exception e) { Log.e(TAG, "Error when fetching identity token", e); return new String[] { null, "Cannot obtain identity token. " + e }; } }
From source file:fi.elfcloud.sci.container.Cluster.java
public Cluster(Client client, JSONObject object) throws JSONException { this.client = client; this.id = object.getInt("id"); this.name = object.getString("name"); this.childCount = object.getInt("descendants"); this.dataItemCount = object.getInt("dataitems"); this.parent_id = object.getInt("parent_id"); this.last_accessed_date = (object.get("last_accessed_date") != JSONObject.NULL ? object.getString("last_accessed_date") : ""); this.last_modified_date = (object.get("modified_date") != JSONObject.NULL ? object.getString("modified_date") : ""); this.permissions = object.getJSONArray("permissions"); }
From source file:com.codebutler.farebot.keys.ClassicSectorKey.java
public static ClassicSectorKey fromJSON(JSONObject json) throws JSONException { return new ClassicSectorKey(json.getString(TYPE), Utils.hexStringToByteArray(json.getString(KEY))); }