List of usage examples for com.google.gson JsonNull INSTANCE
JsonNull INSTANCE
To view the source code for com.google.gson JsonNull INSTANCE.
Click Source Link
From source file:org.mobicents.servlet.restcomm.http.converter.TranscriptionConverter.java
License:Open Source License
private void writeTranscriptionText(final String transcriptionText, final JsonObject object) { if (transcriptionText != null) { object.addProperty("transcription_text", transcriptionText); } else {/*w ww . j a v a 2s .com*/ object.add("transcription_text", JsonNull.INSTANCE); } }
From source file:org.mobicents.servlet.sip.restcomm.http.converter.ApplicationConverter.java
License:Open Source License
private void writeSmsStatusCallback(final URI smsStatusCallback, final JsonObject object) { if (smsStatusCallback != null) { object.addProperty("sms_status_callback", smsStatusCallback.toString()); } else {//from w w w . j a va2 s . c o m object.add("sms_status_callback", JsonNull.INSTANCE); } }
From source file:org.opendatakit.tables.utils.OutputUtil.java
License:Apache License
/** * Gets a string containing information necessary for the data object for this * particular table. The object is something like the following:<br> * { {@link #DATA_KEY_IN_COLLECTION_MODE}: boolean, {@link #DATA_KEY_COUNT}: * int, {@link #DATA_KEY_COLLECTION_SIZE}: Array, (an array of ints) * {@link #DATA_KEY_IS_INDEXED}: boolean, {@link #DATA_KEY_DATA: Array, (2d, * array of rows) {@link #DATA_KEY_COLUMNS}: {elementKey: string, ...}, * {@link #DATA_KEY_ELEMENT_KEY_TO_PATH: elementPath: elementPath, ...}, * * @param db// w ww . j a v a2 s . co m * @param appName * @param tableId * @return */ private static String getStringForDataObject(SQLiteDatabase db, String appName, String tableId, int numberOfRows) { ArrayList<ColumnDefinition> orderedDefns = TableUtil.get().getColumnDefinitions(db, appName, tableId); UserTable userTable = null; userTable = ODKDatabaseUtils.get().rawSqlQuery(db, appName, tableId, orderedDefns, null, null, null, null, null, null); // TODO: This is broken w.r.t. elementKey != elementPath // TODO: HACKED HACKED HACKED HACKED // Because the code is so freaked up we don't have an easy way to get the // information out of the UserTable without going through the TableData // object. So we need to create a dummy CustomTableView to get it to work. TableData tableData = new TableData(userTable); // We need to also store the element key to the index of the data so that // we know how to access it out of the array representing each row. Map<String, Integer> elementKeyToIndex = new HashMap<String, Integer>(); for (ColumnDefinition cd : orderedDefns) { if (cd.isUnitOfRetention()) { elementKeyToIndex.put(cd.getElementKey(), userTable.getColumnIndexOfElementKey(cd.getElementKey())); } } // We don't want to try and write more rows than we have. int numRowsToWrite = Math.min(numberOfRows, userTable.getNumberOfRows()); // First write the array of row ids. String[] rowIds = new String[numRowsToWrite]; for (int i = 0; i < rowIds.length; i++) { rowIds[i] = userTable.getRowAtIndex(i).getRowId(); } // Here we're using this object b/c these appear to be the columns // available to the client--are metadata columns exposed to them? It's // not obvious to me here. Set<String> columnKeys = elementKeyToIndex.keySet(); Map[] partialData = new Map[numRowsToWrite]; // Now construct up the partial data object. for (int i = 0; i < numRowsToWrite; i++) { Map<String, Object> rowOut = new HashMap<String, Object>(); for (String elementKey : columnKeys) { rowOut.put(elementKey, tableData.getData(i, elementKey)); } partialData[i] = rowOut; } // And now construct the object storing the columns data. JsonParser jsonParser = new JsonParser(); Map<String, Object> elementKeyToColumnData = new HashMap<String, Object>(); for (String elementKey : columnKeys) { // The tableData object returns a string, so we'll have to parse it back // into json. String strColumnData = tableData.getColumnDataForElementKey(elementKey, numRowsToWrite); if (strColumnData == null) continue; JsonArray columnData = (JsonArray) jsonParser.parse(strColumnData); // Now that it's json, we want to convert it to an array. Otherwise it // serializes to an object with a single key "elements". Oh gson. String[] columnDataArray = new String[columnData.size()]; for (int i = 0; i < columnDataArray.length; i++) { JsonElement e = columnData.get(i); if (e == JsonNull.INSTANCE) { columnDataArray[i] = null; } else { columnDataArray[i] = e.getAsString(); } } elementKeyToColumnData.put(elementKey, columnDataArray); } Gson gson = new Gson(); // We need to parse some of the String objects returned by TableData into // json so that they're output as objects rather than strings. String columnString = tableData.getColumns(); JsonObject columnJson = (JsonObject) jsonParser.parse(columnString); // Here, as with JsonArray, we need to convert this to a map or else we'll // serialize as the object to a "members" key. Map<String, Object> columnJsonMap = new HashMap<String, Object>(); for (Map.Entry<String, JsonElement> entry : columnJson.entrySet()) { JsonElement e = entry.getValue(); if (e == JsonNull.INSTANCE) { columnJsonMap.put(entry.getKey(), null); } else { columnJsonMap.put(entry.getKey(), e.getAsString()); } } Map<String, Object> outputObject = new HashMap<String, Object>(); outputObject.put(DATA_KEY_IS_GROUPED_BY, tableData.isGroupedBy()); // We don't want the real count, as that could interfere with for loops in // the code. We in fact want the number of rows that are written, as that // will be the number of rows available to the javascript. outputObject.put(DATA_KEY_TABLE_ID, userTable.getTableId()); outputObject.put(DATA_KEY_COUNT, numRowsToWrite); outputObject.put(DATA_KEY_COLUMNS, columnJsonMap); outputObject.put(DATA_KEY_COLUMN_DATA, elementKeyToColumnData); outputObject.put(DATA_KEY_DATA, partialData); outputObject.put(DATA_KEY_ROW_IDS, rowIds); String outputString = gson.toJson(outputObject); return outputString; }
From source file:org.opendaylight.controller.sal.rest.gson.JsonParser.java
License:Open Source License
public JsonElement parse(JsonReader reader) throws JsonIOException, JsonSyntaxException { // code copied from gson's JsonParser and Stream classes boolean lenient = reader.isLenient(); reader.setLenient(true);/*from ww w .j a v a 2s . c om*/ boolean isEmpty = true; try { reader.peek(); isEmpty = false; return read(reader); } catch (EOFException e) { if (isEmpty) { return JsonNull.INSTANCE; } // The stream ended prematurely so it is likely a syntax error. throw new JsonSyntaxException(e); } catch (MalformedJsonException e) { throw new JsonSyntaxException(e); } catch (IOException e) { throw new JsonIOException(e); } catch (NumberFormatException e) { throw new JsonSyntaxException(e); } catch (StackOverflowError | OutOfMemoryError e) { throw new JsonParseException("Failed parsing JSON source: " + reader + " to Json", e); } finally { reader.setLenient(lenient); } }
From source file:org.opendaylight.controller.sal.rest.gson.JsonParser.java
License:Open Source License
public JsonElement read(JsonReader in) throws IOException { switch (in.peek()) { case STRING:/*from w w w.j av a 2 s.c om*/ return new JsonPrimitive(in.nextString()); case NUMBER: String number = in.nextString(); return new JsonPrimitive(new LazilyParsedNumber(number)); case BOOLEAN: return new JsonPrimitive(in.nextBoolean()); case NULL: in.nextNull(); return JsonNull.INSTANCE; case BEGIN_ARRAY: JsonArray array = new JsonArray(); in.beginArray(); while (in.hasNext()) { array.add(read(in)); } in.endArray(); return array; case BEGIN_OBJECT: JsonObject object = new JsonObject(); in.beginObject(); while (in.hasNext()) { final String childName = in.nextName(); if (object.has(childName)) { throw new JsonSyntaxException("Duplicate name " + childName + " in JSON input."); } object.add(childName, read(in)); } in.endObject(); return object; case END_DOCUMENT: case NAME: case END_OBJECT: case END_ARRAY: default: throw new IllegalArgumentException(); } }
From source file:org.openmrs.mobile.utilities.ObservationDeserializer.java
License:Open Source License
@Override public Observation deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject jsonObject = json.getAsJsonObject(); Observation observation = new Observation(); observation.setUuid(jsonObject.get(UUID_KEY).getAsString()); if (jsonObject.get(DISPLAY_KEY) != JsonNull.INSTANCE && jsonObject.get(DISPLAY_KEY) != null) { observation.setDisplay(jsonObject.get(DISPLAY_KEY).getAsString()); }//from ww w .ja v a2s .c om if (jsonObject.get(COMMENT_KEY) != JsonNull.INSTANCE && jsonObject.get(COMMENT_KEY) != null) { observation.setComment(jsonObject.get(COMMENT_KEY).getAsString()); } if (jsonObject.get(DATE_KEY) != JsonNull.INSTANCE && jsonObject.get(DATE_KEY) != null) { observation.setObsDatetime(jsonObject.get(DATE_KEY).getAsString()); } JsonElement encounterJson = jsonObject.get("encounter"); if (null != encounterJson && !encounterJson.isJsonNull()) { Encounter encounter = new Encounter(); encounter.setUuid(encounterJson.getAsJsonObject().get(UUID_KEY).getAsString()); Visit visit = new Visit(); JsonElement visitElement = encounterJson.getAsJsonObject().get("visit"); if (null != visitElement && !visitElement.isJsonNull()) { visit.setUuid(visitElement.getAsJsonObject().get(UUID_KEY).getAsString()); } encounter.setVisit(visit); observation.setEncounter(encounter); } JsonElement conceptJson = jsonObject.get("concept"); if (conceptJson != null && "Visit Diagnoses".equals(conceptJson.getAsJsonObject().get(DISPLAY_KEY).getAsString())) { JsonArray diagnosisDetailJSONArray = jsonObject.get("groupMembers").getAsJsonArray(); for (int i = 0; i < diagnosisDetailJSONArray.size(); i++) { JsonObject diagnosisDetails = diagnosisDetailJSONArray.get(i).getAsJsonObject(); String diagnosisDetail = diagnosisDetails.get("concept").getAsJsonObject().get(DISPLAY_KEY) .getAsString(); if ("Diagnosis order".equals(diagnosisDetail)) { observation.setDiagnosisOrder(diagnosisDetails.getAsJsonObject().get(VALUE_KEY) .getAsJsonObject().get(DISPLAY_KEY).getAsString()); } else if ("Diagnosis certainty".equals(diagnosisDetail)) { observation.setDiagnosisCertanity(diagnosisDetails.getAsJsonObject().get(VALUE_KEY) .getAsJsonObject().get(DISPLAY_KEY).getAsString()); } else { try { observation.setDiagnosisList(diagnosisDetails.getAsJsonObject().get(VALUE_KEY) .getAsJsonObject().get(DISPLAY_KEY).getAsString()); observation.setValueCodedName(diagnosisDetails.getAsJsonObject().get(VALUE_KEY) .getAsJsonObject().get(UUID_KEY).getAsString()); } catch (IllegalStateException e) { observation .setDiagnosisList(diagnosisDetails.getAsJsonObject().get(VALUE_KEY).getAsString()); } } } } else if (conceptJson != null && "Text of encounter note".equals(conceptJson.getAsJsonObject().get(DISPLAY_KEY).getAsString())) { JsonElement encounterNote = jsonObject.getAsJsonObject().get(VALUE_KEY); observation.setDiagnosisNote(!encounterNote.isJsonNull() ? encounterNote.getAsString() : ""); } if (conceptJson != null) { Concept concept = new Concept(); concept.setUuid(conceptJson.getAsJsonObject().get(UUID_KEY).getAsString()); observation.setConcept(concept); } JsonElement personJson = jsonObject.get("person"); if (personJson != null) { Person person = new Person(); person.setUuid(personJson.getAsJsonObject().get(UUID_KEY).getAsString()); person.setDisplay(personJson.getAsJsonObject().get(DISPLAY_KEY).getAsString()); observation.setPerson(person); } JsonElement creatorJson = jsonObject.get("creator"); if (creatorJson != null) { User user = new User(); user.setUuid(creatorJson.getAsJsonObject().get(UUID_KEY).getAsString()); user.setDisplay(creatorJson.getAsJsonObject().get(DISPLAY_KEY).getAsString()); JsonElement creatorPersonJson = creatorJson.getAsJsonObject().get("person"); if (creatorPersonJson != null) { Person person = new Person(); person.setUuid(creatorPersonJson.getAsJsonObject().get(UUID_KEY).getAsString()); person.setDisplay(creatorPersonJson.getAsJsonObject().get(DISPLAY_KEY).getAsString()); user.setPerson(person); } observation.setCreator(user); } JsonElement dateCreatedJson = jsonObject.get("dateCreated"); if (dateCreatedJson != null) { observation.setDateCreated(DateUtils.convertTimeString(dateCreatedJson.getAsString()).toDate()); } JsonElement voidedJson = jsonObject.get("voided"); if (voidedJson != null) { observation.setVoided(Boolean.getBoolean(voidedJson.getAsString())); } return observation; }
From source file:org.openqa.selenium.json.BeanToJsonConverter.java
License:Apache License
/** * Convert an object that may or may not be a JsonElement into its JSON object * representation, handling the case where it is neither in a graceful way. * * @param object which needs conversion//from w w w .ja v a2s . c o m * @return the JSON object representation of object */ public JsonElement convertObject(Object object) { if (object == null) { return JsonNull.INSTANCE; } try { return convertObject(object, MAX_DEPTH); } catch (Exception e) { throw new WebDriverException("Unable to convert: " + object, e); } }
From source file:org.openqa.selenium.json.BeanToJsonConverter.java
License:Apache License
@SuppressWarnings("unchecked") private JsonElement convertObject(Object toConvert, int maxDepth) throws Exception { if (toConvert == null) { return JsonNull.INSTANCE; }//from w ww .j a v a2 s. co m if (toConvert instanceof Boolean) { return new JsonPrimitive((Boolean) toConvert); } if (toConvert instanceof CharSequence) { return new JsonPrimitive(String.valueOf(toConvert)); } if (toConvert instanceof Number) { return new JsonPrimitive((Number) toConvert); } if (toConvert instanceof Level) { return new JsonPrimitive(LogLevelMapping.getName((Level) toConvert)); } if (toConvert.getClass().isEnum() || toConvert instanceof Enum) { return new JsonPrimitive(toConvert.toString()); } if (toConvert instanceof Map) { Map<String, Object> map = (Map<String, Object>) toConvert; if (map.size() == 1 && map.containsKey("w3c cookie")) { return convertObject(map.get("w3c cookie")); } JsonObject converted = new JsonObject(); for (Map.Entry<String, Object> entry : map.entrySet()) { converted.add(entry.getKey(), convertObject(entry.getValue(), maxDepth - 1)); } return converted; } if (toConvert instanceof JsonElement) { return (JsonElement) toConvert; } if (toConvert instanceof Collection) { JsonArray array = new JsonArray(); for (Object o : (Collection<?>) toConvert) { array.add(convertObject(o, maxDepth - 1)); } return array; } if (toConvert.getClass().isArray()) { JsonArray converted = new JsonArray(); int length = Array.getLength(toConvert); for (int i = 0; i < length; i++) { converted.add(convertObject(Array.get(toConvert, i), maxDepth - 1)); } return converted; } if (toConvert instanceof SessionId) { JsonObject converted = new JsonObject(); converted.addProperty("value", toConvert.toString()); return converted; } if (toConvert instanceof Date) { return new JsonPrimitive(TimeUnit.MILLISECONDS.toSeconds(((Date) toConvert).getTime())); } if (toConvert instanceof File) { return new JsonPrimitive(((File) toConvert).getAbsolutePath()); } Method toJson = getMethod(toConvert, "toJson"); if (toJson != null) { try { Object res = toJson.invoke(toConvert); if (res instanceof JsonElement) { return (JsonElement) res; } if (res instanceof Map) { return convertObject(res); } else if (res instanceof Collection) { return convertObject(res); } else if (res instanceof String) { try { return new JsonParser().parse((String) res); } catch (JsonParseException e) { return new JsonPrimitive((String) res); } } } catch (ReflectiveOperationException e) { throw new WebDriverException(e); } } Method toMap = getMethod(toConvert, "toMap"); if (toMap == null) { toMap = getMethod(toConvert, "asMap"); } if (toMap != null) { try { return convertObject(toMap.invoke(toConvert), maxDepth - 1); } catch (ReflectiveOperationException e) { throw new WebDriverException(e); } } try { return mapObject(toConvert, maxDepth - 1, toConvert instanceof Cookie); } catch (Exception e) { throw new WebDriverException(e); } }
From source file:org.openqa.selenium.json.BeanToJsonConverter.java
License:Apache License
private JsonElement mapObject(Object toConvert, int maxDepth, boolean skipNulls) throws Exception { if (maxDepth < 1) { return JsonNull.INSTANCE; }/*from w ww .j a va 2 s . co m*/ // Raw object via reflection? Nope, not needed JsonObject mapped = new JsonObject(); for (SimplePropertyDescriptor pd : SimplePropertyDescriptor.getPropertyDescriptors(toConvert.getClass())) { if ("class".equals(pd.getName())) { mapped.addProperty("class", toConvert.getClass().getName()); continue; } Method readMethod = pd.getReadMethod(); if (readMethod == null) { continue; } if (readMethod.getParameterTypes().length > 0) { continue; } readMethod.setAccessible(true); Object result = readMethod.invoke(toConvert); if (!skipNulls || result != null) { mapped.add(pd.getName(), convertObject(result, maxDepth - 1)); } } return mapped; }
From source file:org.openqa.selenium.remote.BeanToJsonConverter.java
License:Apache License
@SuppressWarnings("unchecked") private JsonElement convertObject(Object toConvert, int maxDepth) throws Exception { if (toConvert == null) { return JsonNull.INSTANCE; }//w ww .jav a 2s . c o m if (toConvert instanceof Boolean) { return new JsonPrimitive((Boolean) toConvert); } if (toConvert instanceof CharSequence) { return new JsonPrimitive(String.valueOf(toConvert)); } if (toConvert instanceof Number) { return new JsonPrimitive((Number) toConvert); } if (toConvert instanceof Level) { return new JsonPrimitive(LogLevelMapping.getName((Level) toConvert)); } if (toConvert.getClass().isEnum() || toConvert instanceof Enum) { return new JsonPrimitive(toConvert.toString()); } if (toConvert instanceof LoggingPreferences) { LoggingPreferences prefs = (LoggingPreferences) toConvert; JsonObject converted = new JsonObject(); for (String logType : prefs.getEnabledLogTypes()) { converted.addProperty(logType, LogLevelMapping.getName(prefs.getLevel(logType))); } return converted; } if (toConvert instanceof SessionLogs) { return convertObject(((SessionLogs) toConvert).getAll(), maxDepth - 1); } if (toConvert instanceof LogEntries) { return convertObject(((LogEntries) toConvert).getAll(), maxDepth - 1); } if (toConvert instanceof Map) { Map<String, Object> map = (Map<String, Object>) toConvert; if (map.size() == 1 && map.containsKey("w3c cookie")) { return convertObject(map.get("w3c cookie")); } JsonObject converted = new JsonObject(); for (Map.Entry<String, Object> entry : map.entrySet()) { converted.add(entry.getKey(), convertObject(entry.getValue(), maxDepth - 1)); } return converted; } if (toConvert instanceof JsonElement) { return (JsonElement) toConvert; } if (toConvert instanceof Collection) { JsonArray array = new JsonArray(); for (Object o : (Collection<?>) toConvert) { array.add(convertObject(o, maxDepth - 1)); } return array; } if (toConvert.getClass().isArray()) { JsonArray converted = new JsonArray(); int length = Array.getLength(toConvert); for (int i = 0; i < length; i++) { converted.add(convertObject(Array.get(toConvert, i), maxDepth - 1)); } return converted; } if (toConvert instanceof SessionId) { JsonObject converted = new JsonObject(); converted.addProperty("value", toConvert.toString()); return converted; } if (toConvert instanceof Date) { return new JsonPrimitive(TimeUnit.MILLISECONDS.toSeconds(((Date) toConvert).getTime())); } if (toConvert instanceof File) { return new JsonPrimitive(((File) toConvert).getAbsolutePath()); } Method toMap = getMethod(toConvert, "toMap"); if (toMap == null) { toMap = getMethod(toConvert, "asMap"); } if (toMap != null) { try { return convertObject(toMap.invoke(toConvert), maxDepth - 1); } catch (IllegalArgumentException e) { throw new WebDriverException(e); } catch (IllegalAccessException e) { throw new WebDriverException(e); } catch (InvocationTargetException e) { throw new WebDriverException(e); } } Method toList = getMethod(toConvert, "toList"); if (toList == null) { toList = getMethod(toConvert, "asList"); } if (toList != null) { try { return convertObject(toList.invoke(toConvert), maxDepth - 1); } catch (IllegalArgumentException e) { throw new WebDriverException(e); } catch (IllegalAccessException e) { throw new WebDriverException(e); } catch (InvocationTargetException e) { throw new WebDriverException(e); } } Method toJson = getMethod(toConvert, "toJson"); if (toJson != null) { try { Object res = toJson.invoke(toConvert); if (res instanceof JsonElement) { return (JsonElement) res; } try { return new JsonParser().parse((String) res); } catch (JsonParseException e) { return new JsonPrimitive((String) res); } } catch (IllegalArgumentException e) { throw new WebDriverException(e); } catch (IllegalAccessException e) { throw new WebDriverException(e); } catch (InvocationTargetException e) { throw new WebDriverException(e); } } try { return mapObject(toConvert, maxDepth - 1, toConvert instanceof Cookie); } catch (Exception e) { throw new WebDriverException(e); } }