Java Code Examples for com.google.gson.JsonElement#getAsLong()

The following examples show how to use com.google.gson.JsonElement#getAsLong() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JsonUtil.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
public static Date getNullableTimestampKey(JsonObject obj, String key)
        throws ResponseFormatException {
    JsonElement val = getNullableKey(obj, key);
    if (val == null) {
        return null;
    }
    if (val.isJsonPrimitive()) {
        try {
            long v = val.getAsLong();
            return new Date(v);
        } catch (NumberFormatException e) {
            throw new ResponseFormatException(key, val, e);
        }
    }
    throw new ResponseFormatException(key, val);
}
 
Example 2
Source File: GsonFactory.java    From DanDanPlayForAndroid with MIT License 5 votes vote down vote up
@Override
public Long deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    try {
        if (json.getAsString().equals("") || json.getAsString().equals("null")) {//定义为long类型,如果后台返回""或者null,则返回0
            return 0L;
        }
    } catch (Exception ignore) {
    }
    try {
        return json.getAsLong();
    } catch (NumberFormatException e) {
        throw new JsonSyntaxException(e);
    }
}
 
Example 3
Source File: JsonStubTrace.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public ITmfEvent parseEvent(ITmfContext context) {
    ITmfLocation location = context.getLocation();
    if (location instanceof TmfLongLocation) {
        TmfLongLocation tmfLongLocation = (TmfLongLocation) location;
        Long locationInfo = tmfLongLocation.getLocationInfo();
        if (location.equals(NULL_LOCATION)) {
            locationInfo = 0L;
        }
        try {
            if (!locationInfo.equals(fFileInput.getFilePointer())) {
                fFileInput.seek(locationInfo);
            }
            String nextJson = readNextEventString(() -> fFileInput.read());
            while (nextJson != null) {
                if (nextJson != null) {
                    JsonObject object = GSON.fromJson(nextJson, JsonObject.class);
                    // Ignore events with no timestamp, they are there just to make sure the traces
                    // parses in those cases
                    JsonElement tsElement = object.get(TIMESTAMP_KEY);
                    if (tsElement != null) {
                        long timestamp = tsElement.getAsLong();
                        return new TmfEvent(this, context.getRank(), TmfTimestamp.fromNanos(timestamp),
                            new TmfEventType("JsonStubEvent", null), null); //$NON-NLS-1$
                    }
                    nextJson = readNextEventString(() -> fFileInput.read());
                }
            }
        } catch (IOException e) {
            // Nothing to do
        }
    }
    return null;
}
 
Example 4
Source File: TmfIntervalDeserializer.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public ITmfStateInterval deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
    JsonObject object = json.getAsJsonObject();
    long start = object.get(TmfIntervalStrings.START).getAsLong();
    long end = object.get(TmfIntervalStrings.END).getAsLong();
    int quark = object.get(TmfIntervalStrings.QUARK).getAsInt();
    String type = object.get(TmfIntervalStrings.TYPE).getAsString();
    if (type.equals(TmfIntervalStrings.NULL)) {
        return new TmfStateInterval(start, end, quark, (Object) null);
    }
    JsonElement value = object.get(TmfIntervalStrings.VALUE);
    try {
        Class<?> typeClass = Class.forName(type);

        if (typeClass.isAssignableFrom(CustomStateValue.class)) {
            String encoded = value.getAsString();
            byte[] serialized = Base64.getDecoder().decode(encoded);
            ByteBuffer buffer = ByteBuffer.wrap(serialized);
            ISafeByteBufferReader sbbr = SafeByteBufferFactory.wrapReader(buffer, serialized.length);
            TmfStateValue sv = CustomStateValue.readSerializedValue(sbbr);
            return new TmfStateInterval(start, end, quark, sv.unboxValue());
        }
        if (typeClass.isAssignableFrom(Integer.class)) {
            return new TmfStateInterval(start, end, quark, value.getAsInt());
        } else if (typeClass.isAssignableFrom(Long.class)) {
            return new TmfStateInterval(start, end, quark, value.getAsLong());
        } else if (typeClass.isAssignableFrom(Double.class)) {
            return new TmfStateInterval(start, end, quark, value.getAsDouble());
        } else if (typeClass.isAssignableFrom(String.class)) {
            return new TmfStateInterval(start, end, quark, value.getAsString());
        }
    } catch (ClassNotFoundException e) {
        // Fall through
    }
    // last ditch attempt
    return new TmfStateInterval(start, end, quark, value.toString());
}
 
Example 5
Source File: DatabaseObjectCommon.java    From StatsAgg with Apache License 2.0 5 votes vote down vote up
public static JsonObject getApiFriendlyJsonObject_CorrectTimesAndTimeUnits(JsonObject jsonObject, String time_FieldName, String timeUnit_FieldName) {
    
    if (jsonObject == null) {
        return null;
    }
    
    try {
        JsonElement time_jsonElement = jsonObject.get(time_FieldName);
        JsonElement timeUnit_JsonElement = jsonObject.get(timeUnit_FieldName);

        if ((time_jsonElement != null) && (timeUnit_JsonElement != null)) {
            long currentField_JsonElement_Long = time_jsonElement.getAsLong();
            int timeUnit_Int = timeUnit_JsonElement.getAsInt();
            BigDecimal time_BigDecimal = DatabaseObjectCommon.getValueForTimeFromMilliseconds(currentField_JsonElement_Long, timeUnit_Int);
            
            jsonObject.remove(time_FieldName);
            JsonBigDecimal time_JsonBigDecimal = new JsonBigDecimal(time_BigDecimal);
            jsonObject.addProperty(time_FieldName, time_JsonBigDecimal);
            
            jsonObject.remove(timeUnit_FieldName);
            jsonObject.addProperty(timeUnit_FieldName, DatabaseObjectCommon.getTimeUnitStringFromCode(timeUnit_Int, false));
        }
        else if (time_jsonElement != null) {
            jsonObject.remove(time_FieldName);
        }
        else if (timeUnit_JsonElement != null) {
            jsonObject.remove(timeUnit_FieldName);
        }
    }
    catch (Exception e) {
        logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
    }
    
    return jsonObject;
}
 
Example 6
Source File: VectorColumnFiller.java    From secor with Apache License 2.0 5 votes vote down vote up
public void convert(JsonElement value, ColumnVector vect, int row) {
    if (value == null || value.isJsonNull()) {
        vect.noNulls = false;
        vect.isNull[row] = true;
    } else {
        LongColumnVector vector = (LongColumnVector) vect;
        vector.vector[row] = value.getAsLong();
    }
}
 
Example 7
Source File: GsonUtil.java    From FriendCircle with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Long deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
    try {
        //定义为long类型,如果后台返回""或者null,则返回0
        if (json.getAsString().equals("") || json.getAsString().equals("null")) {
            return 0L;
        }
    } catch (Exception ignore) {
    }
    try {
        return json.getAsLong();
    } catch (NumberFormatException e) {
        throw new JsonSyntaxException(e);
    }
}
 
Example 8
Source File: MonitorDataService.java    From saluki with Apache License 2.0 5 votes vote down vote up
@Override
public Date deserialize(JsonElement element, Type arg1,
                        JsonDeserializationContext arg2) throws JsonParseException {
    Long timestamp = element.getAsLong();
    Date date = new Date(timestamp);
    return date;
}
 
Example 9
Source File: BackupUtils.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Nullable
public static Long getLong(JsonObject data, String name) {
   JsonElement elem = data.get(name);
   if (elem == null || elem.isJsonNull()) {
      return null;
   }

   return elem.getAsLong();
}
 
Example 10
Source File: GsonUtil.java    From star-zone-android with Apache License 2.0 5 votes vote down vote up
@Override
public Long deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
    try {
        //定义为long类型,如果后台返回""或者null,则返回0
        if (json.getAsString().equals("") || json.getAsString().equals("null")) {
            return 0L;
        }
    } catch (Exception ignore) {
    }
    try {
        return json.getAsLong();
    } catch (NumberFormatException e) {
        throw new JsonSyntaxException(e);
    }
}
 
Example 11
Source File: JsonUtil.java    From camunda-bpm-identity-keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the Long value of a member of a given JsonObject.
 * @param jsonObject the JsonObject
 * @param memberName the name of the member to return
 * @return the Long value of the member or {@code null} if no such member exists
 * @throws JsonException in case of errors
 */
public static Long getJsonLong(JsonObject jsonObject, String memberName) throws JsonException {
	try {
		JsonElement element = jsonObject.get(memberName);
		return element == null ? null : element.getAsLong();
	} catch (ClassCastException | IllegalStateException ex) {
		throw new JsonException("Unable to get '" + memberName + "' from JsonObject " + jsonObject.toString(), ex);
	}
}
 
Example 12
Source File: SqlBuilderSerializer.java    From das with Apache License 2.0 5 votes vote down vote up
Supplier toPrimitive(JsonObject obj){
    if(!obj.has("type")){
        return ()-> new Object();
    }
    String type = obj.get("type").getAsString();
    JsonElement primitive = obj.get("value");
    if(type.equals(String.class.getSimpleName())){
        return () -> primitive.getAsString();
    }
    if(type.equals(Long.class.getSimpleName())){
        return () -> primitive.getAsLong();
    }
    if(type.equals(Integer.class.getSimpleName())){
        return () -> primitive.getAsInt();
    }
    if(type.equals(Boolean.class.getSimpleName())){
        return () -> primitive.getAsBoolean();
    }
    if(type.equals(Float.class.getSimpleName())){
        return () -> primitive.getAsFloat();
    }
    if(type.equals(Date.class.getName())){
        return () -> new Date(primitive.getAsLong());
    }
    if(type.equals(Timestamp.class.getName())){
        return () -> new Timestamp(primitive.getAsLong());
    }
    return () -> null;
}
 
Example 13
Source File: GsonHelper.java    From weixin-java-tools with Apache License 2.0 4 votes vote down vote up
public static Long getAsLong(JsonElement element) {
  return isNull(element) ? null : element.getAsLong();
}
 
Example 14
Source File: TestUtils.java    From headlong with Apache License 2.0 4 votes vote down vote up
public static long parseLong(JsonElement in) {
    return in.getAsLong();
}
 
Example 15
Source File: JsonUtil.java    From The-5zig-Mod with GNU General Public License v3.0 4 votes vote down vote up
public static long getLong(JsonObject object, String name) {
	JsonElement element = object.get(name);
	if (element == null || element.isJsonNull())
		return 0;
	return element.getAsLong();
}
 
Example 16
Source File: MsgDefTypeAdapter.java    From Android with MIT License 4 votes vote down vote up
public long parseLong(String key) {
    JsonElement element = object.get(key);
    if (element == null) return 0;
    return element.getAsLong();
}
 
Example 17
Source File: CustomTypeAdaptersTest.java    From gson with Apache License 2.0 4 votes vote down vote up
@Override
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
  return typeOfT == Date.class
      ? new Date(json.getAsLong())
      : new java.sql.Date(json.getAsLong());
}
 
Example 18
Source File: ViewResponseImpl.java    From java-cloudant with Apache License 2.0 4 votes vote down vote up
ViewResponseImpl(ViewQueryParameters<K, V> initialQueryParameters, JsonObject response,
                 PageMetadata<K, V> pageMetadata) {
    this.initialQueryParameters = initialQueryParameters;

    PageMetadata.PagingDirection thisPageDirection;
    if (pageMetadata == null) {
        previousPageMetadata = null;
        pageNumber = 1l;
        //from a first page we can only page FORWARD
        thisPageDirection = PageMetadata.PagingDirection.FORWARD;
    } else {
        this.pageNumber = pageMetadata.pageNumber;
        thisPageDirection = pageMetadata.direction;
    }

    //build the rows from the response
    JsonArray rowsArray = response.getAsJsonArray("rows");
    if (rowsArray != null) {
        for (JsonElement row : rowsArray) {
            rows.add(fromJson(row));
        }
    }
    int resultRows = rows.size();

    JsonElement totalRowsElement = response.get("total_rows");
    if (totalRowsElement != null) {
        totalRows = totalRowsElement.getAsLong();
    } else {
        //if there is no total rows element, use the rows size
        totalRows = rows.size();
    }

    Long rowsPerPage = (initialQueryParameters.getRowsPerPage() != null) ?
            initialQueryParameters.getRowsPerPage().longValue() : null;

    // We expect limit = rowsPerPage + 1 results, if we have rowsPerPage or less,
    // or if rowsPerPage wasn't set then we are on the last page.
    hasNext = (rowsPerPage != null) ? (resultRows > rowsPerPage) : false;

    if (PageMetadata.PagingDirection.BACKWARD == thisPageDirection) {
        //Result needs reversing because to implement backward paging the view reading
        // order is reversed
        Collections.reverse(rows);
    }

    //set previous page links if not the first page
    if (this.pageNumber > 1) {
        hasPrevious = true;
        // Construct the previous page metadata (i.e. paging backward)
        // Decrement the page number by 1
        // The startKey of this page is also the start key of the previous page, but using a
        // descending lookup indicated by the paging direction.
        previousPageMetadata = new PageMetadata<K, V>(PageMetadata.PagingDirection
                .BACKWARD, this.pageNumber - 1l, PageMetadata.reversePaginationQueryParameters
                (initialQueryParameters, rows.get(0).getKey(), rows.get(0).getId()));
    } else {
        hasPrevious = false;
    }

    // If we are not on the last page, we need to use the last
    // result as the start key for the next page and therefore
    // we don't return it to the user.
    // If we are on the last page, the final row should be returned
    // to the user.
    int lastIndex = resultRows - 1;
    if (hasNext) {
        // Construct the next page metadata (i.e. paging forward)
        // Increment the page number by 1
        // The last element is the start of the next page so use the key and ID from that
        // element for creating the next page query parameters.
        nextPageMetadata = new PageMetadata<K, V>(PageMetadata.PagingDirection
                .FORWARD, this.pageNumber + 1l, PageMetadata.forwardPaginationQueryParameters
                (initialQueryParameters, rows.get(lastIndex).getKey(), rows.get(lastIndex)
                        .getId()));

        // The final element is the first element of the next page, so remove from the list that
        // will be returned.
        rows.remove(lastIndex);
    } else {
        nextPageMetadata = null;
    }

    // calculate paging display info
    if (rowsPerPage != null) {
        long offset = (this.pageNumber - 1) * rowsPerPage;
        resultFrom = offset + 1;
        resultTo = offset + (hasNext ? rowsPerPage : resultRows);
    } else {
        resultFrom = 1;
        resultTo = totalRows;
    }
}
 
Example 19
Source File: JsonUtil.java    From The-5zig-Mod with MIT License 4 votes vote down vote up
public static long getLong(JsonObject object, String name) {
	JsonElement element = object.get(name);
	if (element == null || element.isJsonNull())
		return 0;
	return element.getAsLong();
}
 
Example 20
Source File: JsonDeserializer.java    From anomaly-detection with Apache License 2.0 3 votes vote down vote up
/**
 * Search a long number inside a JSON string matching the input path
 * expression
 *
 * @param jsonElement
 *            a Gson JsonElement
 * @param paths
 *            path fragments
 * @return the matching long number or null in case of no match.
 */
public static long getLongValue(JsonElement jsonElement, String... paths) throws JsonPathNotFoundException {

    jsonElement = getChildNode(jsonElement, paths);
    if (jsonElement != null) {
        return jsonElement.getAsLong();
    }

    throw new JsonPathNotFoundException();
}