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

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

Introduction

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

Prototype

public void beginArray() throws IOException 

Source Link

Document

Consumes the next token from the JSON stream and asserts that it is the beginning of a new array.

Usage

From source file:edu.rpi.shuttles.data.RPIShuttleDataProvider.java

License:Apache License

public SparseArray<Vehicle> updateVehicleLocations() throws IOException {
    // Download vehicle location data.
    URL vehicleLocationURL = new URL(mVehicleLocationsUrl);
    URLConnection vehicleLocationConnection = vehicleLocationURL.openConnection();
    vehicleLocationConnection.setRequestProperty("User-Agent", mUserAgent);
    InputStream in = new BufferedInputStream(vehicleLocationConnection.getInputStream());
    JsonReader reader = new JsonReader(new InputStreamReader(in));
    SparseArray<Vehicle> updated_vehicles = new SparseArray<Vehicle>();

    reader.beginArray();
    while (reader.hasNext()) {
        Vehicle shuttle = readVehicleLocation(reader);
        updated_vehicles.put(shuttle.id, shuttle);
        mVehicles.put(shuttle.id, shuttle);
    }//  w w w.  jav a  2 s. c  om
    reader.endArray();

    reader.close();
    return updated_vehicles;
}

From source file:es.chatclient.server.messages.adapters.ConversDataMessageTypeAdapter.java

@Override
public ConversDataMessage read(JsonReader in) throws IOException {

    final ConversDataMessage conversDate = new ConversDataMessage();
    final List<ConverData> converDataList = new ArrayList();

    in.beginObject();//from   w w w. ja va 2  s  .  c  o m

    in.nextName();

    in.beginArray();

    while (in.hasNext()) {
        in.beginObject();
        final ConverData converData = new ConverData();

        while (in.hasNext()) {
            switch (in.nextName()) {

            case "converID":
                converData.setConverID(in.nextString());

                break;

            case "converName":
                converData.setConverName(in.nextString());
                break;

            case "arrayMessages":

                final List<Message> msgList = new ArrayList();

                in.beginArray();
                while (in.hasNext()) {
                    in.beginObject();
                    final Message msg = new Message();

                    while (in.hasNext()) {
                        switch (in.nextName()) {
                        case "msgID":
                            msg.setMsgID(in.nextString());
                            break;

                        case "msgType":
                            msg.setMsgType(in.nextString());
                            break;

                        case "msgText":
                            msg.setMsgText(in.nextString());
                            break;

                        case "msgDate":
                            msg.setMsgDate(in.nextString());
                            break;

                        case "clientId":
                            msg.setClientId(in.nextString());
                            break;

                        case "converId":
                            msg.setConverId(in.nextString());
                            break;

                        case "userNick":
                            msg.setUserNick(in.nextString());
                            break;

                        } //fin switch

                    }

                    msgList.add(msg);
                    in.endObject();

                }

                in.endArray();

                converData.setConverMessages(msgList);

                break;

            default:

                break;

            }

        }

        converDataList.add(converData);
        in.endObject();

    }

    in.endArray();
    conversDate.setConverDataArray(converDataList);

    in.endObject();

    return conversDate;

}

From source file:eu.fayder.restcountries.rest.CountryServiceBase.java

License:Mozilla Public License

protected List<? extends BaseCountry> loadJson(String filename, Class<? extends BaseCountry> clazz) {
    LOG.debug("Loading JSON " + filename);
    List<BaseCountry> countries = new ArrayList<>();
    InputStream is = CountryServiceBase.class.getClassLoader().getResourceAsStream(filename);
    Gson gson = new Gson();
    JsonReader reader;
    try {//from  w  ww  .j  a  v a 2s.  co  m
        reader = new JsonReader(new InputStreamReader(is, "UTF-8"));
        reader.beginArray();
        while (reader.hasNext()) {
            BaseCountry country = gson.fromJson(reader, clazz);
            countries.add(country);
        }
    } catch (Exception e) {
        LOG.error("Could not load JSON " + filename);
    }
    return countries;
}

From source file:fayder.restcountries.rest.CountryServiceHelper.java

License:Mozilla Public License

public static List<? extends BaseCountry> loadJson(String filename, Class<? extends BaseCountry> clazz) {
    LOG.debug("Loading JSON " + filename);
    List<BaseCountry> countries = new ArrayList<>();
    InputStream is = CountryServiceHelper.class.getClassLoader().getResourceAsStream(filename);
    Gson gson = new Gson();
    JsonReader reader;
    try {/*from ww w. j a  v a  2s.  c o  m*/
        reader = new JsonReader(new InputStreamReader(is, "UTF-8"));
        reader.beginArray();
        while (reader.hasNext()) {
            BaseCountry country = gson.fromJson(reader, clazz);
            countries.add(country);
        }
    } catch (Exception e) {
        LOG.error("Could not load JSON " + filename);
    }
    return countries;
}

From source file:guru.qas.martini.report.DefaultTraceabilityMatrix.java

License:Apache License

@Override
public void createReport(JsonReader reader, OutputStream outputStream) throws IOException {
    checkNotNull(reader, "null JsonReader");
    checkNotNull(outputStream, "null OutputStream");

    Workbook workbook = new XSSFWorkbook();
    Sheet sheet = workbook.createSheet("Results");
    addHeader(sheet);//from   w  w  w . j a va  2s .com

    State state = new DefaultState();
    while (reader.hasNext()) {
        JsonToken peek = reader.peek();

        JsonObject object;
        switch (peek) {
        case BEGIN_ARRAY:
            reader.beginArray();
            continue;
        case BEGIN_OBJECT:
            object = gson.fromJson(reader, JsonObject.class);
            break;
        case END_ARRAY:
            reader.endArray();
            continue;
        case END_DOCUMENT:
            reader.skipValue();
            continue;
        default:
            JsonElement element = gson.fromJson(reader, JsonElement.class);
            LOGGER.warn("skipping unhandled element {}", element);
            continue;
        }

        switch (JsonObjectType.evaluate(object)) {
        case SUITE:
            JsonObject suite = SUITE.get(object);
            state.addSuite(suite);
            break;
        case FEATURE:
            JsonObject feature = FEATURE.get(object);
            state.addFeature(feature);
            break;
        case RESULT:
            JsonObject result = RESULT.get(object);
            addResult(state, sheet, result);
            break;
        default:
            LOGGER.warn("skipping unrecognized JsonObject: {}", object);
        }
    }

    state.updateResults();
    resizeColumns(sheet);

    Sheet suiteSheet = workbook.createSheet("Suites");
    state.updateSuites(suiteSheet);

    workbook.write(outputStream);
    outputStream.flush();
}

From source file:io.github.rcarlosdasilva.weixin.core.json.adapter.OpenPlatformAuthGetLicenseInformationResponseTypeAdapter.java

private void readLicensedAccessToken(JsonReader in, OpenPlatformAuthGetLicenseInformationResponse model)
        throws IOException {
    LicensingInformation licensingInformation = new LicensingInformation();
    in.beginObject();/* w  ww.ja  v a2s .co m*/

    while (in.hasNext()) {
        String key = in.nextName();
        switch (key) {
        case Convention.OPEN_PLATFORM_AUTH_LICENSED_APPID_ALIAS_KEY:
        case Convention.OPEN_PLATFORM_AUTH_LICENSED_APPID_KEY:
            licensingInformation.setAppId(in.nextString());
            break;
        case Convention.OPEN_PLATFORM_AUTH_LICENSED_ACCESS_TOKEN_KEY:
            model.getLicensedAccessToken().setAccessToken(in.nextString());
            break;
        case Convention.OPEN_PLATFORM_AUTH_LICENSED_ACCESS_TOKEN_EXPIRES_IN_KEY:
            model.getLicensedAccessToken().setExpiresIn(in.nextInt());
            break;
        case Convention.OPEN_PLATFORM_AUTH_LICENSED_REFRESH_TOKEN_KEY:
            model.getLicensedAccessToken().setRefreshToken(in.nextString());
            break;
        case Convention.OPEN_PLATFORM_AUTH_LICENSED_FUNCTIONS_INFO_KEY: {
            in.beginArray();

            while (in.hasNext()) {
                in.beginObject();
                in.nextName();
                in.beginObject();
                in.nextName();
                licensingInformation.addLicencedFunction(in.nextInt());
                in.endObject();
                in.endObject();
            }

            in.endArray();
            break;
        }
        default:
            if (in.hasNext()) {
                String value = in.nextString();
                logger.warn(LOG_UNKNOWN_JSON_KEY, key, value);
            }
        }
    }

    in.endObject();
    model.setLicensingInformation(licensingInformation);
}

From source file:io.grpc.internal.JsonParser.java

License:Apache License

private static List<?> parseJsonArray(JsonReader jr) throws IOException {
    jr.beginArray();
    List<Object> array = new ArrayList<>();
    while (jr.hasNext()) {
        Object value = parseRecursive(jr);
        array.add(value);/*from   w w w  .  j a va2s  .  c  o m*/
    }
    checkState(jr.peek() == JsonToken.END_ARRAY, "Bad token: " + jr.getPath());
    jr.endArray();
    return Collections.unmodifiableList(array);
}

From source file:it.bradipao.berengar.DbTool.java

License:Apache License

public static int gson2db(SQLiteDatabase mDB, File jsonFile) {

    // vars/* w w  w  .  j a v  a 2  s . c o  m*/
    int iTableNum = 0;
    FileReader fr = null;
    BufferedReader br = null;
    JsonReader jr = null;
    String name = null;
    String val = null;

    String mTable = null;
    String mTableSql = null;
    ArrayList<String> aFields = null;
    ArrayList<String> aValues = null;
    ContentValues cv = null;

    // file readers
    try {
        fr = new FileReader(jsonFile);
        br = new BufferedReader(fr);
        jr = new JsonReader(br);
    } catch (FileNotFoundException e) {
        Log.e(LOGTAG, "error in gson2db file readers", e);
    }

    // parsing
    try {
        // start database transaction
        mDB.beginTransaction();
        // open root {
        jr.beginObject();
        // iterate through root objects
        while (jr.hasNext()) {
            name = jr.nextName();
            if (jr.peek() == JsonToken.NULL)
                jr.skipValue();
            // number of tables
            else if (name.equals("tables_num")) {
                val = jr.nextString();
                iTableNum = Integer.parseInt(val);
                if (GOLOG)
                    Log.d(LOGTAG, "TABLE NUM : " + iTableNum);
            }
            // iterate through tables array
            else if (name.equals("tables")) {
                jr.beginArray();
                while (jr.hasNext()) {
                    // start table
                    mTable = null;
                    aFields = null;
                    jr.beginObject();
                    while (jr.hasNext()) {
                        name = jr.nextName();
                        if (jr.peek() == JsonToken.NULL)
                            jr.skipValue();
                        // table name
                        else if (name.equals("table_name")) {
                            mTable = jr.nextString();
                        }
                        // table sql
                        else if (name.equals("table_sql")) {
                            mTableSql = jr.nextString();
                            if ((mTable != null) && (mTableSql != null)) {
                                mDB.execSQL("DROP TABLE IF EXISTS " + mTable);
                                mDB.execSQL(mTableSql);
                                if (GOLOG)
                                    Log.d(LOGTAG, "DROPPED AND CREATED TABLE : " + mTable);
                            }
                        }
                        // iterate through columns name
                        else if (name.equals("cols_name")) {
                            jr.beginArray();
                            while (jr.hasNext()) {
                                val = jr.nextString();
                                if (aFields == null)
                                    aFields = new ArrayList<String>();
                                aFields.add(val);
                            }
                            jr.endArray();
                            if (GOLOG)
                                Log.d(LOGTAG, "COLUMN NAME : " + aFields.toString());
                        }
                        // iterate through rows
                        else if (name.equals("rows")) {
                            jr.beginArray();
                            while (jr.hasNext()) {
                                jr.beginArray();
                                // iterate through values in row
                                aValues = null;
                                cv = null;
                                while (jr.hasNext()) {
                                    val = jr.nextString();
                                    if (aValues == null)
                                        aValues = new ArrayList<String>();
                                    aValues.add(val);
                                }
                                jr.endArray();
                                // add to database
                                cv = new ContentValues();
                                for (int j = 0; j < aFields.size(); j++)
                                    cv.put(aFields.get(j), aValues.get(j));
                                mDB.insert(mTable, null, cv);
                                if (GOLOG)
                                    Log.d(LOGTAG, "INSERT IN " + mTable + " : " + aValues.toString());
                            }
                            jr.endArray();
                        } else
                            jr.skipValue();
                    }
                    // end table
                    jr.endObject();
                }
                jr.endArray();
            } else
                jr.skipValue();
        }
        // close root }
        jr.endObject();
        jr.close();
        // successfull transaction
        mDB.setTransactionSuccessful();
    } catch (IOException e) {
        Log.e(LOGTAG, "error in gson2db gson parsing", e);
    } finally {
        mDB.endTransaction();
    }

    return iTableNum;
}

From source file:json_export_import.GSON_Observer.java

public void read() {
    try {//  www  .ja  va  2  s. c om
        JsonReader reader = new JsonReader(new FileReader("/home/rgreim/Output.json"));
        reader.beginArray();
        while (reader.hasNext()) {
            String sequence = reader.nextString();
            System.out.println("Sequenz: " + sequence);
        }
        reader.endArray();
        reader.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(GSON_Observer.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(GSON_Observer.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:junk.StreamingSample.java

License:Apache License

/**
 * Run the bigquery ClI.//from  w ww.j a  v a2 s . co  m
 *
 * @param projectId Project id
 * @param datasetId datasetid
 * @param tableId   tableid
 * @param rows      The source of the JSON rows we are streaming in.
 * @return Returns Iterates through the stream responses
 * @throws IOException          Thrown if there is an error connecting to Bigquery.
 * @throws InterruptedException Should never be thrown
 */
// [START run]
public static Iterator<TableDataInsertAllResponse> run(final String projectId, final String datasetId,
        final String tableId, final JsonReader rows) throws IOException {

    final Bigquery bigquery = BigqueryServiceFactory.getService();
    final Gson gson = new Gson();
    rows.beginArray();

    return new Iterator<TableDataInsertAllResponse>() {

        /**
         * Check whether there is another row to stream.
         *
         * @return True if there is another row in the stream
         */
        public boolean hasNext() {
            try {
                return rows.hasNext();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return false;
        }

        /**
         * Insert the next row, and return the response.
         *
         * @return Next page of data
         */
        public TableDataInsertAllResponse next() {
            try {
                Map<String, Object> rowData = gson.<Map<String, Object>>fromJson(rows,
                        (new HashMap<String, Object>()).getClass());

                return streamRow(bigquery, projectId, datasetId, tableId,
                        new TableDataInsertAllRequest.Rows().setJson(rowData));
            } catch (JsonSyntaxException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        public void remove() {
            this.next();
        }

    };

}