Example usage for com.google.gson JsonElement getAsJsonArray

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

Introduction

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

Prototype

public JsonArray getAsJsonArray() 

Source Link

Document

convenience method to get this element as a JsonArray .

Usage

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;/*from  ww  w . j  ava2 s . 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 {/*from www  .  j a  v a 2 s. co  m*/
        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.dart.server.internal.remote.processor.JsonProcessor.java

License:Open Source License

/**
 * Safely get some member off of the passed {@link JsonObject} and return the {@link JsonArray}.
 * Instead of calling {@link JsonObject#has(String)} before {@link JsonObject#get(String)}, only
 * one call to the {@link JsonObject} is made in order to be faster. The result will be
 * {@code null} if the member is not on the {@link JsonObject}. This is used for optional json
 * parameters./*from   w  ww. j a  v  a  2s .c o  m*/
 * 
 * @param jsonObject the {@link JsonObject}
 * @param memberName the member name
 * @return the looked up {@link JsonArray}, or {@code null}
 */
protected JsonArray safelyGetAsJsonArray(JsonObject jsonObject, String memberName) {
    JsonElement jsonElement = jsonObject.get(memberName);
    if (jsonElement == null) {
        return null;
    } else {
        return jsonElement.getAsJsonArray();
    }
}

From source file:com.google.dart.server.internal.remote.processor.NotificationAnalysisErrorsProcessor.java

License:Open Source License

/**
 * Process the given {@link JsonObject} notification and notify {@link #listener}.
 *//* w  w w. j a va 2  s .  co  m*/
@Override
public void process(JsonObject response) throws Exception {
    JsonObject paramsObject = response.get("params").getAsJsonObject();
    String file = paramsObject.get("file").getAsString();
    // prepare error objects iterator
    JsonElement errorsElement = paramsObject.get("errors");
    // notify listener
    getListener().computedErrors(file, AnalysisError.fromJsonArray(errorsElement.getAsJsonArray()));
}

From source file:com.google.dart.server.internal.remote.processor.NotificationExecutionLaunchDataProcessor.java

License:Open Source License

@Override
public void process(JsonObject response) throws Exception {
    JsonObject paramsObject = response.get("params").getAsJsonObject();
    String file = paramsObject.get("file").getAsString();
    JsonElement jsonKind = paramsObject.get("kind");
    String kind = jsonKind == null ? null : jsonKind.getAsString();
    JsonElement jsonFiles = paramsObject.get("referencedFiles");
    JsonArray referencedFiles = jsonFiles == null ? null : jsonFiles.getAsJsonArray();
    getListener().computedLaunchData(file, kind, constructStringArray(referencedFiles));
}

From source file:com.google.debugging.sourcemap.SourceMapObject.java

License:Apache License

private static String[] getJavaStringArray(JsonElement element) throws JsonParseException {
    if (element == null) {
        return null;
    }/*from  w  w  w  . ja v  a 2  s .  c  o  m*/
    JsonArray array = element.getAsJsonArray();
    int len = array.size();
    String[] result = new String[len];
    for (int i = 0; i < len; i++) {
        result[i] = array.get(i).getAsString();
    }
    return result;
}

From source file:com.google.debugging.sourcemap.SourceMapObjectParser.java

License:Apache License

private static String[] getJavaStringArray(JsonElement element) {
    if (element == null) {
        return null;
    }/*from ww w.  ja  v a 2s  . com*/
    JsonArray array = element.getAsJsonArray();
    int len = array.size();
    String[] result = new String[len];
    for (int i = 0; i < len; i++) {
        result[i] = array.get(i).getAsString();
    }
    return result;
}

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 . ja  v  a  2  s .c o  m

    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.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");
    }//  w  w w .j a  v a  2  s .c  o  m
    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;
}

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

License:Open Source License

private void setRelatedVideos(JsonObject origin, JsonObject dest) {
    JsonArray related = getAsArray(origin, VendorAPISource.Topics.related);
    if (related == null) {
        return;//from  www . ja v a 2 s. c  om
    }
    for (JsonElement el : related) {
        if (!el.isJsonObject()) {
            continue;
        }
        JsonObject obj = el.getAsJsonObject();
        if (!obj.has("name") || !obj.has("values")) {
            continue;
        }

        if (InputJsonKeys.VendorAPISource.Topics.RELATED_NAME_VIDEO
                .equals(obj.getAsJsonPrimitive("name").getAsString())) {

            JsonElement values = obj.get("values");
            if (!values.isJsonArray()) {
                continue;
            }

            // As per the data specification, related content is formatted as
            // "video1 title1\nvideo2 title2\n..."
            StringBuilder relatedContentStr = new StringBuilder();
            for (JsonElement value : values.getAsJsonArray()) {
                String relatedSessionId = value.getAsString();
                JsonObject relatedVideo = videoSessionsById.get(relatedSessionId);
                if (relatedVideo != null) {
                    JsonElement vid = get(relatedVideo, OutputJsonKeys.VideoLibrary.vid);
                    JsonElement title = get(relatedVideo, OutputJsonKeys.VideoLibrary.title);
                    if (vid != null && title != null) {
                        relatedContentStr.append(vid.getAsString()).append(" ").append(title.getAsString())
                                .append("\n");
                    }
                }
            }
            set(new JsonPrimitive(relatedContentStr.toString()), dest, OutputJsonKeys.Sessions.relatedContent);
        }
    }
}