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:TestGenerator.ArgumentCache.UniversalArrayTypeAdapter.java

License:Apache License

@Override
public Object read(JsonReader in) throws IOException {
    if (in.peek() == JsonToken.NULL) {
        in.nextNull();/*from w ww.j a  va2s . co m*/
        return null;
    }

    List<E> list = new ArrayList<E>();
    in.beginArray();
    while (in.hasNext()) {
        //            E instance = componentTypeAdapter.read(in); // old code replacing below block
        E instance = null;
        JsonElement je = this.jsonElementAdapter.read(in);
        if (je.isJsonObject() && je.getAsJsonObject().has(UniversalTypeAdapterFactory.class_token)) {
            try {
                Class clazz = Class.forName(
                        je.getAsJsonObject().get(UniversalTypeAdapterFactory.class_token).getAsString());
                TypeAdapter newAdapter = context.getAdapter(clazz);
                instance = (E) newAdapter.fromJsonTree(je);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        } else {
            instance = componentTypeAdapter.fromJsonTree(je);
        }
        list.add(instance);
    }
    in.endArray();
    Object array = Array.newInstance(componentType, list.size());
    for (int i = 0; i < list.size(); i++) {
        Array.set(array, i, list.get(i));
    }

    return array;
}

From source file:tools.DrawStatisticsForPubMedData.java

License:Apache License

public void parseStream(String jsonFile, String listOfJournals) throws IOException {

    String journalName;/*from   w w  w  .j  av  a 2 s.  co  m*/
    int count = 0;
    int abstract_count = 0;
    int duplicates = 0;

    try {
        JsonReader reader = new JsonReader(new InputStreamReader(new FileInputStream(jsonFile)));
        reader.setLenient(true);

        reader.beginObject();
        reader.skipValue();

        //System.out.println(nam);
        reader.beginArray();
        while (reader.hasNext()) {

            reader.beginObject();
            this.numeOfArticles++;
            while (reader.hasNext()) {
                String name = reader.nextName();

                if (name.equals("abstractText")) {
                    abstract_count++;
                    reader.skipValue();

                } else if (name.equals("journal")) {
                    journalName = reader.nextString();
                    journalList.add(journalName);
                } else if (name.equals("meshMajor")) {
                    int num_labels = readLabelsArray(reader);
                    count += num_labels;
                    labelDensity += (double) num_labels / 26563.0;
                } else if (name.equals("pmid")) {
                    int pmid = reader.nextInt();
                    if (!pmids.contains(pmid))
                        pmids.add(pmid);
                    else
                        duplicates++;
                } else if (name.equals("title")) {
                    reader.skipValue();
                } else if (name.equals("year")) {
                    reader.skipValue();
                } else {
                    System.out.println(name);
                    reader.skipValue();
                }
            }
            reader.endObject();
        }
        reader.endArray();

        System.out.println("Abstracts: " + abstract_count);
        System.out.println("Duplicates: " + duplicates);

        labelsPerArticle = (double) count / (double) numeOfArticles;
        labelDensity = labelDensity / (double) numeOfArticles;
        exportListOfJournals(listOfJournals);
        printStatistics();

    } catch (Exception ex) {
        System.out.println("Abstracts: " + abstract_count);
        System.out.println("Duplicates: " + duplicates);

        labelsPerArticle = (double) count / (double) numeOfArticles;
        labelDensity = labelDensity / (double) numeOfArticles;
        exportListOfJournals(listOfJournals);
        printStatistics();
        Logger.getLogger(DrawStatisticsForPubMedData.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:tools.DrawStatisticsForPubMedData.java

License:Apache License

public int readLabelsArray(JsonReader reader) {

    int count = 0;
    try {/*  w  w w . j  a va  2  s  .co  m*/
        reader.beginArray();
        while (reader.hasNext()) {
            String nextString = reader.nextString();
            labelsList.add(nextString);
            count++;
        }
        reader.endArray();
    } catch (IOException ex) {
    }

    return count;
}

From source file:uk.ac.susx.tag.classificationframework.classifiers.NaiveBayesClassifier.java

License:Apache License

protected static IntSet readJsonIntSet(JsonReader reader, FeatureExtractionPipeline pipeline,
        boolean areFeatures) throws IOException {
    IntSet set = new IntOpenHashSet();
    reader.beginArray();
    while (reader.hasNext()) {
        set.add(areFeatures ? pipeline.featureIndex(reader.nextString())
                : pipeline.labelIndex(reader.nextString()));
    }//from w w  w .ja v  a2 s .  c  om
    reader.endArray();
    return set;
}

From source file:uk.ac.susx.tag.classificationframework.jsonhandling.JsonIterator.java

License:Apache License

public JsonIterator(JsonReader jsonReader, Gson gson) throws IOException {
    this.gson = gson;
    this.jsonReader = jsonReader;
    jsonReader.beginArray();
}

From source file:uk.ac.susx.tag.dependencyparser.datastructures.StringIndexer.java

License:Apache License

public static StringIndexer readJson(JsonReader reader) throws IOException {
    int idStart = 1;
    List<String> strings = new ArrayList<>();
    reader.beginObject();/* ww w. j av  a  2s .  co m*/
    while (reader.hasNext()) {
        String name = reader.nextName();
        switch (name) {
        case "idStart":
            idStart = reader.nextInt();
            break;
        case "strings":
            reader.beginArray();
            while (reader.hasNext()) {
                strings.add(reader.nextString());
            }
            reader.endArray();
        }
    }
    reader.endObject();
    return new StringIndexer(idStart, strings);
}

From source file:us.blanshard.sudoku.game.GameJson.java

License:Apache License

/**
 * Registers type adapters in the given builder so that history lists and undo
 * stacks can be serialized and deserialized.  Note that undo stacks require a
 * CommandFactory be established before deserialization; see {@link #setFactory}.
 *//*from   w  w  w  .  j a  va2s  .  c o m*/
public static GsonBuilder register(GsonBuilder builder) {

    builder.registerTypeHierarchyAdapter(Move.class, new TypeAdapter<Move>() {
        @Override
        public void write(JsonWriter out, Move value) throws IOException {
            out.value(value.toJsonValue());
        }

        @Override
        public Move read(JsonReader in) throws IOException {
            return Move.fromJsonValue(in.nextString());
        }
    });

    final TypeAdapter<Command> commandAdapter = new TypeAdapter<Command>() {
        @Override
        public void write(JsonWriter out, Command value) throws IOException {
            out.value(value.toJsonValue());
        }

        @Override
        public Command read(JsonReader in) throws IOException {
            Iterator<String> values = SPLITTER.split(in.nextString()).iterator();
            String type = values.next();
            return factorySlot.get().toCommand(type, values);
        }
    };
    builder.registerTypeHierarchyAdapter(Command.class, commandAdapter);

    builder.registerTypeAdapter(UndoStack.class, new TypeAdapter<UndoStack>() {
        @Override
        public void write(JsonWriter out, UndoStack value) throws IOException {
            out.beginObject();
            out.name("position").value(value.getPosition());
            out.name("commands").beginArray();
            for (Command c : value.commands)
                commandAdapter.write(out, c);
            out.endArray();
            out.endObject();
        }

        @Override
        public UndoStack read(JsonReader in) throws IOException {
            int position = -1;
            List<Command> commands = null;
            in.beginObject();
            while (in.hasNext()) {
                String name = in.nextName();
                if (name.equals("position")) {
                    position = in.nextInt();
                } else if (name.equals("commands")) {
                    commands = Lists.newArrayList();
                    in.beginArray();
                    while (in.hasNext())
                        commands.add(commandAdapter.read(in));
                    in.endArray();
                } else {
                    in.skipValue();
                }
            }
            in.endObject();
            return new UndoStack(commands, position);
        }
    });

    return builder;
}

From source file:util.android.gson.ArrayAdapter.java

License:Apache License

@Override
public List<T> read(JsonReader reader) throws IOException {

    List<T> list = new ArrayList<T>();

    Gson gson = new GsonBuilder().registerTypeAdapterFactory(new ArrayAdapterFactory()).create();

    if (reader.peek() == JsonToken.BEGIN_OBJECT) {
        T inning = gson.fromJson(reader, adapterclass);
        list.add(inning);/*from ww  w .  ja v  a 2 s  . c om*/

    } else if (reader.peek() == JsonToken.BEGIN_ARRAY) {

        reader.beginArray();
        while (reader.hasNext()) {
            T inning = gson.fromJson(reader, adapterclass);
            list.add(inning);
        }
        reader.endArray();

    }

    return list;
}

From source file:vaeke.restcountries.v0.rest.CountryService.java

License:Mozilla Public License

private void initialize() throws IOException {
    LOG.debug("Loading JSON Database v0");
    InputStream is = this.getClass().getClassLoader().getResourceAsStream("countries.json");
    Gson gson = new Gson();
    JsonReader reader = new JsonReader(new InputStreamReader(is, "UTF-8"));
    countries = new ArrayList<Country>();
    reader.beginArray();
    while (reader.hasNext()) {
        Country country = gson.fromJson(reader, Country.class);
        countries.add(country);/*from w  ww . j  a  v  a2s.c o  m*/
    }
    reader.endArray();
    reader.close();

}

From source file:vaeke.restcountries.v1.rest.CountryService.java

License:Mozilla Public License

private void initialize() {
    LOG.debug("Loading JSON Database v1");
    InputStream is = this.getClass().getClassLoader().getResourceAsStream("countriesV1.json");
    Gson gson = new Gson();
    JsonReader reader;
    try {//from  ww  w.ja  va  2  s . c o m
        reader = new JsonReader(new InputStreamReader(is, "UTF-8"));
        countries = new ArrayList<Country>();
        reader.beginArray();
        while (reader.hasNext()) {
            Country country = gson.fromJson(reader, Country.class);
            countries.add(country);
        }
        reader.endArray();
        reader.close();
    } catch (Exception e) {
        LOG.error("Could not load JSON Database v1 ");
    }

}