/** * 序列化为JSON * * @param js json对象 * @param o 待需序列化的对象 */ private static void serialize(JSONStringer js, Object o) { if (isNull(o)) { try { js.value(null); } catch (JSONException e) { e.printStackTrace(); } return; } Class<?> clazz = o.getClass(); if (isObject(clazz)) { // 对象 serializeObject(js, o); } else if (isArray(clazz)) { // 数组 serializeArray(js, o); } else if (isCollection(clazz)) { // 集合 Collection<?> collection = (Collection<?>) o; serializeCollect(js, collection); } else if (isMap(clazz)) { // 集合 HashMap<?, ?> collection = (HashMap<?, ?>) o; serializeMap(js, collection); } else { // 单个值 try { js.value(o); } catch (JSONException e) { e.printStackTrace(); } } }
void writeTo(JSONStringer stringer) throws JSONException { stringer.object(); for (Map.Entry<String, Object> entry : nameValuePairs.entrySet()) { stringer.key(entry.getKey()).value(entry.getValue()); } stringer.endObject(); }
@Override protected Void doInBackground(Void... params) { try { JSONParser jsonParser = new JSONParser(LoginActivity.this); JSONStringer jsonData = new JSONStringer() .object() .key("email") .value(etForgotPass.getText().toString()) .endObject(); String[] data; data = jsonParser.sendPostReq( Constants.api_ip + Constants.api_forgot_password, jsonData.toString()); responseCode = Integer.valueOf(data[0]); if (responseCode == 200) { jObj = new JSONObject(data[1]); flag = JSONData.getBoolean(jObj, "flag"); message = JSONData.getString(jObj, "message"); } } catch (Exception e) { e.printStackTrace(); } return null; }
public static String stringWithObject(Object value) { String contentString = ""; JSONStringer js = new JSONStringer(); serialize(js, value); contentString = js.toString(); return contentString; }
@Override public void toJSONString(JSONStringer stringer) throws JSONException { super.toJSONString(stringer); stringer.key(Members.COLUMN_IDX.name()).value(m_columnIndex); stringer.key(Members.TABLE_NAME.name()).value(m_tableName); stringer.key(Members.COLUMN_NAME.name()).value(m_columnName); stringer.key(Members.COLUMN_ALIAS.name()).value(m_columnAlias); }
private void encodeBoundingBox(Extent env) throws JSONException { builder.key("bbox"); builder.array(); builder.value(env.getMinX()); builder.value(env.getMinY()); builder.value(env.getMaxX()); builder.value(env.getMaxY()); builder.endArray(); }
/** * Encodes this object as a compact JSON string, such as: * * <pre>{"query":"Pizza","locations":[94043,90210]}</pre> */ @Override public String toString() { try { JSONStringer stringer = new JSONStringer(); writeTo(stringer); return stringer.toString(); } catch (JSONException e) { return null; } }
/** * 序列化集合 * * @param js json对象 * @param collection 集合 */ private static void serializeCollect(JSONStringer js, Collection<?> collection) { try { js.array(); for (Object o : collection) { serialize(js, o); } js.endArray(); } catch (Exception e) { e.printStackTrace(); } }
/** * 序列化数组 * * @param js json对象 * @param array 数组 */ private static void serializeArray(JSONStringer js, Object array) { try { js.array(); for (int i = 0; i < Array.getLength(array); ++i) { Object o = Array.get(array, i); serialize(js, o); } js.endArray(); } catch (Exception e) { e.printStackTrace(); } }
@Override public String toJSONString() { JSONStringer stringer = new JSONStringer(); try { stringer.object(); this.toJSONString(stringer); stringer.endObject(); } catch (JSONException e) { e.printStackTrace(); System.exit(-1); } return stringer.toString(); }
/** * 生成 JSON Description Array String * * @param description Description String * @return JSON String */ @SuppressLint("DefaultLocale") public static String GenerateJSONDescription(String description) { if (description != null) { if (description.length() > 0 && !description.contains("null")) { JSONStringer jsonStringer = new JSONStringer(); try { jsonStringer.array(); for (String item : description.split("#")) { String[] part = item.split(":"); jsonStringer.object(); jsonStringer .key("id") .value( part.length > 0 ? part[0].replaceAll("(?i)bit", "").replaceFirst("^0+(?!$)", "") : ""); jsonStringer.key("value").value(part.length > 1 ? part[1] : ""); jsonStringer.endObject(); } jsonStringer.endArray(); } catch (JSONException e) { e.printStackTrace(); } return jsonStringer.toString(); } else { return ""; } } else { return ""; } }
/** * Encodes {@code data} as a JSON string. This applies quotes and any necessary character * escaping. * * @param data the string to encode. Null will be interpreted as an empty string. */ public static String quote(String data) { if (data == null) { return "\"\""; } try { JSONStringer stringer = new JSONStringer(); stringer.open(JSONStringer.Scope.NULL, ""); stringer.value(data); stringer.close(JSONStringer.Scope.NULL, JSONStringer.Scope.NULL, ""); return stringer.toString(); } catch (JSONException e) { throw new AssertionError(); } }
public String getJSONEncodedParams() { try { JSONStringer json = new JSONStringer().object(); for (String key : params.keySet()) { json.key(key).value(params.get(key)); } return URLEncoder.encode(json.endObject().toString(), "UTF-8"); } catch (Exception e) { e.printStackTrace(); } return null; }
/** * 序列化Map * * @param js json对象 * @param map map对象 */ private static void serializeMap(JSONStringer js, Map<?, ?> map) { try { js.object(); @SuppressWarnings("unchecked") Map<String, Object> valueMap = (Map<String, Object>) map; Iterator<Map.Entry<String, Object>> it = valueMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it.next(); js.key(entry.getKey()); serialize(js, entry.getValue()); } js.endObject(); } catch (Exception e) { e.printStackTrace(); } }
public String toJSONString() { final JSONStringer json = new JSONStringer(); try { if (messageParts.size() == 1) { latest().writeJson(json); } else { json.object().key("text").value("").key("extra").array(); for (final MessagePart part : messageParts) { part.writeJson(json); } json.endArray().endObject(); } } catch (final JSONException e) { throw new RuntimeException("invalid message"); } return json.toString(); }
private JSONObject send(JSONStringer data) throws UnknownHostException, IOException { Socket s = new Socket(_host, _port); s.getOutputStream().write(data.toString().getBytes()); JSONObject o = new JSONObject(new JSONTokener(s.getInputStream())); s.close(); return o; }
public String saveMap(String action, MapViewModel map) { String returnVal = null; try { // POST request to <service>/SaveCrop String s = svcUri + action; HttpPost request = new HttpPost(svcUri + action); request.setHeader("Accept", "application/json"); request.setHeader("Content-type", "application/json"); request.setHeader("User-Agent", "Fiddler"); // Build JSON string JSONStringer mapJson = new JSONStringer() .object() .key("map") .object() .key("mapid") .value(0) .key("longitude") .value(map.getLongitude()) .key("latitude") .value(map.getLatitude()) .key("field_fk") .value(map.getFieldId()) .endObject() .endObject(); StringEntity entity = new StringEntity(mapJson.toString()); request.setEntity(entity); // Send request to WCF service DefaultHttpClient httpClient = new DefaultHttpClient(); HttpResponse response = httpClient.execute(request); HttpEntity httpEntity = response.getEntity(); returnVal = EntityUtils.toString(httpEntity); } catch (Exception e) { e.printStackTrace(); } return returnVal; }
/** * @param e * @param response */ private void getError(Exception e, HttpServletResponse response) { PrintWriter print; // Do not display database or other system errors to the client final String errormessage = "A System Error Occurred, Contact the Administrator"; try { print = response.getWriter(); response.setContentType("text/javascript"); StringBuffer toPrint = new StringBuffer(); StringBuffer toPrint2 = new StringBuffer(); toPrint.append("{ \"result\":"); JSONStringer stringer = new JSONStringer(); stringer.object(); stringer.key("error"); // stringer.value(e.getClass().toString() + ":" + e.getMessage()); stringer.value(errormessage); stringer.endObject(); toPrint.append(stringer.toString()); toPrint2.append(e.getClass().toString() + ":" + e.getMessage() + "\n"); StackTraceElement[] stack = e.getStackTrace(); for (int i = 0; i < stack.length; i++) { toPrint2.append(stack[i].toString() + "\n"); } toPrint.append("}"); print.write(toPrint.toString()); logger.error(toPrint2.toString()); } catch (IOException e1) { e1.printStackTrace(); } catch (JSONException e2) { e2.printStackTrace(); } }
/** * Returns the JSON text for the wrapped JSON object or representation. * * @return The JSON text. * @throws JSONException */ private String getJsonText() throws JSONException { String result = null; if (this.jsonValue != null) { if (this.jsonValue instanceof JSONArray) { JSONArray jsonArray = (JSONArray) this.jsonValue; if (isIndenting()) { result = jsonArray.toString(getIndentingSize()); } else { result = jsonArray.toString(); } } else if (this.jsonValue instanceof JSONObject) { JSONObject jsonObject = (JSONObject) this.jsonValue; if (isIndenting()) { result = jsonObject.toString(getIndentingSize()); } else { result = jsonObject.toString(); } } else if (this.jsonValue instanceof JSONStringer) { JSONStringer jsonStringer = (JSONStringer) this.jsonValue; result = jsonStringer.toString(); } else if (this.jsonValue instanceof JSONTokener) { JSONTokener jsonTokener = (JSONTokener) this.jsonValue; result = jsonTokener.toString(); } } else if (this.jsonRepresentation != null) { try { result = this.jsonRepresentation.getText(); } catch (IOException e) { throw new JSONException(e); } } return result; }
/** * 序列化对象 * * @param js json对象 * @param obj 待序列化对象 */ private static void serializeObject(JSONStringer js, Object obj) { try { js.object(); Class<? extends Object> objClazz = obj.getClass(); Method[] methods = objClazz.getDeclaredMethods(); Field[] fields = objClazz.getDeclaredFields(); for (Field field : fields) { try { String fieldType = field.getType().getSimpleName(); String fieldGetName = parseMethodName(field.getName(), "get"); if (!haveMethod(methods, fieldGetName)) { continue; } Method fieldGetMet = objClazz.getMethod(fieldGetName, new Class[] {}); Object fieldVal = fieldGetMet.invoke(obj, new Object[] {}); String result = null; if ("Date".equals(fieldType)) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US); result = sdf.format((Date) fieldVal); } else { if (null != fieldVal) { result = String.valueOf(fieldVal); } } js.key(field.getName()); serialize(js, result); } catch (Exception e) { continue; } } js.endObject(); } catch (Exception e) { e.printStackTrace(); } }
/** * Main method to encode geometries. * * @param o The object to encode: It can be one of: <code>Feature</code> <code>FeatureCollection * </code> <code>Point</code> <code>MultiPoint</code> * @return The GeoJSON String with the object encoded * @throws JSONException */ public String encode(Object o) throws JSONException { if (o instanceof Feature) { encodeFeature((Feature) o); } else if (o instanceof FeatureCollection) { encodeFeatureCollection((FeatureCollection) o); } else if (o instanceof Point) { encodeGeometry((Point) o); } else if (o instanceof MultiPoint) { encodeGeometry((MultiPoint) o); } else { // TODO // throw exception; } return builder.toString(); }
public String marshal() throws JSONException { JSONStringer stringer = new JSONStringer(); stringer.object(); stringer.key("scope").value(this.scope); if (this.callbackUrl != null) { stringer.key("callbackUrl").value(this.callbackUrl); } if (this.returnUrl != null) { stringer.key("returnUrl").value(this.returnUrl); } stringer.key("deadline").value(this.deadline); stringer.endObject(); return stringer.toString(); }
private void encodeGeometry(IGeometry g) throws JSONException { builder.object(); builder.key("type"); String name = getGeometryName(g); if (name != null) { builder.value(name); if (name.compareTo("Point") == 0) { builder.key("coordinates"); encodeCoordinate((Point) g); } else if (name.compareTo("MultiPoint") == 0) { MultiPoint mp = (MultiPoint) g; builder.key("coordinates"); builder.array(); for (int i = 0; i < mp.getNumPoints(); i++) { encodeCoordinate(((MultiPoint) g).getPoint(i)); } builder.endArray(); } } builder.endObject(); }
private void encodeFeatureCollection(FeatureCollection c) throws JSONException { builder.object(); builder.key("type").value("FeatureCollection"); builder.key("features"); builder.array(); Enumeration e = c.getFeatures().elements(); while (e.hasMoreElements()) { Feature f = (Feature) e.nextElement(); encodeFeature(f); } builder.endArray(); builder.endObject(); }
private void encodeFeature(Feature f) throws JSONException { builder.object(); builder.key("type").value("Feature"); // builder.key("id").value(f.getID()); builder.key("geometry"); IGeometry g = f.getGeometry(); encodeGeometry(g); builder.key("properties"); builder.object(); // TODO encode Feature // f.toJSON(builder); builder.endObject(); builder.endObject(); }
@Override public void generateJson(String prefix, PrintWriter pw, VWorkspace vWorkspace) { Workspace workspace = vWorkspace.getWorkspace(); alignment = AlignmentManager.Instance().getAlignment(workspace.getId(), worksheetId); SemanticTypes types = worksheet.getSemanticTypes(); Map<String, ColumnNode> hNodeIdTocolumnNodeMap = createColumnNodeMap(); Map<String, SemanticTypeNode> hNodeIdToDomainNodeMap = createDomainNodeMap(); JSONStringer jsonStr = new JSONStringer(); try { JSONWriter writer = jsonStr.object(); writer.key("worksheetId").value(worksheetId).key("updateType").value("SemanticTypesUpdate"); writer.key(JsonKeys.Types.name()); writer.array(); // Iterate through all the columns for (HNodePath path : worksheet.getHeaders().getAllPaths()) { HNode node = path.getLeaf(); String nodeId = node.getId(); writer.object(); // Check if a semantic type exists for the HNode SemanticType type = types.getSemanticTypeForHNodeId(nodeId); if (type != null && type.getConfidenceLevel() != SemanticType.ConfidenceLevel.Low) { writer .key(JsonKeys.HNodeId.name()) .value(type.getHNodeId()) .key(JsonKeys.SemanticTypesArray.name()) .array(); ColumnNode alignmentColumnNode = hNodeIdTocolumnNodeMap.get(type.getHNodeId()); SemanticTypeNode domainNode = hNodeIdToDomainNodeMap.get(type.getHNodeId()); if (alignmentColumnNode == null || domainNode == null) { logger.error( "Column node or domain node not found in alignment." + " (This should not happen conceptually!):" + type); continue; } // Add the primary semantic type writer .object() .key(JsonKeys.Origin.name()) .value(type.getOrigin().name()) .key(JsonKeys.ConfidenceLevel.name()) .value(type.getConfidenceLevel().name()) .key(JsonKeys.isPrimary.name()) .value(true); // Add the RDF literal type to show in the text box String rdfLiteralType = alignmentColumnNode.getRdfLiteralType() == null ? "" : alignmentColumnNode.getRdfLiteralType().getDisplayName(); String language = alignmentColumnNode.getLanguage() == null ? "" : alignmentColumnNode.getLanguage(); writer.key(JsonKeys.rdfLiteralType.name()).value(rdfLiteralType); writer.key(JsonKeys.language.name()).value(language); // String domainDisplayLabel = (domainNode.getLabel().getPrefix() != null && // (!domainNode.getLabel().getPrefix().equals(""))) ? // (domainNode.getLabel().getPrefix() + ":" + domainNode.getLocalId()) : // domainNode.getLocalId(); if (!type.isClass()) { writer .key(JsonKeys.FullType.name()) .value(type.getType().getUri()) .key(JsonKeys.DisplayLabel.name()) .value(type.getType().getDisplayName()) .key(JsonKeys.DisplayRDFSLabel.name()) .value(type.getType().getRdfsLabel()) .key(JsonKeys.DisplayRDFSComment.name()) .value(type.getType().getRdfsComment()) .key(JsonKeys.DomainId.name()) .value(domainNode.getId()) .key(JsonKeys.DomainUri.name()) .value(domainNode.getUri()) .key(JsonKeys.DisplayDomainLabel.name()) .value(domainNode.getDisplayId()) .key(JsonKeys.DomainRDFSLabel.name()) .value(domainNode.getRdfsLabel()) .key(JsonKeys.DomainRDFSComment.name()) .value(domainNode.getRdfsComment()); } else { writer .key(JsonKeys.FullType.name()) .value(domainNode.getId()) .key(JsonKeys.DisplayLabel.name()) .value(domainNode.getDisplayId()) .key(JsonKeys.DisplayRDFSLabel.name()) .value(domainNode.getRdfsLabel()) .key(JsonKeys.DisplayRDFSComment.name()) .value(domainNode.getRdfsComment()) .key(JsonKeys.DomainId.name()) .value("") .key(JsonKeys.DomainUri.name()) .value("") .key(JsonKeys.DisplayDomainLabel.name()) .value("") .key(JsonKeys.DomainRDFSLabel.name()) .value("") .key(JsonKeys.DomainRDFSComment.name()) .value(""); } // Mark the special properties writer .key(JsonKeys.isMetaProperty.name()) .value(isMetaProperty(type.getType(), alignmentColumnNode)); writer.endObject(); // Iterate through the synonym semantic types SynonymSemanticTypes synTypes = types.getSynonymTypesForHNodeId(nodeId); if (synTypes != null) { for (SemanticType synType : synTypes.getSynonyms()) { writer .object() .key(JsonKeys.HNodeId.name()) .value(synType.getHNodeId()) .key(JsonKeys.FullType.name()) .value(synType.getType().getUri()) .key(JsonKeys.Origin.name()) .value(synType.getOrigin().name()) .key(JsonKeys.ConfidenceLevel.name()) .value(synType.getConfidenceLevel().name()) .key(JsonKeys.DisplayLabel.name()) .value(synType.getType().getDisplayName()) .key(JsonKeys.DisplayRDFSLabel.name()) .value(synType.getType().getRdfsLabel()) .key(JsonKeys.DisplayRDFSComment.name()) .value(synType.getType().getRdfsComment()) .key(JsonKeys.isPrimary.name()) .value(false); if (!synType.isClass()) { writer .key(JsonKeys.DomainUri.name()) .value(synType.getDomain().getUri()) .key(JsonKeys.DomainId.name()) .value("") .key(JsonKeys.DisplayDomainLabel.name()) .value(synType.getDomain().getDisplayName()) .key(JsonKeys.DomainRDFSLabel.name()) .value(synType.getDomain().getRdfsLabel()) .key(JsonKeys.DomainRDFSComment.name()) .value(synType.getDomain().getRdfsComment()); } else { writer .key(JsonKeys.DomainId.name()) .value("") .key(JsonKeys.DomainUri.name()) .value("") .key(JsonKeys.DisplayDomainLabel.name()) .value("") .key(JsonKeys.DomainRDFSLabel.name()) .value("") .key(JsonKeys.DomainRDFSComment.name()) .value(""); } writer.endObject(); } } writer.endArray(); } else { writer.key(JsonKeys.HNodeId.name()).value(nodeId); writer.key(JsonKeys.SemanticTypesArray.name()).array().endArray(); } writer.endObject(); } writer.endArray(); writer.endObject(); pw.print(writer.toString()); } catch (JSONException e) { logger.error("Error occured while writing to JSON!", e); } }
/** * 将对象转换成Json字符串 * * @param obj * @return json类型字符串 */ public static String toJSON(Object obj) { JSONStringer js = new JSONStringer(); serialize(js, obj); return js.toString(); }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String q = request.getParameter("q"); String simple = request.getParameter("simple"); String test = request.getParameter("test"); boolean isTest = false; if (test != null && test.equals("true")) { isTest = true; } PrintWriter w = response.getWriter(); if (q != null) { // 지원사항을 알려준다. response.setCharacterEncoding("utf-8"); response.setStatus(HttpServletResponse.SC_OK); response.setContentType("application/json;"); String[] collectionNameList = service.getCollectionNameList(); boolean[] status = service.getCollectionStatus(); JSONStringer stringer = new JSONStringer(); try { stringer.array(); if (collectionNameList != null) { for (int i = 0; i < collectionNameList.length; i++) { stringer.object().key("name").value(collectionNameList[i]); if (isTest) { stringer.key("status").value(true); } else { stringer.key("status").value(status[i]); } stringer.endObject(); } } stringer.endArray(); // logger.debug("stringer = "+stringer); w.println(stringer.toString()); } catch (JSONException e) { throw new ServletException("JSONException 발생", e); } } else { String callback = request.getParameter("jsoncallback"); response.setCharacterEncoding("utf-8"); response.setStatus(HttpServletResponse.SC_OK); if (RESULT_TYPE == JSONP_TYPE) { response.setContentType("text/javascript;"); } else { response.setContentType("application/json;"); } String[] collectionNameList = service.getCollectionNameList(); boolean[] status = service.getCollectionStatus(); RealTimeCollectionStatistics[] statistics = service.getCollectionStatisticsList(); RealTimeCollectionStatistics globalCollectionStatistics = service.getGlobalCollectionStatistics(); // 결과생성 JSONStringer stringer = new JSONStringer(); try { // // 간략정보 // if (simple != null) { if (isTest) { stringer.object(); int hit = r.nextInt(30) + 1; stringer.key("h").value(r.nextInt(30) + 1); stringer.key("fh").value(r.nextInt(hit > 5 ? 5 : hit)); int ta = r.nextInt(50) + 1; stringer.key("ta").value(ta + 1); stringer.key("tx").value(ta + r.nextInt(20) + 1); stringer.endObject(); } else { // 컬렉션 통합 정보를 리턴한다. // if(collectionNameList != null){ // int hit = 0; // int failHit = 0; // int avgTime = 0; // int maxTime = 0; // int count = 0; // for (int i = 0; i < collectionNameList.length; i++) { // if(status[i]){ // count++; // hit += statistics[i].getHitPerUnitTime(); // failHit += statistics[i].getFailHitPerUnitTime(); // avgTime += statistics[i].getMeanResponseTime(); // if(statistics[i].getMaxResponseTime() > maxTime){ // maxTime = statistics[i].getMaxResponseTime(); // } // } // } // } stringer.object(); stringer.key("h").value(globalCollectionStatistics.getHitPerUnitTime()); stringer.key("fh").value(globalCollectionStatistics.getFailHitPerUnitTime()); stringer.key("ach").value(globalCollectionStatistics.getAccumulatedHit()); stringer.key("acfh").value(globalCollectionStatistics.getAccumulatedFailHit()); stringer.key("ta").value(globalCollectionStatistics.getMeanResponseTime()); stringer.key("tx").value(globalCollectionStatistics.getMaxResponseTime()); stringer.endObject(); } } else { // // 컬렉션별 상세정보 // stringer.array(); if (collectionNameList != null) { for (int i = 0; i < collectionNameList.length; i++) { if (status[i]) { stringer.object().key("c").value(collectionNameList[i]); if (isTest) { int hit = r.nextInt(10) + 1; stringer.key("h").value(hit); stringer.key("fh").value(r.nextInt(hit > 3 ? 3 : hit)); stringer.key("ta").value(r.nextInt(100) + 1); stringer.key("tx").value(r.nextInt(50) + r.nextInt(20) + 1); } else { stringer.key("h").value(statistics[i].getHitPerUnitTime()); stringer.key("fh").value(statistics[i].getFailHitPerUnitTime()); stringer.key("ach").value(statistics[i].getAccumulatedHit()); stringer.key("acfh").value(statistics[i].getAccumulatedFailHit()); stringer.key("ta").value(statistics[i].getMeanResponseTime()); stringer.key("tx").value(statistics[i].getMaxResponseTime()); } stringer.endObject(); } } } stringer.endArray(); } } catch (JSONException e) { throw new ServletException("JSONException 발생", e); } // JSONP는 데이터 앞뒤로 function명으로 감싸준다. if (RESULT_TYPE == JSONP_TYPE) { w.write(callback + "("); } // 정보를 보내준다. w.write(stringer.toString()); if (RESULT_TYPE == JSONP_TYPE) { w.write(");"); } } w.close(); }
// ***************************************************************************** // Save Contact using HTTP PUT method with singleContactUrl. // If Id is zero(0) a new Contact will be added. // If Id is non-zero an existing Contact will be updated. // HTTP POST could be used to add a new Contact but the ContactService knows // an Id of zero means a new Contact so in this case the HTTP PUT is used. // ***************************************************************************** public Integer SaveContact(Contact saveContact) { Integer statusCode = 0; HttpResponse response; try { boolean isValid = true; // Data validation goes here if (isValid) { // POST request to <service>/SaveVehicle HttpPut request = new HttpPut(singleContactUrl + saveContact.getId()); request.setHeader("User-Agent", "dev.ronlemire.contactClient"); request.setHeader("Accept", "application/json"); request.setHeader("Content-type", "application/json"); // Build JSON string JSONStringer contact = new JSONStringer() .object() .key("Id") .value(Integer.parseInt(saveContact.getId())) .key("FirstName") .value(saveContact.getFirstName()) .key("LastName") .value(saveContact.getLastName()) .key("Email") .value(saveContact.getEmail()) .endObject(); StringEntity entity = new StringEntity(contact.toString()); request.setEntity(entity); // Send request to WCF service DefaultHttpClient httpClient = new DefaultHttpClient(); response = httpClient.execute(request); Log.d("WebInvoke", "Saving : " + response.getStatusLine().getStatusCode()); // statusCode = // Integer.toString(response.getStatusLine().getStatusCode()); statusCode = response.getStatusLine().getStatusCode(); if (saveContact.getId().equals("0")) { // New Contact.Id is in buffer HttpEntity responseEntity = response.getEntity(); char[] buffer = new char[(int) responseEntity.getContentLength()]; InputStream stream = responseEntity.getContent(); InputStreamReader reader = new InputStreamReader(stream); reader.read(buffer); stream.close(); statusCode = Integer.parseInt(new String(buffer)); } else { statusCode = response.getStatusLine().getStatusCode(); } } } catch (Exception e) { e.printStackTrace(); } return statusCode; }
public JSONStringer generateDeviceJSON(Context context, boolean isFirst, String userAccount) { LocationUtils location = new LocationUtils(context); JSONStringer deviceJson = new JSONStringer(); try { deviceJson.object(); deviceJson.key("deviceid"); // deviceJson.value(getsDeviceIdSHA1()); deviceJson.value(getPseudoID()); deviceJson.key("useraccount"); deviceJson.value(userAccount); // /TODO deviceJson.key("devicename"); deviceJson.value(sDeviceManufacturer); deviceJson.key("devicetype"); deviceJson.value("1"); // 1手机 deviceJson.key("deviceos"); deviceJson.value(2000); // Android deviceJson.key("devicemac"); deviceJson.value(WLAN_MAC); deviceJson.key("devicephonenum"); deviceJson.value(TEL); deviceJson.key("deviceislock"); deviceJson.value(0); deviceJson.key("deviceisdel"); deviceJson.value(0); deviceJson.key("deviceinittime"); Date date = new Date(); deviceJson.value(date.getTime()); // TODO 日期格式 long型 deviceJson.key("devicevalidperiod"); deviceJson.value(365); // //TODO 暂定365天有效。服务器需要支持修改 deviceJson.key("deviceisillegal"); deviceJson.value(0); deviceJson.key("deviceisactive"); deviceJson.value(isFirst ? 1 : 0); // 第一台设备不做peer校验,直接注册 deviceJson.key("deviceislogout"); deviceJson.value(0); deviceJson.key("deviceeaster"); deviceJson.value(userAccount); deviceJson.key("bakstr1"); deviceJson.value(location.getLocation()); // TODO 目前是经度+空格+纬度 deviceJson.endObject(); Log.d(TAG, "JSON-----" + deviceJson.toString()); } catch (JSONException e) { e.printStackTrace(); } return deviceJson; }