Example usage for com.google.gson JsonArray size

List of usage examples for com.google.gson JsonArray size

Introduction

In this page you can find the example usage for com.google.gson JsonArray size.

Prototype

public int size() 

Source Link

Document

Returns the number of elements in the array.

Usage

From source file:com.google.samples.apps.iosched.server.schedule.model.DataExtractor.java

License:Open Source License

public JsonArray extractVideoSessions(JsonDataSources sources) {
    videoSessionsById = new HashMap<String, JsonObject>();
    if (categoryToTagMap == null) {
        throw new IllegalStateException("You need to extract tags before attempting to extract video sessions");
    }//from   w  w  w  .java2  s . c o m
    if (speakersById == null) {
        throw new IllegalStateException(
                "You need to extract speakers before attempting to extract video sessions");
    }

    JsonArray result = new JsonArray();
    JsonDataSource source = sources.getSource(InputJsonKeys.VendorAPISource.MainTypes.topics.name());
    if (source != null) {
        for (JsonObject origin : source) {

            if (!isVideoSession(origin)) {
                continue;
            }
            if (isHiddenSession(origin)) {
                // Sessions with a "Hidden from schedule" flag should be ignored
                continue;
            }

            JsonObject dest = new JsonObject();

            JsonPrimitive vid = setVideoForVideoSession(origin, dest);

            JsonElement id = get(origin, InputJsonKeys.VendorAPISource.Topics.id);
            // video library id must be the Youtube video id
            set(vid, dest, OutputJsonKeys.VideoLibrary.id);
            set(origin, InputJsonKeys.VendorAPISource.Topics.title, dest, OutputJsonKeys.VideoLibrary.title,
                    obfuscate ? Converters.OBFUSCATE : null);
            set(origin, InputJsonKeys.VendorAPISource.Topics.description, dest,
                    OutputJsonKeys.VideoLibrary.desc, obfuscate ? Converters.OBFUSCATE : null);
            set(new JsonPrimitive(Config.CONFERENCE_YEAR), dest, OutputJsonKeys.VideoLibrary.year);

            JsonElement videoTopic = null;
            JsonArray categories = origin
                    .getAsJsonArray(InputJsonKeys.VendorAPISource.Topics.categoryids.name());
            for (JsonElement category : categories) {
                JsonObject tag = categoryToTagMap.get(category.getAsString());
                if (tag != null) {
                    if (isHashtag(tag)) {
                        videoTopic = get(tag, OutputJsonKeys.Tags.name);
                        // by definition, the first tag that can be a hashtag (usually a TOPIC) is considered the video tag
                        break;
                    }
                }
            }
            if (videoTopic != null) {
                set(videoTopic, dest, OutputJsonKeys.VideoLibrary.topic);
            }

            // Concatenate speakers:
            JsonArray speakers = getAsArray(origin, InputJsonKeys.VendorAPISource.Topics.speakerids);
            StringBuilder sb = new StringBuilder();
            if (speakers != null)
                for (int i = 0; i < speakers.size(); i++) {
                    String speakerId = speakers.get(i).getAsString();
                    usedSpeakers.add(speakerId);
                    JsonObject speaker = speakersById.get(speakerId);
                    if (speaker != null) {
                        sb.append(get(speaker, OutputJsonKeys.Speakers.name).getAsString());
                        if (i < speakers.size() - 1)
                            sb.append(", ");
                    }
                }
            set(new JsonPrimitive(sb.toString()), dest, OutputJsonKeys.VideoLibrary.speakers);
            videoSessionsById.put(id.getAsString(), dest);
            result.add(dest);
        }
    }
    return result;
}

From source file:com.google.walkaround.proto.gson.RobotSearchDigestGsonImpl.java

License:Apache License

@Override
public void fromGson(JsonElement json, Gson gson, RawStringData raw) throws GsonException {
    reset();/*www .j  a  v a2 s  .co  m*/
    JsonObject jsonObject = json.getAsJsonObject();
    // NOTE: always check with has(...) as the json might not have all required
    // fields set.
    if (jsonObject.has("1")) {
        setWaveId(jsonObject.get("1").getAsString());
    }
    if (jsonObject.has("2")) {
        JsonArray array = jsonObject.get("2").getAsJsonArray();
        for (int i = 0; i < array.size(); i++) {
            addParticipant(array.get(i).getAsString());
        }
    }
    if (jsonObject.has("3")) {
        setTitle(jsonObject.get("3").getAsString());
    }
    if (jsonObject.has("4")) {
        setSnippet(jsonObject.get("4").getAsString());
    }
    if (jsonObject.has("5")) {
        setLastModifiedMillis(GsonUtil.fromJson(jsonObject.get("5")));
    }
    if (jsonObject.has("6")) {
        setBlipCount(jsonObject.get("6").getAsInt());
    }
    if (jsonObject.has("7")) {
        setUnreadBlipCount(jsonObject.get("7").getAsInt());
    }
}

From source file:com.google.wave.api.impl.EventMessageBundleGsonAdaptor.java

License:Apache License

@Override
public EventMessageBundle deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject jsonObj = json.getAsJsonObject();
    String robotAddress = jsonObj.get(ROBOT_ADDRESS_TAG).getAsString();
    String rpcServerUrl = "";
    if (jsonObj.has(RPC_SERVER_URL_TAG)) {
        rpcServerUrl = jsonObj.get(RPC_SERVER_URL_TAG).getAsString();
    }// w  ww  .  ja v  a  2 s .  c  o  m
    EventMessageBundle result = new EventMessageBundle(robotAddress, rpcServerUrl);

    OperationQueue operationQueue;
    if (jsonObj.has(PROXYING_FOR_TAG)) {
        result.setProxyingFor(jsonObj.get(PROXYING_FOR_TAG).getAsString());
        operationQueue = new OperationQueue(new ArrayList<OperationRequest>(), result.getProxyingFor());
    } else {
        operationQueue = new OperationQueue();
    }

    // Deserialize wavelet.
    WaveletData waveletData = context.deserialize(jsonObj.get(WAVELET_TAG), WaveletData.class);
    result.setWaveletData(waveletData);
    Map<String, Blip> blips = new HashMap<String, Blip>();
    Map<String, BlipThread> threads = new HashMap<String, BlipThread>();
    Wavelet wavelet = Wavelet.deserialize(operationQueue, blips, threads, waveletData);
    wavelet.setRobotAddress(robotAddress);
    result.setWavelet(wavelet);

    // Deserialize threads.
    Map<String, BlipThread> tempThreads = context.deserialize(jsonObj.get(THREADS_TAG),
            GsonFactory.THREAD_MAP_TYPE);
    for (Entry<String, BlipThread> entry : tempThreads.entrySet()) {
        BlipThread thread = entry.getValue();
        threads.put(entry.getKey(),
                new BlipThread(thread.getId(), thread.getLocation(), thread.getBlipIds(), blips));
    }

    // Deserialize blips.
    Map<String, BlipData> blipDatas = context.deserialize(jsonObj.get(BLIPS_TAG), GsonFactory.BLIP_MAP_TYPE);
    result.setBlipData(blipDatas);
    for (Entry<String, BlipData> entry : blipDatas.entrySet()) {
        blips.put(entry.getKey(), Blip.deserialize(operationQueue, wavelet, entry.getValue()));
    }

    // Deserialize events.
    JsonArray eventsArray = jsonObj.get(EVENTS_TAG).getAsJsonArray();
    List<Event> events = new ArrayList<Event>(eventsArray.size());
    for (JsonElement element : eventsArray) {
        JsonObject eventObject = element.getAsJsonObject();
        try {
            events.add(EventSerializer.deserialize(wavelet, result, eventObject, context));
        } catch (EventSerializationException e) {
            throw new JsonParseException(e.getMessage());
        }
    }
    result.setEvents(events);
    return result;
}

From source file:com.google.wave.api.RobotSerializer.java

License:Apache License

/**
 * Deserializes operations. This method supports only the new JSON-RPC style
 * operations./*from   ww  w .  j  a va  2s.  co  m*/
 *
 * @param jsonString the operations JSON string to deserialize.
 * @return a list of {@link OperationRequest},that represents the operations.
 * @throws InvalidRequestException if there is a problem deserializing the
 *     operations.
 */
public List<OperationRequest> deserializeOperations(String jsonString) throws InvalidRequestException {
    if (Util.isEmptyOrWhitespace(jsonString)) {
        return Collections.emptyList();
    }

    // Parse incoming operations.
    JsonArray requestsAsJsonArray = null;

    JsonElement json = null;
    try {
        json = jsonParser.parse(jsonString);
    } catch (JsonParseException e) {
        throw new InvalidRequestException("Couldn't deserialize incoming operations: " + jsonString, null, e);
    }

    if (json.isJsonArray()) {
        requestsAsJsonArray = json.getAsJsonArray();
    } else {
        requestsAsJsonArray = new JsonArray();
        requestsAsJsonArray.add(json);
    }

    // Convert incoming operations into a list of JsonRpcRequest.
    ProtocolVersion protocolVersion = determineProtocolVersion(requestsAsJsonArray);
    PROTOCOL_VERSION_COUNTERS.get(protocolVersion).incrementAndGet();
    List<OperationRequest> requests = new ArrayList<OperationRequest>(requestsAsJsonArray.size());
    for (JsonElement requestAsJsonElement : requestsAsJsonArray) {
        validate(requestAsJsonElement);
        requests.add(getGson(protocolVersion).fromJson(requestAsJsonElement, OperationRequest.class));
    }
    return requests;
}

From source file:com.google.wave.api.RobotSerializer.java

License:Apache License

/**
 * Determines the protocol version of a given operation bundle JSON by
 * inspecting the first operation in the bundle. If it is a
 * {@code robot.notify} operation, and contains {@code protocolVersion}
 * parameter, then this method will return the value of that parameter.
 * Otherwise, this method will return the default version.
 *
 * @param operationBundle the operation bundle to check.
 * @return the wire protocol version of the given operation bundle.
 *///from www  .  j av a 2s . c  om
private ProtocolVersion determineProtocolVersion(JsonArray operationBundle) {
    if (operationBundle.size() == 0 || !operationBundle.get(0).isJsonObject()) {
        return defaultProtocolVersion;
    }

    JsonObject firstOperation = operationBundle.get(0).getAsJsonObject();
    if (!firstOperation.has(RequestProperty.METHOD.key())) {
        return defaultProtocolVersion;
    }

    String method = firstOperation.get(RequestProperty.METHOD.key()).getAsString();
    if (isRobotNotifyOperationMethod(method)) {
        JsonObject params = firstOperation.get(RequestProperty.PARAMS.key()).getAsJsonObject();
        if (params.has(ParamsProperty.PROTOCOL_VERSION.key())) {
            JsonElement protocolVersionElement = params.get(ParamsProperty.PROTOCOL_VERSION.key());
            if (!protocolVersionElement.isJsonNull()) {
                return ProtocolVersion.fromVersionString(protocolVersionElement.getAsString());
            }
        }
    }
    return defaultProtocolVersion;
}

From source file:com.google.wave.splash.data.serialize.JsonSerializer.java

License:Apache License

private JsonObject getDataObject(String json) {
    if (json == null) {
        return null;
    }//from  www  .j a va2 s . c o m
    JsonArray array = parser.parse(json).getAsJsonArray();
    if (array.size() == 0) {
        return null;
    }
    return array.get(0).getAsJsonObject().getAsJsonObject("data");
}

From source file:com.googleapis.maps.services.impl.DistanceMatrixQueryImpl.java

License:Apache License

protected List<DistanceMatrixResult> unmarshallList(JsonObject response) {
    String status = response.get("status").getAsString();
    if (!"OK".equals(status) && !"ZERO_RESULTS".equals(status)) {
        throw createGoogleMapsException(status);
    }//from   w w w  .j  a  v a2 s. com
    List<String> originAddresses = unmarshall(new TypeToken<List<String>>() {
    }, response.get("origin_addresses"));
    List<String> destinationAddresses = unmarshall(new TypeToken<List<String>>() {
    }, response.get("destination_addresses"));

    ArrayList<DistanceMatrixResult> list = new ArrayList<DistanceMatrixResult>();
    JsonArray results = response.get("rows").getAsJsonArray();
    for (int i = 0; i < results.size(); i++) {
        JsonElement object = results.get(i);
        List<DistanceMatrixResult> elements = unmarshall(new TypeToken<List<DistanceMatrixResult>>() {
        }, object.getAsJsonObject().get("elements"));
        for (int j = 0; j < elements.size(); j++) {
            DistanceMatrixResult element = elements.get(j);
            element.setOriginAddress(originAddresses.get(i));
            element.setDestinationAddress(destinationAddresses.get(j));
            list.add(element);
        }
    }
    return list;
}

From source file:com.googlecode.goclipse.tooling.oracle.GuruPackageDescribeParser.java

License:Open Source License

protected ArrayList2<StructureElement> parseElements(JsonArray members, boolean parsingMethods)
        throws CommonException {
    ArrayList2<StructureElement> elements = new ArrayList2<>();

    if (members != null) {
        for (int i = 0; i < members.size(); i++) {
            JsonElement arrayElement = members.get(i);
            if (arrayElement.isJsonObject()) {
                JsonObject jsonObject = arrayElement.getAsJsonObject();
                StructureElement structureElement = parseStructureElement(jsonObject, parsingMethods);
                if (structureElement == null) {
                    continue; // Can happen for external elements
                }/* ww  w.j  a va2  s . c  o  m*/
                elements.add(structureElement);
            } else {
                throw new CommonException("'members' array element is not a JSONObject: " + arrayElement);
            }
        }
    }

    Collections.sort(elements, new Comparator<StructureElement>() {
        @Override
        public int compare(StructureElement o1, StructureElement o2) {
            SourceRange sr1 = o1.getSourceRange();
            SourceRange sr2 = o2.getSourceRange();

            int cmp = sr1.getOffset() - sr2.getOffset();
            if (cmp == 0) {
                int offset1 = o1.getNameSourceRange2() == null ? 0 : o1.getNameSourceRange2().getOffset();
                int offset2 = o2.getNameSourceRange2() == null ? 0 : o2.getNameSourceRange2().getOffset();
                return offset1 - offset2;
            }
            return cmp;
        }
    });

    return elements;
}

From source file:com.graphhopper.json.FeatureJsonDeserializer.java

License:Apache License

@Override
public JsonFeature deserialize(JsonElement json, Type type, JsonDeserializationContext context)
        throws JsonParseException {
    try {/*from  w  w  w  .j  a v a  2 s.  c o m*/
        JsonObject obj = json.getAsJsonObject();
        String id, strType = null;
        Map<String, Object> properties = null;
        BBox bbox = null;
        Geometry geometry = null;

        // TODO ensure uniqueness
        if (obj.has("id"))
            id = obj.get("id").getAsString();
        else
            id = UUID.randomUUID().toString();

        if (obj.has("properties")) {
            properties = context.deserialize(obj.get("properties"), Map.class);
        }

        if (obj.has("bbox"))
            bbox = parseBBox(obj.get("bbox").getAsJsonArray());

        if (obj.has("geometry")) {
            JsonObject geometryJson = obj.get("geometry").getAsJsonObject();

            if (geometryJson.has("coordinates")) {
                if (!geometryJson.has("type"))
                    throw new IllegalArgumentException("No type for non-empty coordinates specified");

                strType = context.deserialize(geometryJson.get("type"), String.class);
                if ("Point".equals(strType)) {
                    JsonArray arr = geometryJson.get("coordinates").getAsJsonArray();
                    double lon = arr.get(0).getAsDouble();
                    double lat = arr.get(1).getAsDouble();
                    if (arr.size() == 3)
                        geometry = new Point(lat, lon, arr.get(2).getAsDouble());
                    else
                        geometry = new Point(lat, lon);

                } else if ("MultiPoint".equals(strType)) {
                    geometry = parseLineString(geometryJson);

                } else if ("LineString".equals(strType)) {
                    geometry = parseLineString(geometryJson);

                } else {
                    throw new IllegalArgumentException("Coordinates type " + strType + " not yet supported");
                }
            }
        }

        return new JsonFeature(id, strType, bbox, geometry, properties);

    } catch (Exception ex) {
        throw new JsonParseException("Problem parsing JSON feature " + json);
    }
}

From source file:com.graphhopper.json.FeatureJsonDeserializer.java

License:Apache License

LineString parseLineString(JsonObject geometry) {
    JsonArray arr = geometry.get("coordinates").getAsJsonArray();
    boolean is3D = arr.size() == 0 || arr.get(0).getAsJsonArray().size() == 3;
    LineString lineString = new LineString(arr.size(), is3D);

    for (int i = 0; i < arr.size(); i++) {
        JsonArray pointArr = arr.get(i).getAsJsonArray();
        double lon = pointArr.get(0).getAsDouble();
        double lat = pointArr.get(1).getAsDouble();
        if (pointArr.size() == 3)
            lineString.add(lat, lon, pointArr.get(2).getAsDouble());
        else/* ww  w .  j av a 2 s. com*/
            lineString.add(lat, lon);
    }
    return lineString;
}