Example usage for com.google.gson JsonElement isJsonArray

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

Introduction

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

Prototype

public boolean isJsonArray() 

Source Link

Document

provides check for verifying if this element is an array or not.

Usage

From source file:com.github.nyrkovalex.deploy.me.parsing.Parser.java

License:Open Source License

@Override
public Script parse(String path, JsonElement locations) {
    Iterable<String> targets = locations.isJsonArray()
            ? FluentIterable.from(locations.getAsJsonArray()).transform(item -> item.getAsString()).toSet()
            : ImmutableSet.of(locations.getAsString());
    return new Script(path, targets);
}

From source file:com.github.rustdt.tooling.RustJsonMessageParser.java

License:Open Source License

protected ArrayList2<String> parseNotes(JsonElement children) throws CommonException {
    ArrayList2<String> notes = new ArrayList2<>();
    if (children == null || !children.isJsonArray()) {
        return notes;
    }/*w  ww  .j a  v  a2  s .  c o  m*/
    JsonArray childrenArray = children.getAsJsonArray();
    if (childrenArray.size() == 0) {
        return notes;
    }
    for (JsonElement child : childrenArray) {
        if (child.isJsonObject()) {
            String childMessageString = helper.getOptionalString(child.getAsJsonObject(), "message");
            if (childMessageString != null && !childMessageString.isEmpty()) {
                notes.add(childMessageString);
            }
        }
    }
    return notes;
}

From source file:com.github.strawberry.util.Json.java

License:Open Source License

public static Collection parseArray(String json) {
    JsonArray o = (JsonArray) parser.parse(json);
    Collection c = Lists.newArrayList();
    for (JsonElement value : o) {
        if (!value.isJsonPrimitive()) {
            if (value.isJsonArray()) {
                c.add(parseArray(value.toString()));
            } else if (value.isJsonObject()) {
                c.add(parse(value.toString()));
            }/*ww  w. j av a  2  s . c  o  m*/

        } else {
            c.add(parsePrimitive(value));

        }
    }
    return c;
}

From source file:com.github.strawberry.util.Json.java

License:Open Source License

public static Map<String, Object> parse(String json) {
    JsonObject o = (JsonObject) parser.parse(json);
    Set<Map.Entry<String, JsonElement>> set = o.entrySet();
    Map<String, Object> map = Maps.newHashMap();
    for (Map.Entry<String, JsonElement> e : set) {
        String key = e.getKey();/*www  .java2  s  .  c  o m*/
        JsonElement value = e.getValue();
        if (!value.isJsonPrimitive()) {
            if (value.isJsonObject()) {
                map.put(key, parse(value.toString()));

            } else if (value.isJsonArray()) {
                map.put(key, parseArray(value.toString()));

            }
        } else {
            map.put(key, parsePrimitive(value));
        }

    }
    return map;

}

From source file:com.github.zhizheng.json.JsonValueTypes.java

License:Apache License

/**
 *  Json /*from ww  w.j  av a  2  s.c  o  m*/
 * 
 * @param jsonElement
 * @return
 */
public static String getJsonValueType(JsonElement jsonElement) {
    if (jsonElement.isJsonObject()) {
        return OBJECT.toString();
    }
    if (jsonElement.isJsonArray()) {
        return ARRAY.toString();
    }
    if (jsonElement.isJsonPrimitive()) {
        JsonPrimitive asJsonPrimitive = jsonElement.getAsJsonPrimitive();
        if (asJsonPrimitive.isBoolean()) {
            return BOOLEAN.toString();
        }
        if (asJsonPrimitive.isNumber()) {
            return NUMBER.toString();
        }
        return STRING.toString();
    }
    return NULL.toString();
}

From source file:com.goodow.wind.server.rpc.DeltaHandler.java

License:Apache License

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String keyString = requireParameter(req, Params.ID);
    JsonObject toRtn;//  w ww  .jav a2s . co  m
    try {
        if (!keyString.startsWith("[")) {
            Long version = Long.parseLong(requireParameter(req, Params.VERSION));
            String endVersionString = optionalParameter(req, Params.END_VERSION, null);
            Long endVersion = endVersionString == null ? null : Long.parseLong(endVersionString);
            toRtn = fetchHistory(new ObjectId(keyString), version, endVersion);
        } else {
            JsonElement keys = new JsonParser().parse(keyString);
            assert keys.isJsonArray();
            String sid = requireParameter(req, Params.SESSION_ID);
            toRtn = fetchHistories(new SessionId(sid), keys.getAsJsonArray());
        }
    } catch (SlobNotFoundException e) {
        throw new BadRequestException("Object not found or access denied", e);
    } catch (AccessDeniedException e) {
        throw new BadRequestException("Object not found or access denied", e);
    } catch (NumberFormatException nfe) {
        throw new BadRequestException("Parse error", nfe);
    }

    resp.setContentType("application/json");
    Util.writeJsonResult(resp.getWriter(), toRtn.toString());
}

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 {//  ww w  . jav  a  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.google.gwtjsonrpc.server.CallDeserializer.java

License:Apache License

public CallType deserialize(final JsonElement json, final Type typeOfT,
        final JsonDeserializationContext context) throws JsonParseException, NoSuchRemoteMethodException {
    if (!json.isJsonObject()) {
        throw new JsonParseException("Expected object");
    }//from w  w  w . j a  v  a  2 s.  com

    final JsonObject in = json.getAsJsonObject();
    req.id = in.get("id");

    final JsonElement jsonrpc = in.get("jsonrpc");
    final JsonElement version = in.get("version");
    if (isString(jsonrpc) && version == null) {
        final String v = jsonrpc.getAsString();
        if ("2.0".equals(v)) {
            req.versionName = "jsonrpc";
            req.versionValue = jsonrpc;
        } else {
            throw new JsonParseException("Expected jsonrpc=2.0");
        }

    } else if (isString(version) && jsonrpc == null) {
        final String v = version.getAsString();
        if ("1.1".equals(v)) {
            req.versionName = "version";
            req.versionValue = version;
        } else {
            throw new JsonParseException("Expected version=1.1");
        }
    } else {
        throw new JsonParseException("Expected version=1.1 or jsonrpc=2.0");
    }

    final JsonElement method = in.get("method");
    if (!isString(method)) {
        throw new JsonParseException("Expected method name as string");
    }

    req.method = server.lookupMethod(method.getAsString());
    if (req.method == null) {
        throw new NoSuchRemoteMethodException();
    }

    final JsonElement callback = in.get("callback");
    if (callback != null) {
        if (!isString(callback)) {
            throw new JsonParseException("Expected callback as string");
        }
        req.callback = callback.getAsString();
    }

    final JsonElement xsrfKey = in.get("xsrfKey");
    if (xsrfKey != null) {
        if (!isString(xsrfKey)) {
            throw new JsonParseException("Expected xsrfKey as string");
        }
        req.xsrfKeyIn = xsrfKey.getAsString();
    }

    final Type[] paramTypes = req.method.getParamTypes();
    final JsonElement params = in.get("params");
    if (params != null) {
        if (!params.isJsonArray()) {
            throw new JsonParseException("Expected params array");
        }

        final JsonArray paramsArray = params.getAsJsonArray();
        if (paramsArray.size() != paramTypes.length) {
            throw new JsonParseException("Expected " + paramTypes.length + " parameter values in params array");
        }

        final Object[] r = new Object[paramTypes.length];
        for (int i = 0; i < r.length; i++) {
            final JsonElement v = paramsArray.get(i);
            if (v != null) {
                r[i] = context.deserialize(v, paramTypes[i]);
            }
        }
        req.params = r;
    } else {
        if (paramTypes.length != 0) {
            throw new JsonParseException("Expected params array");
        }
        req.params = JsonServlet.NO_PARAMS;
    }

    return req;
}

From source file:com.google.gwtjsonrpc.server.MapDeserializer.java

License:Apache License

public Map<Object, Object> deserialize(final JsonElement json, final Type typeOfT,
        final JsonDeserializationContext context) throws JsonParseException {
    final Type kt = ((ParameterizedType) typeOfT).getActualTypeArguments()[0];
    final Type vt = ((ParameterizedType) typeOfT).getActualTypeArguments()[1];

    if (json.isJsonNull()) {
        return null;
    }//from   w ww.j  ava  2  s .  c o  m

    if (kt == String.class) {
        if (!json.isJsonObject()) {
            throw new JsonParseException("Expected object for map type");
        }
        final JsonObject p = (JsonObject) json;
        final Map<Object, Object> r = createInstance(typeOfT);
        for (final Map.Entry<String, JsonElement> e : p.entrySet()) {
            final Object v = context.deserialize(e.getValue(), vt);
            r.put(e.getKey(), v);
        }
        return r;
    } else {
        if (!json.isJsonArray()) {
            throw new JsonParseException("Expected array for map type");
        }

        final JsonArray p = (JsonArray) json;
        final Map<Object, Object> r = createInstance(typeOfT);
        for (int n = 0; n < p.size();) {
            final Object k = context.deserialize(p.get(n++), kt);
            final Object v = context.deserialize(p.get(n++), vt);
            r.put(k, v);
        }
        return r;
    }
}

From source file:com.google.iosched.model.DataExtractor.java

License:Open Source License

public JsonArray extractSessions(JsonDataSources sources) {
    if (videoSessionsById == null) {
        throw new IllegalStateException(
                "You need to extract video sessions before attempting to extract sessions");
    }//from w ww.ja v  a2s  .  c  om
    if (categoryToTagMap == null) {
        throw new IllegalStateException("You need to extract tags before attempting to extract sessions");
    }

    JsonArray result = new JsonArray();
    JsonDataSource source = sources.getSource(VendorAPISource.MainTypes.topics.name());
    if (source != null) {
        for (JsonObject origin : source) {
            if (isVideoSession(origin)) {
                // Sessions with the Video tag are processed as video library content
                continue;
            }
            if (isHiddenSession(origin)) {
                // Sessions with a "Hidden from schedule" flag should be ignored
                continue;
            }
            JsonElement title = get(origin, VendorAPISource.Topics.title);
            // Since the CMS returns an empty keynote as a session, we need to ignore it
            if (title != null && title.isJsonPrimitive() && "keynote".equalsIgnoreCase(title.getAsString())) {
                continue;
            }
            JsonObject dest = new JsonObject();
            set(origin, VendorAPISource.Topics.id, dest, OutputJsonKeys.Sessions.id);
            set(origin, VendorAPISource.Topics.id, dest, OutputJsonKeys.Sessions.url, Converters.SESSION_URL);
            set(origin, VendorAPISource.Topics.title, dest, OutputJsonKeys.Sessions.title, null);
            set(origin, VendorAPISource.Topics.description, dest, OutputJsonKeys.Sessions.description, null);
            set(origin, VendorAPISource.Topics.start, dest, OutputJsonKeys.Sessions.startTimestamp,
                    Converters.DATETIME);
            set(origin, VendorAPISource.Topics.finish, dest, OutputJsonKeys.Sessions.endTimestamp,
                    Converters.DATETIME);

            JsonElement documents = get(origin, VendorAPISource.Topics.documents);
            if (documents != null && documents.isJsonArray() && documents.getAsJsonArray().size() > 0) {
                // Note that the input for SessionPhotoURL is the entity ID. We simply ignore the original
                // photo URL, because that will be processed by an offline cron script, resizing the
                // photos and saving them to a known location with the entity ID as its base name.
                set(origin, VendorAPISource.Topics.id, dest, OutputJsonKeys.Sessions.photoUrl,
                        Converters.SESSION_PHOTO_URL);
            }

            setVideoPropertiesInSession(origin, dest);
            setRelatedVideos(origin, dest);

            JsonElement mainTag = null;
            JsonElement hashtag = null;
            JsonElement mainTagColor = null;
            JsonArray categories = origin.getAsJsonArray(VendorAPISource.Topics.categoryids.name());
            JsonArray tags = new JsonArray();
            for (JsonElement category : categories) {
                JsonObject tag = categoryToTagMap.get(category.getAsString());
                if (tag != null) {
                    JsonElement tagName = get(tag, OutputJsonKeys.Tags.tag);
                    tags.add(tagName);
                    usedTags.add(tagName.getAsString());

                    if (mainTag == null) {
                        // check if the tag is from a "default" category. For example, if THEME is the default
                        // category, all sessions will have a "mainTag" property set to the first tag of type THEME
                        JsonElement tagCategory = get(tag, OutputJsonKeys.Tags.category); // THEME, TYPE or TOPIC
                        if (tagCategory.equals(mainCategory)) {
                            mainTag = tagName;
                            mainTagColor = get(tag, OutputJsonKeys.Tags.color);
                        }
                        if (hashtag == null && isHashtag(tag)) {
                            hashtag = get(tag, OutputJsonKeys.Tags.hashtag);
                            if (hashtag == null || hashtag.getAsString() == null
                                    || hashtag.getAsString().isEmpty()) {
                                // If no hashtag set in the tagsconf file, we will convert the tagname to find one:
                                hashtag = new JsonPrimitive(
                                        get(tag, OutputJsonKeys.Tags.name, Converters.TAG_NAME).getAsString()
                                                .toLowerCase());
                            }
                        }
                    }
                }
            }
            set(tags, dest, OutputJsonKeys.Sessions.tags);
            if (mainTag != null) {
                set(mainTag, dest, OutputJsonKeys.Sessions.mainTag);
            }
            if (mainTagColor != null) {
                set(mainTagColor, dest, OutputJsonKeys.Sessions.color);
            }
            if (hashtag != null) {
                set(hashtag, dest, OutputJsonKeys.Sessions.hashtag);
            }

            JsonArray speakers = getAsArray(origin, VendorAPISource.Topics.speakerids);
            if (speakers != null)
                for (JsonElement speaker : speakers) {
                    String speakerId = speaker.getAsString();
                    usedSpeakers.add(speakerId);
                }
            set(speakers, dest, OutputJsonKeys.Sessions.speakers);

            JsonArray sessions = origin.getAsJsonArray(VendorAPISource.Topics.sessions.name());
            if (sessions != null && sessions.size() > 0) {
                String roomId = get(sessions.get(0).getAsJsonObject(), VendorAPISource.Sessions.roomid)
                        .getAsString();
                roomId = Config.ROOM_MAPPING.getRoomId(roomId);
                set(new JsonPrimitive(roomId), dest, OutputJsonKeys.Sessions.room);

                // captions URL is set based on the session room, so keep it here.
                String captionsURL = Config.ROOM_MAPPING.getCaptions(roomId);
                if (captionsURL != null) {
                    set(new JsonPrimitive(captionsURL), dest, OutputJsonKeys.Sessions.captionsUrl);
                }
            }

            result.add(dest);
        }
    }
    return result;
}