Example usage for com.google.gson JsonElement getAsJsonPrimitive

List of usage examples for com.google.gson JsonElement getAsJsonPrimitive

Introduction

In this page you can find the example usage for com.google.gson JsonElement getAsJsonPrimitive.

Prototype

public JsonPrimitive getAsJsonPrimitive() 

Source Link

Document

convenience method to get this element as a JsonPrimitive .

Usage

From source file:com.samsung.memoryanalysis.traceparser.TraceAnalysisRunner.java

License:Open Source License

private FreeVariables buildFVMap(File dir) throws IOException {
    File fvFile = new File(dir, "freevars.json");
    FreeVariables res = new FreeVariables();
    if (fvFile.exists()) {
        JsonObject json = null;/*from w  w w. j a va2  s .  co m*/
        try {
            json = parser.parse(new BufferedReader(new FileReader(fvFile))).getAsJsonObject();// parser.parse(js.get());
        } catch (JsonParseException ex) {
            throw new IOException("Invalid free-variables map file: " + ex.getMessage());
        }

        for (Map.Entry<String, JsonElement> entry : json.entrySet()) {
            JsonElement o = entry.getValue();
            if (o.isJsonPrimitive() && o.getAsJsonPrimitive().isString())
                res.put(Integer.parseInt(entry.getKey()), FreeVariables.ANY);
            else {
                JsonArray a = o.getAsJsonArray();
                final Set<String> freeVars = HashSetFactory.make();
                for (int i = 0; i < a.size(); i++) {
                    final JsonElement jsonElement = a.get(i);
                    freeVars.add(jsonElement.getAsString());
                }
                res.put(Integer.parseInt(entry.getKey()), freeVars);
            }
        }
    }
    return res;
}

From source file:com.samsung.sjs.FFILinkage.java

License:Apache License

public void parseTable(JsonObject table) {
    String name = table.getAsJsonPrimitive("name").getAsString();
    JsonArray arr = table.getAsJsonArray("fields");
    LinkedList<String> l = new LinkedList<>();
    for (JsonElement fname : arr) {
        l.add(fname.getAsJsonPrimitive().getAsString());
    }/*ww w  .  ja  v a2 s .c o  m*/
    tables_to_generate.put(name, l);
}

From source file:com.seleritycorp.common.base.config.ConfigUtils.java

License:Apache License

/**
 * Adds a JSON element to a Config.//from  w  w  w .j a  v a 2 s.c  o  m
 * 
 * @param element The element to add
 * @param config The config instance to add the element to
 * @param key The key in the config space
 */
private static void loadJson(JsonElement element, ConfigImpl config, String key) {
    if (element.isJsonObject()) {
        loadJson(element.getAsJsonObject(), config, key);
    } else if (element.isJsonArray()) {
        loadJson(element.getAsJsonArray(), config, key);
    } else if (element.isJsonPrimitive()) {
        loadJson(element.getAsJsonPrimitive(), config, key);
    } else if (element.isJsonNull()) {
        // null does not need a dedicated representation, so we
        // skip this case.
    } else {
        throw new UnsupportedOperationException("Unimplemented " + "JsonElement state");
    }
}

From source file:com.sgcv.rest.jsf.web.cliente.util.DateTypeAdapter.java

public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    return new Date(json.getAsJsonPrimitive().getAsLong());
}

From source file:com.simiacryptus.mindseye.lang.Tensor.java

License:Apache License

/**
 * From json tensor./* w ww. j a  va 2 s  .  co m*/
 *
 * @param json      the json
 * @param resources the resources
 * @return the tensor
 */
@Nullable
public static Tensor fromJson(@Nullable final JsonElement json, @Nullable Map<CharSequence, byte[]> resources) {
    if (null == json)
        return null;
    if (json.isJsonArray()) {
        final JsonArray array = json.getAsJsonArray();
        final int size = array.size();
        if (array.get(0).isJsonPrimitive()) {
            final double[] doubles = IntStream.range(0, size).mapToObj(i -> {
                return array.get(i);
            }).mapToDouble(element -> {
                return element.getAsDouble();
            }).toArray();
            @Nonnull
            Tensor tensor = new Tensor(doubles);
            assert tensor.isValid();
            return tensor;
        } else {
            final List<Tensor> elements = IntStream.range(0, size).mapToObj(i -> {
                return array.get(i);
            }).map(element -> {
                return Tensor.fromJson(element, resources);
            }).collect(Collectors.toList());
            @Nonnull
            final int[] dimensions = elements.get(0).getDimensions();
            if (!elements.stream().allMatch(t -> Arrays.equals(dimensions, t.getDimensions()))) {
                throw new IllegalArgumentException();
            }
            @Nonnull
            final int[] newDdimensions = Arrays.copyOf(dimensions, dimensions.length + 1);
            newDdimensions[dimensions.length] = size;
            @Nonnull
            final Tensor tensor = new Tensor(newDdimensions);
            @Nullable
            final double[] data = tensor.getData();
            for (int i = 0; i < size; i++) {
                @Nullable
                final double[] e = elements.get(i).getData();
                System.arraycopy(e, 0, data, i * e.length, e.length);
            }
            for (@Nonnull
            Tensor t : elements) {
                t.freeRef();
            }
            assert tensor.isValid();
            return tensor;
        }
    } else if (json.isJsonObject()) {
        JsonObject jsonObject = json.getAsJsonObject();
        @Nonnull
        int[] dims = fromJsonArray(jsonObject.getAsJsonArray("length"));
        @Nonnull
        Tensor tensor = new Tensor(dims);
        SerialPrecision precision = SerialPrecision
                .valueOf(jsonObject.getAsJsonPrimitive("precision").getAsString());
        JsonElement base64 = jsonObject.get("base64");
        if (null == base64) {
            if (null == resources)
                throw new IllegalArgumentException("No Data Resources");
            CharSequence resourceId = jsonObject.getAsJsonPrimitive("resource").getAsString();
            tensor.setBytes(resources.get(resourceId), precision);
        } else {
            tensor.setBytes(Base64.getDecoder().decode(base64.getAsString()), precision);
        }
        assert tensor.isValid();
        JsonElement id = jsonObject.get("id");
        if (null != id) {
            tensor.setId(UUID.fromString(id.getAsString()));
        }
        return tensor;
    } else {
        @Nonnull
        Tensor tensor = new Tensor(json.getAsJsonPrimitive().getAsDouble());
        assert tensor.isValid();
        return tensor;
    }
}

From source file:com.siso.app.utils.DateSerializer.java

public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    return new java.util.Date(json.getAsJsonPrimitive().getAsLong());
}

From source file:com.softwarementors.extjs.djn.router.processor.standard.json.JsonRequestProcessor.java

License:Open Source License

private @CheckForNull Object toSimpleJavaType(JsonElement jsonValue) {
    if (jsonValue == null)
        return null; //VR
    Object value = null;//ww w.  j ava 2 s.c  o m
    if (!jsonValue.isJsonNull()) {
        if (jsonValue.isJsonPrimitive()) {
            JsonPrimitive primitive = jsonValue.getAsJsonPrimitive();
            if (primitive.isBoolean()) {
                value = Boolean.valueOf(primitive.getAsBoolean());
            } else if (primitive.isNumber()) {
                value = Double.valueOf(primitive.getAsDouble());
            } else if (primitive.isString()) {
                value = primitive.getAsString();
            } else {
                throw UnexpectedException.forUnexpectedCodeBranchExecuted();
            }
        } else if (jsonValue.isJsonArray()) {
            //This simply does not work (?) 
            JsonArray array = jsonValue.getAsJsonArray();
            Object[] result = new Object[array.size()];
            for (int i = 0; i < array.size(); i++) {
                result[i] = toSimpleJavaType(array.get(i));
            }
            value = result;
        } else if (jsonValue.isJsonObject()) {
            //This simply does not work (?)
            //value = getGson().fromJson(jsonValue, Map.class );

            JsonObject obj = jsonValue.getAsJsonObject();
            Iterator<Entry<String, JsonElement>> properties = obj.entrySet().iterator();
            Map<String, Object> result = new HashMap<String, Object>();
            while (properties.hasNext()) {
                Entry<String, JsonElement> property = properties.next();
                JsonElement propertyValue = property.getValue();
                result.put(property.getKey(), toSimpleJavaType(propertyValue));
            }
            value = result;
        } else {
            throw UnexpectedException.forUnexpectedCodeBranchExecuted();
        }
    }

    return value;
}

From source file:com.splicemachine.tutorials.function.JsonFunction.java

License:Apache License

/**
 *
 * Call Method for parsing the string into either a singleton List with a LocatedRow or
 * an empty list.//from   www.  java 2  s.co m
 *
 * @param s
 * @return
 * @throws Exception
 */
@Override
public Iterator<LocatedRow> call(final String jsonString) throws Exception {

    Iterator<LocatedRow> itr = Collections.<LocatedRow>emptyList().iterator();
    if (jsonString == null) {
        return itr;
    }

    JsonElement elem = parser.parse(jsonString);
    JsonObject root = elem.getAsJsonObject();
    JsonArray dataArray = root == null ? null : root.getAsJsonArray("data");
    int numRcds = dataArray == null ? 0 : dataArray.size();

    if (numRcds == 0) {
        return itr;
    }

    List<LocatedRow> rows = new ArrayList<LocatedRow>();
    //Loop through each of the entries in the array
    for (int i = 0; i < numRcds; i++) {

        //The definition of the row to be returned
        ExecRow returnRow = execRow.getClone();

        //Reset the column counter
        int column = 1;

        JsonObject json = dataArray.get(i).getAsJsonObject();

        //Retrieve the properties for each entry
        Set<Entry<String, JsonElement>> keys = json.entrySet();
        for (Map.Entry<String, JsonElement> entry : keys) {
            String key = entry.getKey();
            JsonElement valueElem = json.get(key);

            DataValueDescriptor dvd = returnRow.getColumn(column);
            int type = dvd.getTypeFormatId();

            String value = valueElem.getAsJsonPrimitive().getAsString();

            switch (type) {
            case StoredFormatIds.SQL_TIME_ID:
                if (calendar == null)
                    calendar = new GregorianCalendar();
                //if (timeFormat == null || value==null){
                ((DateTimeDataValue) dvd).setValue(value, calendar);
                // }else
                //     dvd.setValue(SpliceDateFunctions.TO_TIME(value, timeFormat),calendar);
                break;
            case StoredFormatIds.SQL_DATE_ID:
                if (calendar == null)
                    calendar = new GregorianCalendar();
                //if (dateTimeFormat == null || value == null)
                ((DateTimeDataValue) dvd).setValue(value, calendar);
                //else
                //    dvd.setValue(SpliceDateFunctions.TO_DATE(value, dateTimeFormat),calendar);
                break;
            case StoredFormatIds.SQL_TIMESTAMP_ID:
                if (calendar == null)
                    calendar = new GregorianCalendar();
                //if (timestampFormat == null || value==null)
                ((DateTimeDataValue) dvd).setValue(value, calendar);
                //else
                //    dvd.setValue(SpliceDateFunctions.TO_TIMESTAMP(value, timestampFormat),calendar);
                break;
            default:
                dvd.setValue(value);

            }
            column++;
        }

        rows.add(new LocatedRow(returnRow));
    }
    return rows.iterator();
}

From source file:com.stackmob.sdk.callback.StackMobBinaryCallback.java

License:Apache License

private boolean isTemporaryPasswordMessage(String name) {
    try {/*from   w  w  w  .ja v a  2s  .c  o m*/
        String test = new String(responseBody, "UTF-8");
        JsonElement message = new JsonParser().parse(new String(responseBody, "UTF-8")).getAsJsonObject()
                .get(name);
        return message != null && message.isJsonPrimitive() && message.getAsJsonPrimitive().isString()
                && message.getAsString().startsWith("Temporary password reset required.");
    } catch (Exception e) {
        return false;
    }
}

From source file:com.stackmob.sdk.callback.StackMobCallback.java

License:Apache License

private boolean isTemporaryPasswordMessage(String name) {
    boolean matched = false;
    try {//  w  w w.  j  a v a2  s.  com
        JsonElement message = new JsonParser().parse(new String(responseBody, "UTF-8")).getAsJsonObject()
                .get(name);
        matched = message != null && message.isJsonPrimitive() && message.getAsJsonPrimitive().isString()
                && message.getAsString().startsWith("Temporary password reset required.");
    } catch (Throwable ignore) {
    }
    return matched;
}