List of usage examples for com.google.gson JsonObject JsonObject
JsonObject
From source file:ca.ualberta.cmput301w14t08.geochan.json.LocationJsonConverter.java
License:Apache License
/** * Serializes data from a Location into JSON format. * /*from w w w . ja v a 2 s.com*/ * (Some of this code is taken from a stackOverflow user * Brian Roach, for details, see: http://stackoverflow.com/a/13997920) * * @param location * the Location to serialize * @param type * the Type * @param jsc * the JSON serialization context * * @return A JsonElement representing the serialized Location. * */ @Override public JsonElement serialize(Location location, Type type, JsonSerializationContext jsc) { JsonObject jo = new JsonObject(); jo.addProperty("mProvider", location.getProvider()); jo.addProperty("mAccuracy", location.getAccuracy()); jo.addProperty("latitude", location.getLatitude()); jo.addProperty("longitude", location.getLongitude()); return jo; }
From source file:ca.ualberta.cmput301w14t08.geochan.json.ThreadCommentJsonConverter.java
License:Apache License
/** * Serializes a ThreadComment object into JSON format. * /*from w w w .j a va 2 s. co m*/ * @param thread the ThreadComment to serialize. * @param type the Type * @param context the JsonSerializationContext * * @return A JsonElement representing the serialized ThreadComment. */ @Override public JsonElement serialize(ThreadComment thread, Type type, JsonSerializationContext context) { JsonObject object = new JsonObject(); object.addProperty("title", thread.getTitle()); object.addProperty("threadDate", thread.getThreadDate().getTime()); object.addProperty("hasImage", thread.getBodyComment().hasImage()); object.addProperty("id", thread.getId()); if (thread.getBodyComment().getLocation() != null) { object.addProperty("location", thread.getBodyComment().getLocation().getLatitude() + "," + thread.getBodyComment().getLocation().getLongitude()); if (thread.getBodyComment().getLocation().getLocationDescription() != null) { object.addProperty("locationDescription", thread.getBodyComment().getLocation().getLocationDescription()); } } else { object.addProperty("location", "-999,-999"); } object.addProperty("user", thread.getBodyComment().getUser()); object.addProperty("hash", thread.getBodyComment().getHash()); object.addProperty("textPost", thread.getBodyComment().getTextPost()); if (thread.getBodyComment().hasImage()) { Bitmap bitmapThumb = thread.getBodyComment().getImageThumb(); /* * http://stackoverflow.com/questions/9224056/android-bitmap-to-base64 * -string */ ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); bitmapThumb.compress(Bitmap.CompressFormat.JPEG, 90, byteArrayOutputStream); byte[] byteThumbArray = byteArrayOutputStream.toByteArray(); String encodedThumb = Base64.encodeToString(byteThumbArray, Base64.NO_WRAP); object.addProperty("imageThumbnail", encodedThumb); } return object; }
From source file:ca.ualberta.cmput301w14t08.geochan.json.ThreadCommentOfflineJsonConverter.java
License:Apache License
/** * Serializes a ThreadComment object into JSON format. * // ww w. j a v a 2 s. c om * @param thread The ThreadComment to serialize. * @param type The Type. * @param context The JsonSerializationContext * * @return A JsonElement representing the serialized ThreadComment. */ @Override public JsonElement serialize(ThreadComment thread, Type type, JsonSerializationContext context) { JsonObject object = new JsonObject(); object.addProperty("title", thread.getTitle()); object.addProperty("threadDate", thread.getThreadDate().getTime()); object.addProperty("hasImage", thread.getBodyComment().hasImage()); object.addProperty("id", thread.getId()); if (thread.getBodyComment().getLocation() != null) { object.addProperty("location", thread.getBodyComment().getLocation().getLatitude() + "," + thread.getBodyComment().getLocation().getLongitude()); if (thread.getBodyComment().getLocation().getLocationDescription() != null) { object.addProperty("locationDescription", thread.getBodyComment().getLocation().getLocationDescription()); } } else { object.addProperty("location", "-999,-999"); } object.addProperty("user", thread.getBodyComment().getUser()); object.addProperty("hash", thread.getBodyComment().getHash()); object.addProperty("textPost", thread.getBodyComment().getTextPost()); if (thread.getBodyComment().hasImage()) { Bitmap bitmapThumb = thread.getBodyComment().getImageThumb(); /* * http://stackoverflow.com/questions/9224056/android-bitmap-to-base64 * -string */ ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); bitmapThumb.compress(Bitmap.CompressFormat.JPEG, 90, byteArrayOutputStream); byte[] byteThumbArray = byteArrayOutputStream.toByteArray(); String encodedThumb = Base64.encodeToString(byteThumbArray, Base64.NO_WRAP); object.addProperty("imageThumbnail", encodedThumb); } recursiveSerialize(object, thread.getBodyComment(), thread.getBodyComment().getChildren()); // Serialize all the images in the thread. return object; }
From source file:ca.ualberta.CMPUT301W15T06.GsonAdapter.java
License:Apache License
@Override public JsonElement serialize(T src, Type type, JsonSerializationContext context) { // TODO Auto-generated method stub JsonObject retValue = new JsonObject(); String className = src.getClass().getCanonicalName(); retValue.addProperty(CLASSNAME, className); JsonElement elem = context.serialize(src); retValue.add(INSTANCE, elem);/* w ww. jav a 2 s . co m*/ return retValue; }
From source file:ca.ualberta.cs.scandaloutraveltracker.mappers.UserMapper.java
License:Apache License
@Override public JsonElement serialize(Location location, Type arg1, JsonSerializationContext arg2) { JsonObject jo = new JsonObject(); jo.addProperty("provider", location.getProvider()); jo.addProperty("accuracy", location.getAccuracy()); jo.addProperty("longitude", location.getLongitude()); jo.addProperty("latitude", location.getLatitude()); return jo;/* w w w. ja v a2 s . c o m*/ }
From source file:ca.ualberta.cs.team1travelexpenseapp.gsonUtils.RuntimeTypeAdapterFactory.java
License:Apache License
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) { if (type.getRawType() != baseType) { return null; }//w w w. j a v a2s . c o m final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<String, TypeAdapter<?>>(); final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<Class<?>, TypeAdapter<?>>(); for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) { TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue())); labelToDelegate.put(entry.getKey(), delegate); subtypeToDelegate.put(entry.getValue(), delegate); } return new TypeAdapter<R>() { @Override public R read(JsonReader in) throws IOException { JsonElement jsonElement = Streams.parse(in); JsonElement labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName); if (labelJsonElement == null) { throw new JsonParseException("cannot deserialize " + baseType + " because it does not define a field named " + typeFieldName); } String label = labelJsonElement.getAsString(); @SuppressWarnings("unchecked") // registration requires that subtype extends T TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label); if (delegate == null) { throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label + "; did you forget to register a subtype?"); } return delegate.fromJsonTree(jsonElement); } @Override public void write(JsonWriter out, R value) throws IOException { Class<?> srcType = value.getClass(); String label = subtypeToLabel.get(srcType); @SuppressWarnings("unchecked") // registration requires that subtype extends T TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType); if (delegate == null) { throw new JsonParseException( "cannot serialize " + srcType.getName() + "; did you forget to register a subtype?"); } JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject(); if (jsonObject.has(typeFieldName)) { throw new JsonParseException("cannot serialize " + srcType.getName() + " because it already defines a field named " + typeFieldName); } JsonObject clone = new JsonObject(); clone.add(typeFieldName, new JsonPrimitive(label)); for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) { clone.add(e.getKey(), e.getValue()); } Streams.write(clone, out); } }; }
From source file:callAPIHelper.CallApiHelper.java
public String CallAPIForURL(DataURL dataUrl, RowDataFromFile data) throws UnsupportedEncodingException, IOException { String code = ""; String POST_URL = dataUrl.getUrl(); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(POST_URL); httpPost.setHeader("Content-type", dataUrl.getContentType()); httpPost.setHeader("Accept-Content Type", dataUrl.getAcceptType()); JsonObject jdata = data.getData();/* ww w. j ava 2s.co m*/ System.out.println("data post: " + jdata.toString()); httpPost.setEntity(new StringEntity(jdata.toString())); CloseableHttpResponse httpResponse = httpClient.execute(httpPost); if (httpResponse.getStatusLine().getStatusCode() == 200) { BufferedReader reader = new BufferedReader( new InputStreamReader(httpResponse.getEntity().getContent())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = reader.readLine()) != null) { response.append(inputLine); } reader.close(); JsonObject jresp = new JsonObject(); jresp = gson.fromJson(response.toString(), JsonObject.class); System.out.println("data resp: " + jresp.toString()); // JsonElement je = jresp.get("code"); code = jresp.toString(); } else { System.out.println("API Fail status code = " + httpResponse.getStatusLine().getStatusCode()); // return new DataResponseWithdrawFunds();/ code = "-1"; } return code; }
From source file:carsharing.starter.automotive.iot.ibm.com.mobilestarterapp.AnalyzeMyDriving.java
License:Open Source License
public void sendLocation(final Location location) { if (connectDeviceClient()) { final GregorianCalendar cal = new GregorianCalendar(); final TimeZone gmt = TimeZone.getTimeZone("GMT"); cal.setTimeZone(gmt);// w w w. j av a2 s .c o m final SimpleDateFormat formattedCal = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); formattedCal.setCalendar(cal); final String timestamp = formattedCal.format(cal.getTime()); final double speed = Math.max(0.0, location.getSpeed() * 60 * 60 / 1000); final double longitude = location.getLongitude(); final double latitude = location.getLatitude(); final String mobileAppDeviceId = FirstPage.mobileAppDeviceId; final String status = tripID != null ? "Unlocked" : "Locked"; if (tripID == null) { // this trip should be completed, so lock device now userUnlocked = false; } final JsonObject event = new JsonObject(); final JsonObject data = new JsonObject(); event.add("d", data); data.addProperty("trip_id", tripID); data.addProperty("speed", speed); data.addProperty("lng", longitude); data.addProperty("lat", latitude); data.addProperty("ts", timestamp); data.addProperty("id", mobileAppDeviceId); data.addProperty("status", status); final ActionBar supportActionBar = ((AppCompatActivity) getActivity()).getSupportActionBar(); if (deviceClient.publishEvent("sensorData", event, 0)) { Log.d("MQTT", "publish event " + event.toString()); supportActionBar.setTitle(speedMessage + " - Data sent (" + (++transmissionCount) + ")"); } else { Log.d("MQTT", "ERROR in publishing event " + event.toString()); supportActionBar.setTitle("Data Transmission Error."); } } }
From source file:cashPR.AddUpdateCashVoucher.java
private JsonObject saveVoucher(ArrayList<CashPaymentReceiptModel> detail) { final JsonObject jResultObj = new JsonObject(); Connection dataConnection = null; if (dataConnection == null) { dataConnection = helper.getConnMpAdmin(); }//from w ww.ja va2s. co m if (dataConnection != null) { try { dataConnection.setAutoCommit(false); String sql = null; PreparedStatement psLocal = null; if (detail.get(0).getRef_no().equalsIgnoreCase("")) { sql = "INSERT INTO CPRHD (VDATE, TOT_BAL, AC_CD, USER_ID, CTYPE, branch_cd,REF_NO) " + "VALUES (?, ?, ?, ?, ?, ?, ?)"; // ref_no = lb.generateCPNo(type); if (detail.get(0).getType() == 0) { detail.get(0).setRef_no(lb.generateKey(dataConnection, "CPRHD", "REF_NO", "CP", 7)); } else { detail.get(0).setRef_no(lb.generateKey(dataConnection, "CPRHD", "REF_NO", "CR", 7)); } } else if (!detail.get(0).getRef_no().equalsIgnoreCase("")) { if (detail.get(0).getType() == 0) { CashPaymentUpdate cp = new CashPaymentUpdate(); cp.deleteEntry(dataConnection, detail.get(0).getRef_no()); } else if (detail.get(0).getType() == 1) { CashReciept cr = new CashReciept(); cr.deleteEntry(dataConnection, detail.get(0).getRef_no()); } sql = "DELETE FROM CPRDT WHERE REF_NO='" + detail.get(0).getRef_no() + "'"; psLocal = dataConnection.prepareStatement(sql); psLocal.executeUpdate(); sql = "DELETE FROM payment WHERE REF_NO='" + detail.get(0).getRef_no() + "'"; psLocal = dataConnection.prepareStatement(sql); psLocal.executeUpdate(); sql = "UPDATE CPRHD SET VDATE=?, TOT_BAL=?, AC_CD=?, USER_ID=?, CTYPE=?, " + "EDIT_NO=EDIT_NO+1, TIME_STAMP=CURRENT_TIMESTAMP,branch_cd=? WHERE REF_NO=?"; } psLocal = dataConnection.prepareStatement(sql); psLocal.setString(1, detail.get(0).getVdate()); psLocal.setDouble(2, detail.get(0).getTot_amt()); psLocal.setString(3, detail.get(0).getAc_cd()); psLocal.setString(4, detail.get(0).getUser_id()); psLocal.setInt(5, detail.get(0).getType()); psLocal.setString(6, detail.get(0).getBranch_cd()); psLocal.setString(7, detail.get(0).getRef_no()); psLocal.executeUpdate(); sql = "Update CPRHD set INIT_TIMESTAMP = TIME_STAMP where ref_no='" + detail.get(0).getRef_no() + "'"; psLocal = dataConnection.prepareStatement(sql); psLocal.executeUpdate(); sql = "INSERT INTO CPRDT (SR_NO, DOC_REF_NO, BAL, REMARK, REF_NO) " + "VALUES (?, ?, ?, ?, ?)"; psLocal = dataConnection.prepareStatement(sql); for (int i = 0; i < detail.size(); i++) { { psLocal.setInt(1, i + 1); psLocal.setString(2, detail.get(i).getDoc_ref_no()); psLocal.setDouble(3, detail.get(i).getAmt()); psLocal.setString(4, detail.get(i).getRemark()); psLocal.setString(5, detail.get(0).getRef_no()); psLocal.executeUpdate(); sql = "INSERT INTO PAYMENT (CASH_AMT, BANK_CD, BANK_NAME, BANK_BRANCH, CHEQUE_NO, CHEQUE_DATE, BANK_AMT, CARD_NAME, CARD_AMT, REF_NO,USER_ID,vou_date)" + " VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"; PreparedStatement pstLocal = dataConnection.prepareStatement(sql); if (detail.get(i).getType() == 0) { pstLocal.setDouble(1, detail.get(i).getAmt() * -1); } else { pstLocal.setDouble(1, detail.get(i).getAmt() * 1); } pstLocal.setString(2, ""); pstLocal.setString(3, ""); pstLocal.setString(4, ""); pstLocal.setString(5, ""); pstLocal.setString(6, null); pstLocal.setDouble(7, 0.00); pstLocal.setString(8, ""); pstLocal.setDouble(9, 0.00); pstLocal.setString(10, detail.get(0).getRef_no()); pstLocal.setString(11, detail.get(i).getUser_id()); pstLocal.setString(12, detail.get(i).getVdate()); pstLocal.executeUpdate(); } } if (detail.get(0).getType() == 0) { CashPaymentUpdate cp = new CashPaymentUpdate(); cp.addEntry(dataConnection, detail.get(0).getRef_no()); } else if (detail.get(0).getType() == 1) { CashReciept cr = new CashReciept(); cr.addEntry(dataConnection, detail.get(0).getRef_no()); } dataConnection.commit(); dataConnection.setAutoCommit(true); jResultObj.addProperty("result", 1); jResultObj.addProperty("Cause", "success"); } catch (SQLNonTransientConnectionException ex1) { ex1.printStackTrace(); jResultObj.addProperty("result", -1); jResultObj.addProperty("Cause", "Server is down"); } catch (SQLException ex) { ex.printStackTrace(); jResultObj.addProperty("result", -1); jResultObj.addProperty("Cause", ex.getMessage()); try { dataConnection.rollback(); dataConnection.setAutoCommit(true); } catch (Exception e) { } } } return jResultObj; }
From source file:cashPR.DeleteCashBill.java
private JsonObject saveVoucher(String ref_no, int type) { final JsonObject jResultObj = new JsonObject(); Connection dataConnection = null; if (dataConnection == null) { dataConnection = helper.getConnMpAdmin(); }// w w w . j av a 2 s. c o m if (dataConnection != null) { try { String sql = "SELECT doc_ref_no FROM billadjst WHERE dr_doc_ref_no='" + ref_no + "' OR cr_doc_ref_no='" + ref_no + "'"; PreparedStatement pstLocal = dataConnection.prepareStatement(sql); ResultSet rsLocal = pstLocal.executeQuery(); if (rsLocal.next()) { jResultObj.addProperty("result", -1); jResultObj.addProperty("Cause", "Voucher is in adjustment process"); } else { dataConnection.setAutoCommit(false); PreparedStatement psLocal = null; if (type == 0) { CashPaymentUpdate cp = new CashPaymentUpdate(); cp.deleteEntry(dataConnection, ref_no); } else if (type == 1) { CashReciept cr = new CashReciept(); cr.deleteEntry(dataConnection, ref_no); } sql = "DELETE FROM CPRDT WHERE REF_NO='" + ref_no + "'"; psLocal = dataConnection.prepareStatement(sql); psLocal.executeUpdate(); sql = "DELETE FROM payment WHERE REF_NO='" + ref_no + "'"; psLocal = dataConnection.prepareStatement(sql); psLocal.executeUpdate(); sql = "delete from CPRHD WHERE REF_NO=?"; psLocal = dataConnection.prepareStatement(sql); psLocal.setString(1, ref_no); psLocal.executeUpdate(); dataConnection.commit(); dataConnection.setAutoCommit(true); jResultObj.addProperty("result", 1); jResultObj.addProperty("Cause", "success"); } } catch (SQLNonTransientConnectionException ex1) { ex1.printStackTrace(); jResultObj.addProperty("result", -1); jResultObj.addProperty("Cause", "Server is down"); } catch (SQLException ex) { ex.printStackTrace(); jResultObj.addProperty("result", -1); jResultObj.addProperty("Cause", ex.getMessage()); try { dataConnection.rollback(); dataConnection.setAutoCommit(true); } catch (Exception e) { } } } return jResultObj; }