Example usage for com.google.gson JsonPrimitive getAsString

List of usage examples for com.google.gson JsonPrimitive getAsString

Introduction

In this page you can find the example usage for com.google.gson JsonPrimitive getAsString.

Prototype

@Override
public String getAsString() 

Source Link

Document

convenience method to get this element as a String.

Usage

From source file:com.diversityarrays.dalclient.DalUtil.java

License:Open Source License

static public DalResponseRecord createFrom(String requestUrl, String tagName, JsonObject input) {
    DalResponseRecord result = new DalResponseRecord(requestUrl, tagName);
    for (Map.Entry<String, JsonElement> entry : input.entrySet()) {
        String key = entry.getKey();
        JsonElement value = entry.getValue();
        if (value == null || value.isJsonNull()) {
            result.rowdata.put(key, "");
        } else if (value.isJsonArray()) {
            JsonArray array = (JsonArray) value;
            int count = 0;
            for (JsonElement elt : array) {
                if (elt != null && elt.isJsonObject()) {
                    JsonObject child = (JsonObject) elt;
                    Map<String, String> childMap = asRowdata(child);
                    if (childMap != null) {
                        result.addNestedData(key, childMap);
                    }//  w w w  .  ja v a 2 s.c  om
                } else {
                    result.warnings.add(String.format("unexpected value-type for '%s'[%d] :%s", //$NON-NLS-1$
                            key, count, elt == null ? "null" : elt.getClass().getName()));
                }
                ++count;
            }
        } else if (value.isJsonPrimitive()) {
            JsonPrimitive prim = (JsonPrimitive) value;
            result.rowdata.put(key, prim.getAsString());
        } else if (value.isJsonObject()) {
            // ?? perhaps
            Map<String, String> childMap = asRowdata((JsonObject) value);
            if (childMap != null) {
                result.addNestedData(key, childMap);
            }
        } else {
            result.warnings.add(String.format("unexpected value-type for '%s' :%s", //$NON-NLS-1$
                    key, value.getClass().getName()));
        }
    }
    return result;
}

From source file:com.edduarte.argus.reader.JsonReader.java

License:Apache License

private void readRecursive(JsonElement root, MutableString collector) {
    if (root.isJsonObject()) {
        JsonObject object = (JsonObject) root;
        object.entrySet().forEach(e -> {
            collector.append(e.getKey());
            collector.append(' ');
            readRecursive(e.getValue(), collector);
            collector.append(' ');
        });/*w ww.  j a v  a 2 s .  c  o  m*/
    } else if (root.isJsonArray()) {
        JsonArray array = (JsonArray) root;
        array.forEach(child -> {
            readRecursive(child, collector);
            collector.append(' ');
        });
    } else if (root.isJsonPrimitive()) {
        JsonPrimitive primitive = (JsonPrimitive) root;
        collector.append(primitive.getAsString());
        collector.append(' ');
    }
}

From source file:com.exsoloscript.challonge.gson.OffsetDateTimeAdapter.java

License:Apache License

@Override
public OffsetDateTime deserialize(JsonElement json, Type type,
        JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
    JsonPrimitive jsonPrimitive = json.getAsJsonPrimitive();

    // if provided as String - '2011-12-03T10:15:30+01:00'
    if (jsonPrimitive.isString()) {
        return OffsetDateTime.parse(jsonPrimitive.getAsString(), DateTimeFormatter.ISO_OFFSET_DATE_TIME);
    }// ww w.  java2 s  .  c  o  m

    throw new JsonParseException("Unable to parse OffsetDateTime. DateTime was not provided as string.");
}

From source file:com.facebook.buck.intellij.plugin.ws.buckevents.BuckEventAdapter.java

License:Apache License

@Override
public BuckEventInterface deserialize(JsonElement jsonElement, Type type,
        JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
    JsonObject jsonObject = jsonElement.getAsJsonObject();
    JsonPrimitive prim = (JsonPrimitive) jsonObject.get("type");
    String typeFromJSON = prim.getAsString();

    if (MAPPINGS.containsKey(typeFromJSON)) {
        return jsonDeserializationContext.deserialize(jsonElement, MAPPINGS.get(typeFromJSON));
    }/*from   w  w w.  j  av  a 2  s .co m*/

    return jsonDeserializationContext.deserialize(jsonElement, BuckEventUnknown.class);
}

From source file:com.facebook.buck.json.RawParser.java

License:Apache License

/**
 * @return One of: String, Boolean, Long, Number, List<Object>, Map<String, Object>.
 *///from ww w. j  av a 2s.  c o  m
@Nullable
@VisibleForTesting
static Object toRawTypes(JsonElement json) {
    // Cases are ordered from most common to least common.
    if (json.isJsonPrimitive()) {
        JsonPrimitive primitive = json.getAsJsonPrimitive();
        if (primitive.isString()) {
            return interner.intern(primitive.getAsString());
        } else if (primitive.isBoolean()) {
            return primitive.getAsBoolean();
        } else if (primitive.isNumber()) {
            Number number = primitive.getAsNumber();
            // Number is likely an instance of class com.google.gson.internal.LazilyParsedNumber.
            if (number.longValue() == number.doubleValue()) {
                return number.longValue();
            } else {
                return number;
            }
        } else {
            throw new IllegalStateException("Unknown primitive type: " + primitive);
        }
    } else if (json.isJsonArray()) {
        JsonArray array = json.getAsJsonArray();
        List<Object> out = Lists.newArrayListWithCapacity(array.size());
        for (JsonElement item : array) {
            out.add(toRawTypes(item));
        }
        return out;
    } else if (json.isJsonObject()) {
        Map<String, Object> out = new LinkedHashMap<>(json.getAsJsonObject().entrySet().size());
        for (Map.Entry<String, JsonElement> entry : json.getAsJsonObject().entrySet()) {
            // On a large project, without invoking intern(), we have seen `buck targets` OOM. When this
            // happened, according to the .hprof file generated using -XX:+HeapDumpOnOutOfMemoryError,
            // 39.6% of the memory was spent on char[] objects while 14.5% was spent on Strings.
            // (Another 10.5% was spent on java.util.HashMap$Entry.) Introducing intern() stopped the
            // OOM from happening.
            out.put(interner.intern(entry.getKey()), toRawTypes(entry.getValue()));
        }
        return out;
    } else if (json.isJsonNull()) {
        return null;
    } else {
        throw new IllegalStateException("Unknown type: " + json);
    }
}

From source file:com.flipkart.polyguice.config.JsonConfiguration.java

License:Apache License

private void flatten(String prefix, JsonElement element) {
    if (element.isJsonPrimitive()) {
        JsonPrimitive jsonPrim = element.getAsJsonPrimitive();
        if (jsonPrim.isBoolean()) {
            configTab.put(prefix, jsonPrim.getAsBoolean());
        } else if (jsonPrim.isNumber()) {
            configTab.put(prefix, jsonPrim.getAsNumber());
        } else if (jsonPrim.isString()) {
            configTab.put(prefix, jsonPrim.getAsString());
        }//w w  w.  ja v  a 2 s  .  c om
    } else if (element.isJsonObject()) {
        JsonObject jsonObj = element.getAsJsonObject();
        for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {
            String prefix1 = ((prefix != null) ? prefix + "." : "") + entry.getKey();
            flatten(prefix1, entry.getValue());
        }
    }
}

From source file:com.frontier45.flume.sink.elasticsearch2.ElasticSearchLogStashEventSerializer.java

License:Apache License

private Object getValue(JsonElement obj) {
    JsonPrimitive jp = obj.getAsJsonPrimitive();
    if (jp.isBoolean()) {
        return jp.getAsBoolean();
    } else if (jp.isNumber()) {
        String value = jp.getAsString();
        if (value.indexOf(".") > 0) {
            return jp.getAsDouble();
        } else {/*from   w ww .  j  a va 2 s.  c o m*/
            return jp.getAsLong();
        }
    } else if (jp.isString()) {
        return jp.getAsString();
    }
    return obj;
}

From source file:com.getperka.flatpack.codexes.DateCodex.java

License:Apache License

@Override
public D readNotNull(JsonElement element, DeserializationContext context) throws Exception {
    if (element.isJsonPrimitive()) {
        long instant;
        JsonPrimitive primitive = element.getAsJsonPrimitive();
        if (primitive.isNumber()) {
            instant = primitive.getAsLong();
        } else {//from  w  w  w.ja  va2  s.c o  m
            instant = ISODateTimeFormat.dateTimeParser().parseMillis(primitive.getAsString());
        }
        return constructor.newInstance(instant);
    }
    throw new IllegalArgumentException("Could not parse " + element.toString() + " as a date value");
}

From source file:com.getperka.flatpack.codexes.DynamicCodex.java

License:Apache License

/**
 * Attempt to infer the type from the JsonElement presented.
 * <ul>/*from   ww  w .  j a  va2s. c  om*/
 * <li>boolean -> {@link Boolean}
 * <li>number -> {@link BigDecimal}
 * <li>string -> {@link HasUuid} or {@link String}
 * <li>array -> {@link ListCodex}
 * <li>object -> {@link StringMapCodex}
 * </ul>
 */
@Override
public Object readNotNull(JsonElement element, DeserializationContext context) throws Exception {
    if (element.isJsonPrimitive()) {
        JsonPrimitive primitive = element.getAsJsonPrimitive();
        if (primitive.isBoolean()) {
            return primitive.getAsBoolean();
        } else if (primitive.isNumber()) {
            // Always return numbers as BigDecimals for consistency
            return primitive.getAsBigDecimal();
        } else {
            String value = primitive.getAsString();

            // Interpret UUIDs as entity references
            if (UUID_PATTERN.matcher(value).matches()) {
                UUID uuid = UUID.fromString(value);
                HasUuid entity = context.getEntity(uuid);
                if (entity != null) {
                    return entity;
                }
            }

            return value;
        }
    } else if (element.isJsonArray()) {
        return listCodex.get().readNotNull(element, context);
    } else if (element.isJsonObject()) {
        return mapCodex.get().readNotNull(element, context);
    }
    context.fail(new UnsupportedOperationException("Cannot infer data type for " + element.toString()));
    return null;
}

From source file:com.github.autermann.matlab.json.MatlabValueSerializer.java

License:Open Source License

private MatlabScalar parseMatlabScalar(JsonElement value) {
    JsonPrimitive p = (JsonPrimitive) value;
    if (p.isString()) {
        return new MatlabScalar(Double.valueOf(p.getAsString()));
    } else {/*from   w  w  w  . j  a  v a  2 s .c  om*/
        return new MatlabScalar(p.getAsDouble());
    }
}