Example usage for com.google.gson JsonPrimitive toString

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

Introduction

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

Prototype

@Override
public String toString() 

Source Link

Document

Returns a String representation of this element.

Usage

From source file:ccm.pay2spawn.util.JsonNBTHelper.java

License:Open Source License

/**
 * There is no way to detect number types and NBT is picky about this. Lets hope the original type id is there, otherwise we are royally screwed.
 *//* w  ww .  j  a  va2  s  .c  o m*/
public static NBTBase parseJSON(JsonPrimitive element) {
    String string = element.getAsString();
    if (string.contains(":")) {
        for (int id = 0; id < NBTTypes.length; id++) {
            if (string.startsWith(NBTTypes[id] + ":")) {
                String value = string.replace(NBTTypes[id] + ":", "");
                value = RandomRegistry.solveRandom(id, value);
                switch (id) {
                // 0 = END
                case BYTE:
                    return new NBTTagByte(Byte.parseByte(value));
                case SHORT:
                    return new NBTTagShort(Short.parseShort(value));
                case INT:
                    return new NBTTagInt(Integer.parseInt(value));
                case LONG:
                    return new NBTTagLong(Long.parseLong(value));
                case FLOAT:
                    return new NBTTagFloat(Float.parseFloat(value));
                case DOUBLE:
                    return new NBTTagDouble(Double.parseDouble(value));
                case BYTE_ARRAY:
                    return parseJSONByteArray(value);
                case STRING:
                    return new NBTTagString(value);
                // 9 = LIST != JsonPrimitive
                // 10 = COMPOUND != JsonPrimitive
                case INT_ARRAY:
                    return parseJSONIntArray(value);
                }
            }
        }
    }

    // Now it becomes guesswork.
    if (element.isString())
        return new NBTTagString(string);
    if (element.isBoolean())
        return new NBTTagByte((byte) (element.getAsBoolean() ? 1 : 0));

    Number n = element.getAsNumber();
    if (n instanceof Byte)
        return new NBTTagByte(n.byteValue());
    if (n instanceof Short)
        return new NBTTagShort(n.shortValue());
    if (n instanceof Integer)
        return new NBTTagInt(n.intValue());
    if (n instanceof Long)
        return new NBTTagLong(n.longValue());
    if (n instanceof Float)
        return new NBTTagFloat(n.floatValue());
    if (n instanceof Double)
        return new NBTTagDouble(n.doubleValue());

    throw new NumberFormatException(element.toString() + " is was not able to be parsed.");
}

From source file:ccm.pay2spawn.util.JsonNBTHelper.java

License:Open Source License

public static JsonPrimitive fixNulls(JsonPrimitive primitive) {
    if (primitive.isBoolean())
        return new JsonPrimitive(primitive.getAsBoolean());
    if (primitive.isNumber())
        return new JsonPrimitive(primitive.getAsNumber());
    if (primitive.isString())
        return new JsonPrimitive(primitive.getAsString());
    return JSON_PARSER.parse(primitive.toString()).getAsJsonPrimitive();
}

From source file:com.cinchapi.concourse.importer.LineBasedImporter.java

License:Apache License

/**
 * At a minimum, this method is responsible for taking a raw source string
 * value and converting it to a {@link JsonElement}. The default
 * implementation makes an effort to represent numeric and boolean values as
 * appropriate {@link JsonPrimitive json primitives}. All other kinds of
 * values are represented as strings, which is the correct format for the
 * server to handle masquerading types (i.e. resolvable links, links, tags,
 * forced doubles, etc)./*from  w  w  w.j  a v a2  s.  c o m*/
 * <p>
 * The default behaviour is appropriate in most cases, but this method can
 * be used by subclasses to define dynamic intermediary transformations to
 * data to better prepare it for import.
 * </p>
 * <h1>Examples</h1> <h2>Specifying Link Resolution</h2>
 * <p>
 * The server will convert raw data of the form
 * <code>@&lt;key&gt;@value@&lt;key&gt;@</code> into a Link to all the
 * records where key equals value in Concourse. For this purpose, the
 * subclass can convert the raw value to this form using the
 * {@link Convert#stringToResolvableLinkSpecification(String, String)}
 * method.
 * </p>
 * <p>
 * <h2>Normalizing Data</h2>
 * It may be desirable to normalize the raw data before input. For example,
 * the subclass may wish to convert all strings to a specific case, or
 * sanitize inputs, etc.
 * </p>
 * <p>
 * <h2>Compacting Representation</h2>
 * If a column in a file contains a enumerated set of string values, it may
 * be desirable to transform the values to a string representation of a
 * number so that, when converted, the data is more compact and takes up
 * less space.
 * </p>
 * 
 * @param key
 * @param value
 * @return the transformed values in a JsonArray
 */
protected JsonElement transformValue(String key, String value) {
    JsonPrimitive element;
    Object parsed;
    if ((parsed = Strings.tryParseNumberStrict(value)) != null) {
        element = new JsonPrimitive((Number) parsed);
    } else if ((parsed = Strings.tryParseBoolean(value)) != null) {
        element = new JsonPrimitive((Boolean) parsed);
    } else {
        element = new JsonPrimitive(value);
        element.toString();
    }
    return element;
}

From source file:com.google.appinventor.components.runtime.GoogleMap.java

License:Open Source License

@SimpleFunction(description = "Adding a list of markers that are represented as JsonArray. "
        + " The inner JsonObject represents a marker"
        + "and is composed of name-value pairs. Name fields for a marker are: "
        + "\"lat\" (type double) [required], \"lng\"(type double) [required], "
        + "\"color\"(type int)[in hue value ranging from 0~360], "
        + "\"title\"(type String), \"snippet\"(type String), \"draggable\"(type boolean)")
public void AddMarkersFromJson(String jsonString) {
    ArrayList<Integer> markerIds = new ArrayList<Integer>();
    JsonParser parser = new JsonParser();
    float[] hsv = new float[3];

    // parse jsonString into jsonArray
    try {/*from  ww w . j  a va  2  s  .  com*/
        JsonElement markerList = parser.parse(jsonString);
        if (markerList.isJsonArray()) {
            JsonArray markerArray = markerList.getAsJsonArray();

            Log.i(TAG, "It's a JsonArry: " + markerArray.toString());
            for (JsonElement marker : markerArray) {
                boolean addOne = true;
                // now we have marker
                if (marker.isJsonObject()) {
                    JsonObject markerJson = marker.getAsJsonObject();
                    if (markerJson.get("lat") == null || markerJson.get("lng") == null) {
                        addOne = false;

                    } else { // having correct syntax of a marker in Json

                        // check for cases: "lat" : "40.7561"  (as String)
                        JsonPrimitive jpLat = (JsonPrimitive) markerJson.get("lat");
                        JsonPrimitive jpLng = (JsonPrimitive) markerJson.get("lng");

                        double latitude = 0;
                        double longitude = 0;

                        try { //it's possible that when converting to Double, we will have errors
                              // for example, some json has "lat": "" (empty string for lat, lng values)

                            if (jpLat.isString() && jpLng.isString()) {
                                Log.i(TAG, "jpLat:" + jpLat.toString());
                                Log.i(TAG, "jpLng:" + jpLng.toString());

                                latitude = new Double(jpLat.getAsString());
                                longitude = new Double(jpLng.getAsString());
                                Log.i(TAG, "convert to double:" + latitude + "," + longitude);
                            } else {
                                latitude = markerJson.get("lat").getAsDouble();
                                longitude = markerJson.get("lng").getAsDouble();
                            }

                        } catch (NumberFormatException e) {
                            addOne = false;
                        }
                        // check for Lat, Lng correct range

                        if ((latitude < -90) || (latitude > 90) || (longitude < -180) || (longitude > 180)) {
                            Log.i(TAG, "Lat/Lng wrong range:" + latitude + "," + longitude);
                            addOne = false;

                        }

                        Color.colorToHSV(mMarkerColor, hsv);
                        float defaultColor = hsv[0];
                        float color = (markerJson.get("color") == null) ? defaultColor
                                : markerJson.get("color").getAsInt();

                        if ((color < 0) || (color > 360)) {
                            Log.i(TAG, "Wrong color");
                            addOne = false;
                        }

                        String title = (markerJson.get("title") == null) ? ""
                                : markerJson.get("title").getAsString();
                        String snippet = (markerJson.get("snippet") == null) ? ""
                                : markerJson.get("snippet").getAsString();
                        boolean draggable = (markerJson.get("draggable") == null) ? mMarkerDraggable
                                : markerJson.get("draggable").getAsBoolean();

                        if (addOne) {
                            Log.i(TAG, "Adding marker" + latitude + "," + longitude);
                            int uniqueId = generateMarkerId();
                            markerIds.add(uniqueId);
                            addMarkerToMap(latitude, longitude, uniqueId, color, title, snippet, draggable);
                        }
                    }
                }
            } //end of JsonArray

        } else { // not a JsonArray
            form.dispatchErrorOccurredEvent(this, "AddMarkersFromJson",
                    ErrorMessages.ERROR_GOOGLE_MAP_INVALID_INPUT,
                    "markers needs to be represented as JsonArray");
            markersList = YailList.makeList(markerIds);
        }

    } catch (JsonSyntaxException e) {
        form.dispatchErrorOccurredEvent(this, "AddMarkersFromJson",
                ErrorMessages.ERROR_GOOGLE_MAP_JSON_FORMAT_DECODE_FAILED, jsonString);
        markersList = YailList.makeList(markerIds); // return an empty markerIds list
    }

    markersList = YailList.makeList(markerIds);
    //  return YailList.makeList(markerIds);
}

From source file:com.helion3.safeguard.util.DataUtil.java

License:MIT License

/**
 * Convert JSON to a DataContainer.// ww w. ja va  2s  .c  om
 * @param json JsonObject
 * @return DataContainer
 */
public static DataContainer jsonToDataContainer(JsonObject json) {
    DataContainer result = new MemoryDataContainer();

    for (Entry<String, JsonElement> entry : json.entrySet()) {
        DataQuery keyQuery = DataQuery.of(entry.getKey());
        Object object = entry.getValue();

        if (object instanceof JsonObject) {
            result.set(keyQuery, jsonToDataContainer((JsonObject) object));
        } else if (object instanceof JsonArray) {
            JsonArray array = (JsonArray) object;
            Iterator<JsonElement> iterator = array.iterator();

            List<Object> list = new ArrayList<Object>();
            while (iterator.hasNext()) {
                Object child = iterator.next();

                if (child instanceof JsonPrimitive) {
                    JsonPrimitive primitive = (JsonPrimitive) child;

                    if (primitive.isString()) {
                        list.add(primitive.getAsString());
                    } else if (primitive.isNumber()) {
                        // @todo may be wrong format. how do we handle?
                        list.add(primitive.getAsInt());
                    } else if (primitive.isBoolean()) {
                        list.add(primitive.getAsBoolean());
                    } else {
                        SafeGuard.getLogger()
                                .error("Unhandled list JsonPrimitive data type: " + primitive.toString());
                    }
                }
            }

            result.set(keyQuery, list);
        } else {
            if (object instanceof JsonPrimitive) {
                JsonPrimitive primitive = (JsonPrimitive) object;

                if (primitive.isString()) {
                    result.set(keyQuery, primitive.getAsString());
                } else if (primitive.isNumber()) {
                    // @todo may be wrong format. how do we handle?
                    result.set(keyQuery, primitive.getAsInt());
                } else if (primitive.isBoolean()) {
                    result.set(keyQuery, primitive.getAsBoolean());
                } else {
                    SafeGuard.getLogger().error("Unhandled JsonPrimitive data type: " + primitive.toString());
                }
            }
        }
    }

    return result;
}

From source file:com.ls.util.internal.ObjectComparator.java

License:Open Source License

private static Object getDifferencesForPrimitives(JsonPrimitive origin, JsonPrimitive patched) {
    if (patched.equals(origin)) {
        return UNCHANGED;
    } else {//ww w  .j a  va2s. c  om
        return patched.toString();
    }
}

From source file:com.nextdoor.bender.operation.json.key.KeyNameOperation.java

License:Apache License

protected void perform(JsonObject obj) {
    Set<Entry<String, JsonElement>> entries = obj.entrySet();
    Set<Entry<String, JsonElement>> orgEntries = new HashSet<Entry<String, JsonElement>>(entries);

    for (Entry<String, JsonElement> entry : orgEntries) {

        JsonElement val = entry.getValue();
        obj.remove(entry.getKey());//www.j  a  v a 2 s  .  c  om
        String key = entry.getKey().toLowerCase().replaceAll("[ .]", "_");

        if (val.isJsonPrimitive()) {
            JsonPrimitive prim = val.getAsJsonPrimitive();

            if (prim.isBoolean()) {
                obj.add(key + "__bool", val);
            } else if (prim.isNumber()) {
                if (prim.toString().contains(".")) {
                    obj.add(key + "__float", val);
                } else {
                    obj.add(key + "__long", val);
                }
            } else if (prim.isString()) {
                obj.add(key + "__str", val);
            }
        } else if (val.isJsonObject()) {
            obj.add(key, val);
            perform(val.getAsJsonObject());
        } else if (val.isJsonArray()) {
            obj.add(key + "__arr", val);
        }
    }
}

From source file:edu.isi.wings.portal.classes.JsonHandler.java

License:Apache License

private static void addConstraints(Template tpl, String json) {
    JsonElement el = new JsonParser().parse(json);
    for (JsonElement tel : el.getAsJsonArray()) {
        JsonObject triple = tel.getAsJsonObject();
        String subj = triple.getAsJsonObject("subject").get("id").getAsString();
        String pred = triple.getAsJsonObject("predicate").get("id").getAsString();
        JsonObject objitem = triple.getAsJsonObject("object");
        if (objitem.get("value") != null && objitem.get("isLiteral").getAsBoolean()) {
            JsonPrimitive obj = objitem.get("value").getAsJsonPrimitive();
            String objtype = objitem.get("type") != null ? objitem.get("type").getAsString() : null;
            tpl.getConstraintEngine().createNewDataConstraint(subj, pred,
                    obj.isString() ? obj.getAsString() : obj.toString(), objtype);
        } else {//  w w  w . ja  va2  s  . c  o  m
            String obj = objitem.get("id").getAsString();
            tpl.getConstraintEngine().createNewConstraint(subj, pred, obj);
        }
    }
}

From source file:net.doubledoordev.backend.util.JsonNBTHelper.java

License:Open Source License

/**
 * There is no way to detect number types and NBT is picky about this. Lets hope the original type id is there, otherwise we are royally screwed.
 *//*from w  w w . j a  v  a2  s .  c  o  m*/
public static Tag parseJSON(JsonPrimitive element) {
    String string = element.getAsString();
    if (string.contains(":")) {
        String[] split = string.split(":", 2);
        switch (TagType.getByTypeName(split[0])) {
        case TAG_END:
            return new EndTag();
        case TAG_BYTE:
            return new ByteTag("", Byte.parseByte(split[1]));
        case TAG_SHORT:
            return new ShortTag("", Short.parseShort(split[1]));
        case TAG_INT:
            return new IntTag("", Integer.parseInt(split[1]));
        case TAG_LONG:
            return new LongTag("", Long.parseLong(split[1]));
        case TAG_FLOAT:
            return new FloatTag("", Float.parseFloat(split[1]));
        case TAG_DOUBLE:
            return new DoubleTag("", Double.parseDouble(split[1]));
        case TAG_BYTE_ARRAY:
            return parseJSONByteArray(split[1]);
        case TAG_STRING:
            return new StringTag("", split[1]);
        // TAG_LIST != JsonPrimitive
        // TAG_COMPOUND != JsonPrimitive
        case TAG_INT_ARRAY:
            return parseJSONIntArray(split[1]);
        case TAG_SHORT_ARRAY:
            return parseJSONShortArray(split[1]);
        }
    }

    // Now it becomes guesswork.
    if (element.isString())
        return new StringTag("", string);
    if (element.isBoolean())
        return new ByteTag("", element.getAsBoolean());

    Number n = element.getAsNumber();
    if (n instanceof Byte)
        return new ByteTag("", n.byteValue());
    if (n instanceof Short)
        return new ShortTag("", n.shortValue());
    if (n instanceof Integer)
        return new IntTag("", n.intValue());
    if (n instanceof Long)
        return new LongTag("", n.longValue());
    if (n instanceof Float)
        return new FloatTag("", n.floatValue());
    if (n instanceof Double)
        return new DoubleTag("", n.doubleValue());

    try {
        return new IntTag("", Integer.parseInt(element.toString()));
    } catch (NumberFormatException ignored) {

    }
    throw new NumberFormatException(element.getAsNumber() + " is was not able to be parsed.");
}

From source file:net.doubledoordev.backend.util.JsonNBTHelper.java

License:Open Source License

public static JsonPrimitive fixNulls(JsonPrimitive primitive) {
    if (primitive.isBoolean())
        return new JsonPrimitive(primitive.getAsBoolean());
    if (primitive.isNumber())
        return new JsonPrimitive(primitive.getAsNumber());
    if (primitive.isString())
        return new JsonPrimitive(primitive.getAsString());
    return JSONPARSER.parse(primitive.toString()).getAsJsonPrimitive();
}