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

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this JSON reader and the underlying java.io.Reader .

Usage

From source file:co.cask.cdap.format.StructuredRecordStringConverter.java

License:Apache License

/**
 * Converts a json string to a {@link StructuredRecord} based on the schema.
 *///  ww w .j  a va 2 s.  c  om
public static StructuredRecord fromJsonString(String json, Schema schema) throws IOException {
    JsonReader reader = new JsonReader(new StringReader(json));
    try {
        return (StructuredRecord) readJson(reader, schema);
    } finally {
        reader.close();
    }
}

From source file:co.moonmonkeylabs.flowmortarexampleapp.common.flow.GsonParceler.java

License:Apache License

private Object decode(String json) throws IOException {
    JsonReader reader = new JsonReader(new StringReader(json));

    try {/*from  w  w  w .j a  v a 2s.c o m*/
        reader.beginObject();

        Class<?> type = Class.forName(reader.nextName());
        return gson.fromJson(reader, type);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    } finally {
        reader.close();
    }
}

From source file:com.aliakseipilko.flightdutytracker.utils.AirportCodeConverter.java

License:Open Source License

private void generateAirports() {
    JsonReader jsonReader = new JsonReader(
            new InputStreamReader(ctx.getResources().openRawResource(R.raw.airports)));
    try {//from ww w. ja v  a2 s  .com
        jsonReader.beginArray();
        while (jsonReader.hasNext()) {
            Airport airport = gson.fromJson(jsonReader, Airport.class);
            if (airport.getIATA() == null) {
                airport.setIATA("");
            }
            if (airport.getICAO() == null) {
                airport.setICAO("");
            }
            airports.add(airport);
        }
        jsonReader.endArray();
        jsonReader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.andgate.ikou.io.LevelService.java

License:Open Source License

public static Level read(final FileHandle levelFile) throws IOException {
    Level level = null;//w  w  w.j  ava  2 s  .c om

    if (levelFile.exists() && levelFile.extension().equals(Constants.LEVEL_EXTENSION_NO_DOT)) {
        InputStream levelIn = new GZIPInputStream(levelFile.read());
        Reader reader = new BufferedReader(new InputStreamReader(levelIn));
        JsonReader jsonReader = new JsonReader(reader);

        try {
            // Skip the first int, it's just the floor numbers.
            levelIn.read();
            Gson gson = new Gson();
            level = gson.fromJson(jsonReader, Level.class);
        } finally {
            jsonReader.close();
        }
    }

    if (level == null) {
        final String errorMessage = "Failed to load level \"" + levelFile.path() + levelFile.name() + "\"";
        throw new IOException(errorMessage);
    }

    return level;
}

From source file:com.andrewreitz.onthisday.ui.flow.GsonParcer.java

License:Apache License

private T decode(String json) throws IOException {
    JsonReader reader = new JsonReader(new StringReader(json));

    try {//from   ww w  .  java 2  s .c o  m
        reader.beginObject();

        Class<?> type = Class.forName(reader.nextName());
        return gson.fromJson(reader, type);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    } finally {
        reader.close();
    }
}

From source file:com.android.ide.common.blame.MergingLogPersistUtil.java

License:Apache License

@NonNull
static Map<SourceFile, Map<SourcePosition, SourceFilePosition>> loadFromMultiFile(@NonNull File folder,
        @NonNull String shard) {//from ww w . j av a  2 s  . com
    Map<SourceFile, Map<SourcePosition, SourceFilePosition>> map = Maps.newConcurrentMap();
    JsonReader reader;
    File file = getMultiFile(folder, shard);
    if (!file.exists()) {
        return map;
    }
    try {
        reader = new JsonReader(Files.newReader(file, Charsets.UTF_8));
    } catch (FileNotFoundException e) {
        // Shouldn't happen unless it disappears under us.
        return map;
    }
    try {
        reader.beginArray();
        while (reader.peek() != JsonToken.END_ARRAY) {
            reader.beginObject();
            SourceFile toFile = SourceFile.UNKNOWN;
            Map<SourcePosition, SourceFilePosition> innerMap = Maps.newLinkedHashMap();
            while (reader.peek() != JsonToken.END_OBJECT) {
                final String name = reader.nextName();
                if (name.equals(KEY_OUTPUT_FILE)) {
                    toFile = mSourceFileJsonTypeAdapter.read(reader);
                } else if (name.equals(KEY_MAP)) {
                    reader.beginArray();
                    while (reader.peek() != JsonToken.END_ARRAY) {
                        reader.beginObject();
                        SourceFilePosition from = null;
                        SourcePosition to = null;
                        while (reader.peek() != JsonToken.END_OBJECT) {
                            final String innerName = reader.nextName();
                            if (innerName.equals(KEY_FROM)) {
                                from = mSourceFilePositionJsonTypeAdapter.read(reader);
                            } else if (innerName.equals(KEY_TO)) {
                                to = mSourcePositionJsonTypeAdapter.read(reader);
                            } else {
                                throw new IOException(String.format("Unexpected property: %s", innerName));
                            }
                        }
                        if (from == null || to == null) {
                            throw new IOException("Each record must contain both from and to.");
                        }
                        innerMap.put(to, from);
                        reader.endObject();
                    }
                    reader.endArray();
                } else {
                    throw new IOException(String.format("Unexpected property: %s", name));
                }
            }
            map.put(toFile, innerMap);
            reader.endObject();
        }
        reader.endArray();
        return map;
    } catch (IOException e) {
        // TODO: trigger a non-incremental merge if this happens.
        throw new RuntimeException(e);
    } finally {
        try {
            reader.close();
        } catch (Throwable e2) {
            // well, we tried.
        }
    }
}

From source file:com.android.ide.common.blame.MergingLogPersistUtil.java

License:Apache License

@NonNull
static Map<SourceFile, SourceFile> loadFromSingleFile(@NonNull File folder, @NonNull String shard) {
    Map<SourceFile, SourceFile> fileMap = Maps.newConcurrentMap();
    JsonReader reader;
    File file = getSingleFile(folder, shard);
    if (!file.exists()) {
        return fileMap;
    }/*from  w  w  w  . j  av a 2s. co m*/
    try {
        reader = new JsonReader(Files.newReader(file, Charsets.UTF_8));
    } catch (FileNotFoundException e) {
        // Shouldn't happen unless it disappears under us.
        return fileMap;
    }
    try {
        reader.beginArray();
        while (reader.peek() != JsonToken.END_ARRAY) {
            reader.beginObject();
            SourceFile merged = SourceFile.UNKNOWN;
            SourceFile source = SourceFile.UNKNOWN;
            while (reader.peek() != JsonToken.END_OBJECT) {
                String name = reader.nextName();
                if (name.equals(KEY_MERGED)) {
                    merged = mSourceFileJsonTypeAdapter.read(reader);
                } else if (name.equals(KEY_SOURCE)) {
                    source = mSourceFileJsonTypeAdapter.read(reader);
                } else {
                    throw new IOException(String.format("Unexpected property: %s", name));
                }
            }
            reader.endObject();
            fileMap.put(merged, source);
        }
        reader.endArray();
        return fileMap;
    } catch (IOException e) {
        // TODO: trigger a non-incremental merge if this happens.
        throw new RuntimeException(e);
    } finally {
        try {
            reader.close();
        } catch (Throwable e) {
            // well, we tried.
        }
    }
}

From source file:com.avatarproject.core.storage.Serializer.java

License:Open Source License

/**
 * Gets the object from file/*from  ww w .j a  va 2 s  .  c  o  m*/
 * @param caller Class<?> of the object being deserialized
 * @param file File containing the object
 * @return Deserialized Object
 */
public static Object get(Class<?> caller, File file) {
    try {
        if (!file.exists()) {
            return null;
        }
        if (file.length() == 0) {
            return null;
        }
        JsonReader reader = new JsonReader(
                new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")));
        Gson gson = new Gson();
        reader.setLenient(true);
        Object object = gson.fromJson(reader, caller);
        reader.close();
        if (object != null && object instanceof Serializer) {
            ((Serializer) object).setFile(file);
        }
        return object;
    } catch (Exception e) {
        log.warning("Error loading GSON Object '" + caller.getSimpleName() + "' for '" + file.toString() + "'");
        e.printStackTrace();
        return null;
    }
}

From source file:com.battlelancer.seriesguide.dataliberation.JsonImportTask.java

License:Apache License

private void importFromJson(@JsonExportTask.BackupType int type, FileInputStream in)
        throws JsonParseException, IOException, IllegalArgumentException {
    Gson gson = new Gson();
    JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
    reader.beginArray();//  w ww.j a v  a  2 s  .  c om

    if (type == JsonExportTask.BACKUP_SHOWS) {
        while (reader.hasNext()) {
            Show show = gson.fromJson(reader, Show.class);
            addShowToDatabase(show);
        }
    } else if (type == JsonExportTask.BACKUP_LISTS) {
        while (reader.hasNext()) {
            List list = gson.fromJson(reader, List.class);
            addListToDatabase(list);
        }
    } else if (type == JsonExportTask.BACKUP_MOVIES) {
        while (reader.hasNext()) {
            Movie movie = gson.fromJson(reader, Movie.class);
            addMovieToDatabase(movie);
        }
    }

    reader.endArray();
    reader.close();
}

From source file:com.battlelancer.seriesguide.dataliberation.JsonImportTask.java

License:Apache License

private int importLists(File importPath) {
    File backupLists = new File(importPath, JsonExportTask.EXPORT_JSON_FILE_LISTS);
    if (!backupLists.exists() || !backupLists.canRead()) {
        // Skip lists if the file is not accessible
        return SUCCESS;
    }/* www . j  a v a  2  s. co m*/

    // Access JSON from backup folder to create new database
    try {
        InputStream in = new FileInputStream(backupLists);

        Gson gson = new Gson();

        JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
        reader.beginArray();

        while (reader.hasNext()) {
            List list = gson.fromJson(reader, List.class);
            addListToDatabase(list);
        }

        reader.endArray();
        reader.close();
    } catch (JsonParseException | IOException | IllegalStateException e) {
        // the given Json might not be valid or unreadable
        Timber.e(e, "JSON lists import failed");
        return ERROR;
    }

    return SUCCESS;
}