Example usage for com.google.gson.stream JsonReader nextName

List of usage examples for com.google.gson.stream JsonReader nextName

Introduction

In this page you can find the example usage for com.google.gson.stream JsonReader nextName.

Prototype

public String nextName() throws IOException 

Source Link

Document

Returns the next token, a com.google.gson.stream.JsonToken#NAME property name , and consumes it.

Usage

From source file:com.sap.core.odata.core.ep.consumer.JsonServiceDocumentConsumer.java

License:Apache License

private ServiceDocumentImpl readServiceDocument(final JsonReader reader) throws EntityProviderException {
    try {//from  ww  w  . java2 s .co  m
        reader.beginObject();
        currentHandledObjectName = reader.nextName();
        if (FormatJson.D.equals(currentHandledObjectName)) {
            reader.beginObject();
            readContent(reader);
            reader.endObject();
        }
        reader.endObject();
        reader.peek();
        reader.close();
    } catch (final IOException e) {
        throw new EntityProviderException(
                EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass().getSimpleName()), e);
    } catch (final IllegalStateException e) {
        throw new EntityProviderException(
                EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass().getSimpleName()), e);
    } catch (final EdmException e) {
        throw new EntityProviderException(
                EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass().getSimpleName()), e);
    }
    return new ServiceDocumentImpl().setEntitySetsInfo(entitySets);
}

From source file:com.sap.core.odata.core.ep.consumer.JsonServiceDocumentConsumer.java

License:Apache License

private void readContent(final JsonReader reader) throws IOException, EdmException, EntityProviderException {
    currentHandledObjectName = reader.nextName();
    if (FormatJson.ENTITY_SETS.equals(currentHandledObjectName)) {
        reader.beginArray();/*from   w  ww. j  a v  a2s.  c  o  m*/
        readEntitySets(reader);
        reader.endArray();
    }
}

From source file:com.sap.core.odata.core.ep.util.JsonUtils.java

License:Apache License

public static int startJson(final JsonReader reader) throws EntityProviderException {
    //The enclosing "d" and "results" are optional - so we cannot check for the presence
    //but we have to read over them in case they are present.
    JsonToken token;//from  w ww .  ja  va2 s .c  om
    try {
        token = reader.peek();
        int openJsonObjects = 0;
        if (JsonToken.BEGIN_OBJECT == token) {
            reader.beginObject();
            openJsonObjects++;
            token = reader.peek();
            if (JsonToken.NAME == token) {
                String name = reader.nextName();
                if (!("d".equals(name) ^ "results".equals(name))) {
                    //TODO I18N
                    throw new EntityProviderException(EntityProviderException.COMMON,
                            name + " not expected, only d or results");
                }
            }

            token = reader.peek();
            if (JsonToken.BEGIN_OBJECT == token) {
                reader.beginObject();
                openJsonObjects++;
            } else if (JsonToken.BEGIN_ARRAY == token) {
                //TODO I18N
                throw new EntityProviderException(EntityProviderException.COMMON, "Array not expected");
            }
        }

        return openJsonObjects;
    } catch (IOException e) {
        //TODO I18N
        throw new EntityProviderException(EntityProviderException.COMMON, e);
    }
}

From source file:com.seleritycorp.common.base.coreservices.RawCoreServiceClient.java

License:Apache License

private void pushToWriter(JsonReader reader, JsonWriter writer) throws IOException {
    int count = 0;
    boolean isObject = reader.peek() == JsonToken.BEGIN_OBJECT;
    do {//from   w  ww . jav a 2  s  . c  om
        JsonToken jsToken = reader.peek();
        switch (jsToken) {
        case BEGIN_ARRAY:
            reader.beginArray();
            writer.beginArray();
            if (!isObject) {
                count++;
            }
            break;
        case END_ARRAY:
            reader.endArray();
            writer.endArray();
            if (!isObject) {
                count--;
            }
            break;
        case BEGIN_OBJECT:
            reader.beginObject();
            writer.beginObject();
            if (isObject) {
                count++;
            }
            break;
        case END_OBJECT:
            reader.endObject();
            writer.endObject();
            if (isObject) {
                count--;
            }
            break;
        case NAME:
            String name = reader.nextName();
            writer.name(name);
            break;
        case STRING:
            String stringValue = reader.nextString();
            writer.value(stringValue);
            break;
        case NUMBER:
            String numValue = reader.nextString();
            writer.value(new BigDecimal(numValue));
            break;
        case BOOLEAN:
            boolean boolValue = reader.nextBoolean();
            writer.value(boolValue);
            break;
        case NULL:
            reader.nextNull();
            writer.nullValue();
            break;
        case END_DOCUMENT:
            return;
        default:
            return;
        }
    } while (count != 0);
}

From source file:com.solidfire.jsvcgen.serialization.ApiServerExceptionTypeAdapter.java

License:Open Source License

/**
 * {@inheritDoc}//from ww  w .  j a  v a  2s  .  c  o  m
 */
@Override
public ApiServerException read(JsonReader in) throws IOException {

    String name = null;
    String code = null;
    String message = null;

    in.beginObject();
    while (in.hasNext()) {
        if (in.peek() != JsonToken.NAME) {
            in.skipValue();
            continue;
        }

        switch (in.nextName()) {
        case "name":
            name = in.nextString();
            break;
        case "code":
            code = in.nextString();
            break;
        case "message":
            message = in.nextString();
            break;
        }
    }
    in.endObject();

    return new ApiServerException(name, code, message);
}

From source file:com.squareup.wire.MessageTypeAdapter.java

License:Apache License

@SuppressWarnings("unchecked")
@Override//from w w w .  j  a  v a2 s  .  c o m
public M read(JsonReader in) throws IOException {
    if (in.peek() == JsonToken.NULL) {
        in.nextNull();
        return null;
    }

    MessageAdapter<M> messageAdapter = wire.messageAdapter(type);
    Message.Builder<M> builder = messageAdapter.newBuilder();
    in.beginObject();

    while (in.peek() == JsonToken.NAME) {
        String name = in.nextName();
        MessageAdapter.FieldInfo fieldInfo = messageAdapter.getField(name);
        if (fieldInfo == null) {
            Extension<?, ?> extension = messageAdapter.getExtension(name);
            if (extension == null) {
                parseUnknownField(in, builder, Integer.parseInt(name));
            } else {
                Type valueType = getType(extension);
                Object value = parseValue(extension.getLabel(), valueType, parse(in));
                ((ExtendableMessage.ExtendableBuilder) builder).setExtension(extension, value);
            }
        } else {
            Type valueType = getType(fieldInfo);
            Object value = parseValue(fieldInfo.label, valueType, parse(in));
            // Use the builder setter method to ensure proper 'oneof' behavior.
            messageAdapter.setBuilderMethod(builder, fieldInfo, value);
        }
    }

    in.endObject();
    return builder.build();
}

From source file:com.suny.whereami.service.google.Place.java

License:Open Source License

/**
 * Read fields from a result object./* w  ww .j a  v a 2  s .com*/
 * 
 * @param fields
 *            to read or 0 if all fields should be read
 * @param maxResults
 *            maximum number of reviews, events, and photos to return
 */
Place(JsonReader in, int fields, int maxResults) throws IOException {
    in.beginObject();
    while (in.hasNext()) {
        Key key = Key.get(in.nextName());
        if (key == UNKNOWN || fields != 0 && key.mField != null && !key.mField.in(fields)) {
            /* unknown field or caller doesn't want it */
            in.skipValue();
            continue;
        }

        switch (key) {
        case id:
            mId = in.nextString();
            break;
        case reference:
            mReference = in.nextString();
            break;
        case icon:
            mIcon = in.nextString();
            break;
        case url:
            mUrl = in.nextString();
            break;
        case geometry:
            in.beginObject();
            while (in.hasNext()) {
                if (in.nextName().equals("location")) {
                    in.beginObject();
                    while (in.hasNext()) {
                        switch (Key.get(in.nextName())) {
                        case lat:
                            mLat = in.nextDouble();
                            break;
                        case lng:
                            mLong = in.nextDouble();
                            break;
                        default:
                            in.skipValue();
                        }
                    }
                    in.endObject();
                } else {
                    in.skipValue(); // "viewport"
                }
            }
            in.endObject();
            break;
        case name:
            mName = in.nextString();
            break;
        case address_components:
            mAddress = new Address(in);
            break;
        case formatted_address:
            mFmtAddress = in.nextString();
            break;
        case vicinity:
            mVicinity = in.nextString();
            break;
        case international_phone_number:
            mIntlPhone = in.nextString();
            break;
        case formatted_phone_number:
            mFmtPhone = in.nextString();
            break;
        case website:
            mWebsite = in.nextString();
            break;
        case types:
            types(in);
            break;
        case price_level:
            mPrice = in.nextInt();
            break;
        case rating:
            mRating = (float) in.nextDouble();
            break;
        case reviews:
            in.beginArray();
            while (in.hasNext()) {
                if (mReviews == null) {
                    int cap = Math.min(Math.max(0, maxResults), MAX_REVIEWS);
                    mReviews = new ArrayList<Review>(cap > 0 ? cap : MAX_REVIEWS);
                }
                if (maxResults <= 0 || mReviews.size() < maxResults) {
                    mReviews.add(new Review(in));
                } else {
                    in.skipValue();
                }
            }
            in.endArray();
            break;
        case opening_hours:
            in.beginObject();
            while (in.hasNext()) {
                switch (Key.get(in.nextName())) {
                case open_now:
                    mOpen = in.nextBoolean();
                    break;
                case periods:
                    in.beginArray();
                    while (in.hasNext()) {
                        if (mOpenHours == null) {
                            mOpenHours = new ArrayList<OpeningHours>();
                        }
                        mOpenHours.add(new OpeningHours(in));
                    }
                    in.endArray();
                    break;
                default:
                    in.skipValue();
                }
            }
            in.endObject();
            break;
        case events:
            in.beginArray();
            while (in.hasNext()) {
                if (mEvents == null) {
                    int cap = Math.min(Math.max(0, maxResults), MAX_EVENTS);
                    mEvents = new ArrayList<Event>(cap > 0 ? cap : MAX_EVENTS);
                }
                if (maxResults <= 0 || mEvents.size() < maxResults) {
                    mEvents.add(new Event(in));
                } else {
                    in.skipValue();
                }
            }
            in.endArray();
            break;
        case utc_offset:
            mUtcOffset = in.nextInt();
            break;
        case photos:
            in.beginArray();
            while (in.hasNext()) {
                if (mPhotos == null) {
                    int cap = Math.min(Math.max(0, maxResults), MAX_PHOTOS);
                    mPhotos = new ArrayList<Photo>(cap > 0 ? cap : MAX_PHOTOS);
                }
                if (maxResults <= 0 || mPhotos.size() < maxResults) {
                    mPhotos.add(new Photo(in));
                } else {
                    in.skipValue();
                }
            }
            in.endArray();
            break;
        default:
            in.skipValue();
        }
    }
    in.endObject();
}

From source file:com.teotigraphix.caustk.tone.ToneUtils.java

License:Apache License

/**
 * Reads and returns the {@link ToneType} from the JSON data.
 * /*from w w  w.  j av a 2  s. c o m*/
 * @param data Valid serialized Tone data.
 * @throws IOException
 */
public static ToneType readToneType(String data) throws IOException {
    JsonReader reader = new JsonReader(new StringReader(data));
    String type = null;
    try {
        reader.beginObject();
        while (reader.hasNext()) {
            String name = reader.nextName();
            if (name.equals("toneType")) {
                type = reader.nextString();
            } else {
                reader.skipValue();
            }
        }
        reader.endObject();
    } finally {
        reader.close();
    }
    if (type != null)
        return ToneType.valueOf(type);

    return null;
}

From source file:com.triarc.sync.SyncAdapter.java

License:Apache License

@SuppressLint("NewApi")
private void readResponse(SyncTypeCollection typeCollection, InputStream inputStream, HttpResponse response)
        throws UnsupportedEncodingException, IOException, JSONException, Exception {
    long lastUpdate = 0;
    Header header = response.getFirstHeader("X-Application-Timestamp");
    if (header != null) {
        String value = header.getValue();
        lastUpdate = Long.parseLong(value);
    }//from  w  ww .  j av  a 2 s  . c  om

    // json is UTF-8 by default
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
    JsonStreamParser parser = new JsonStreamParser(reader);
    JsonReader jsonReader = new JsonReader(reader);
    jsonReader.beginObject();
    jsonReader.nextName();
    jsonReader.beginObject();
    while (jsonReader.hasNext()) {

        String syncName = jsonReader.nextName();
        SyncType syncType = this.GetSyncType(typeCollection, syncName);

        JsonElement fromJson = new Gson().fromJson(jsonReader, JsonElement.class);
        updateLocalTypeData(fromJson.getAsJsonObject(), syncType, typeCollection, syncResult);

        notificationQueue.add(new SyncNotificationMessage(syncType, fromJson.toString()));
        // String path = jsonReader.getPath();
        // String nextName = jsonReader.nextName();
        // jsonReader.endObject();
    }
    jsonReader.endObject();

    // String json = getStringForReader(reader);
    //
    //
    // JSONObject syncChangeSets = new JSONObject(json)
    // .getJSONObject("changeSetPerType");
    //
    // // first save all
    // for (SyncType syncType : typeCollection.getTypes()) {
    // syncResult.madeSomeProgress();
    // String name = syncType.getName();
    //
    // if (syncChangeSets.has(name)) {
    // JSONObject changeSetObject = syncChangeSets.getJSONObject(name);
    // updateLocalTypeData(changeSetObject, syncType, typeCollection,
    // syncResult);
    // notificationMap.put(syncType, changeSetObject);
    // } else {
    // Log.w(TAG, "Server does not support syncing of " + name);
    // sendLogs();
    // }
    // }

    // store collection update timestamp
    PreferenceManager.getDefaultSharedPreferences(this.getContext()).edit()
            .putLong(typeCollection.getName(), lastUpdate).commit();
    // then notify all
    notifyWebApp();

}

From source file:com.utad.flume.interceptor.InterceptorTwitter.java

License:Apache License

private byte[] readJsonStream(InputStream is) {
    byte[] body = null;
    try {/*from  w w w  .  java2s.c  om*/
        JsonReader reader = new JsonReader(new InputStreamReader(is, "UTF-8"));
        try {
            long id = 0L;
            String text = null;
            String userName = null;
            String userScreenName = null;
            reader.beginObject();
            while (reader.hasNext()) {
                String name = reader.nextName();
                if (name.equals("id")) {
                    id = reader.nextLong();
                } else if (name.equals("text")) {
                    text = reader.nextString();
                } else if (name.equals("user")) {
                    reader.beginObject();
                    while (reader.hasNext()) {
                        name = reader.nextName();
                        if (name.equals("name")) {
                            userName = reader.nextString();
                        } else if (name.equals("screen_name")) {
                            userScreenName = reader.nextString();
                        } else {
                            reader.skipValue();
                        }
                    }
                    reader.endObject();
                } else {
                    reader.skipValue();
                }
            }
            reader.endObject();

            StringBuilder builder = new StringBuilder("ID:");
            builder.append(id);
            builder.append("||");
            if (outputText) {
                builder.append("TEXT:").append(text).append("||");
            }
            if (outputUserName) {
                builder.append("USER:").append(userName).append("||");
            }
            if (outputUserScreenName) {
                builder.append("SCREEN:").append(userScreenName).append("||");
            }

            logger.debug("id: {}", id);
            logger.debug("text: {}", text);
            logger.debug("username: {}", userName);
            logger.debug("screenName: {}", userScreenName);

            body = builder.toString().getBytes("UTF-8");
        } finally {
            reader.close();
        }
    } catch (UnsupportedEncodingException e) {
        logger.error("UTF-8 is not supported on this runtime", e);
    } catch (IOException e) {
        logger.error("Caught an IOException", e);
    }
    return body;
}