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

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

Introduction

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

Prototype

public JsonReader(Reader in) 

Source Link

Document

Creates a new instance that reads a JSON-encoded stream from in .

Usage

From source file:data.GoogleActDataGetter.java

public double readActualData(String tickerSymbol) throws IOException, NumberFormatException {
    StringBuilder urlBuilder = new StringBuilder();

    urlBuilder.append("http://finance.google.com/finance/info?client=ig&q=");

    urlBuilder.append(tickerSymbol);/*from ww  w  .  j  av a2  s.c o m*/

    URL urlGoogle = new URL(urlBuilder.toString());
    BufferedReader in = new BufferedReader(new InputStreamReader(urlGoogle.openStream()));

    in.skip(3);

    Gson gson = new GsonBuilder().create();
    JsonReader reader = new JsonReader(in);
    reader.setLenient(true);
    DataGSON[] p = gson.fromJson(reader, DataGSON[].class);

    in.close();

    return Double.parseDouble(p[0].l.replaceAll(",", ""));
}

From source file:data.GoogleActDataGetter.java

public Map<String, Double> readActualData(String[] tickerSymbols) throws IOException, NumberFormatException {
    StringBuilder urlBuilder = new StringBuilder();

    urlBuilder.append("http://finance.google.com/finance/info?client=ig&q=");

    for (String tickerSymbol : tickerSymbols) {
        urlBuilder.append(tickerSymbol);
        urlBuilder.append(",");
    }/*w  w w  . ja va2 s .  c om*/
    urlBuilder.deleteCharAt(urlBuilder.length() - 1); //remove last ,

    URL urlGoogle = new URL(urlBuilder.toString());
    BufferedReader in = new BufferedReader(new InputStreamReader(urlGoogle.openStream()));

    in.skip(3);

    Gson gson = new GsonBuilder().create();
    JsonReader reader = new JsonReader(in);
    reader.setLenient(true);
    DataGSON[] dataFromGSON = gson.fromJson(reader, DataGSON[].class);

    in.close();

    Map<String, Double> valuesMap;
    valuesMap = new HashMap(dataFromGSON.length);

    for (DataGSON entryGSON : dataFromGSON) {
        String tickerSymbol = entryGSON.t;
        String strValue = entryGSON.l.replaceAll(",", "");
        valuesMap.put(tickerSymbol, Double.parseDouble(strValue));
    }

    return valuesMap;
}

From source file:data.Task1bData.java

License:Apache License

public void readData(String jsonFile) throws IOException {

    int num_questions = 0;
    int num_triples = 0;
    int type_yesno = 0;
    int type_factoid = 0;
    int type_list = 0;
    int type_summary = 0;

    try {//w  ww .j a v a  2 s.  c o m
        JsonReader reader = new JsonReader(new InputStreamReader(new FileInputStream(jsonFile)));
        //reader.setLenient(true);
        //    JsonToken peeknext = reader.peek();
        //    peeknext.

        reader.beginObject();
        while (reader.hasNext()) {

            String nextfield = reader.nextName();
            if (nextfield.equals("questions")) {
                reader.beginArray();
                while (reader.hasNext()) {

                    reader.beginObject();
                    num_questions++;

                    Question qst = new Question();

                    while (reader.hasNext()) {
                        String name = reader.nextName();
                        int k = 0;
                        if (name.equals("body")) {
                            String body = reader.nextString();
                            qst.setBody(body);
                        } else if (name.equals("triples")) {
                            num_triples++;
                            ArrayList<Triple> triples = readTriplesArray(reader);
                            qst.addTriples(triples);
                        } else if (name.equals("type")) {
                            String type = reader.nextString();

                            if (type.equals("yesno")) {
                                qst.setType(Question.YESNO);
                                type_yesno++;

                            } else if (type.equals("factoid")) {
                                qst.setType(Question.FACTOID);
                                type_factoid++;

                            }
                            if (type.equals("summary")) {
                                qst.setType(Question.SUMMARY);
                                type_summary++;

                            }
                            if (type.equals("list")) {
                                qst.setType(Question.LIST);
                                type_list++;

                            }
                        } else if (name.equals("id")) {
                            String id = reader.nextString();
                            qst.setId(id);
                        } else if (name.equals("concepts")) {
                            ArrayList<String> concepts = readConcepts(reader);
                            qst.addConcepts(concepts);
                        } else if (name.equals("documents")) {
                            ArrayList<String> docs = readDocuments(reader);

                            qst.addDocuments(docs);
                        } else if (name.equals("exact_answer")) {
                            ExactAnswer ea = new ExactAnswer();
                            JsonToken peek = reader.peek();
                            if (peek == JsonToken.BEGIN_ARRAY) //list or factoid
                            {
                                reader.beginArray();

                                JsonToken peek1 = reader.peek();
                                ArrayList<String> listOfAnswers = new ArrayList<String>();
                                ArrayList<ArrayList<String>> listofarrays = new ArrayList<ArrayList<String>>();

                                if (peek1 == JsonToken.BEGIN_ARRAY) // list (or factoid-list since BioASQ3)
                                {
                                    /*
                                     * Warning: changed the following for BioASQ 5
                                     * No synonyms in submissions anymore, only in gold files
                                    */
                                    if (VERSION_OF_CHALLENGE == evaluation.EvaluatorTask1b.BIOASQ2
                                            || VERSION_OF_CHALLENGE == evaluation.EvaluatorTask1b.BIOASQ3) {
                                        listofarrays = readExactAnswerListOfArraysv2(reader);
                                        ea.setLists(listofarrays);
                                    } else if (VERSION_OF_CHALLENGE == evaluation.EvaluatorTask1b.BIOASQ5) {
                                        if (!this.isGold) { // For submissions use restricted parsing : only first of synonyms taken into account
                                            listofarrays = readExactAnswerListOfArraysv3(reader);
                                        } else { // For golden read all synonyms normally
                                            listofarrays = readExactAnswerListOfArraysv2(reader);
                                        }
                                        ea.setLists(listofarrays);
                                    } else {
                                        System.out.println("Wrong challenge version. I will exit.");
                                        System.exit(0);
                                    }
                                } else if (peek1 == JsonToken.STRING) // factoid (for BioASQ1&2)
                                {
                                    /*
                                     * Warning: changed the following for BioASQ 3
                                     * we now have list of arrays for factoid 
                                    */
                                    if (VERSION_OF_CHALLENGE == evaluation.EvaluatorTask1b.BIOASQ2) {
                                        listOfAnswers = readExactAnswerArray(reader);
                                        ea.setAnswers(listOfAnswers);
                                    }
                                    //not reached!
                                    else if (VERSION_OF_CHALLENGE == evaluation.EvaluatorTask1b.BIOASQ3) {
                                        listofarrays = readExactAnswerListOfArraysv2(reader);
                                        ea.setLists(listofarrays);
                                    }
                                    /*
                                     * Warning: changed the following for BioASQ 5
                                     * No synonyms are submitted anymore by participants
                                    */
                                    //not reached!
                                    else if (VERSION_OF_CHALLENGE == evaluation.EvaluatorTask1b.BIOASQ5) {
                                        listofarrays = readExactAnswerListOfArraysv3(reader);
                                        ea.setLists(listofarrays);
                                    } else {
                                        System.out.println("Wrong challenge version. I will exit.");
                                        System.exit(0);
                                    }
                                }

                                //ea.setAnswers(listOfAnswers);
                                qst.setExact_answer(ea);
                                reader.endArray();

                            } else if (peek == JsonToken.STRING) //yesno
                            {
                                String yesno_answer = reader.nextString();
                                yesno_answer = yesno_answer.toLowerCase();
                                if (yesno_answer.contains("yes"))
                                    ea.setAnswer("yes");
                                else if (yesno_answer.contains("no"))
                                    ea.setAnswer("no");
                                else {
                                    ea.setAnswer("none");
                                    //  System.out.println("Unknown answer in yesno question: "+yesno_answer);
                                }
                                qst.setExact_answer(ea);
                            }

                        }

                        //                      Edited for BioASQ4 Evaluation (to solve format conflict with Rouge.py)            
                        //                      ideal answers are not evaluated with this code, so no need to read them(Rouge and manual queration is used instead)

                        //                      else if(name.equals("ideal_answer"))
                        //                      {
                        //                          String ideal="";
                        //                          try{ideal = reader.nextString();}catch(IllegalStateException ex){System.out.println(ex.toString());System.out.println(jsonFile);
                        //                          }
                        //                          qst.setIdeal_answer(ideal);
                        //                      }
                        else if (name.equals("snippets")) {
                            ArrayList<Snippet> snippets = readSnippets(reader);
                            qst.addSnippets(snippets);
                        } else {
                            reader.skipValue();

                        }
                    }
                    //reader.skipValue();
                    reader.endObject();
                    this.questions.add(qst);

                }
                reader.endArray();
            } else {
                reader.skipValue();

            }
        }
        reader.endObject();
        /*     System.out.println("Number of questions:"+num_questions);
             System.out.println("Number of triples:"+num_triples);
             System.out.println("Number of yesno:"+type_yesno);
             System.out.println("Number of factoid:"+type_factoid);
             System.out.println("Number of list:"+type_list);
             System.out.println("Number of summary:"+type_summary);*/

    } catch (FileNotFoundException ex) {
        System.out.println("Problem in JSONfile : " + jsonFile);
    }

}

From source file:data.TaskADataParser.java

License:Apache License

/**
 * // w  w  w . j  a  v a  2 s  . c om
 * Return a json reader and opens the array
 * 
 */
public static JsonReader streamParser(String jsonFile) throws IOException {

    int count = 0;
    int abstract_count = 0;
    int duplicates = 0;
    JsonReader reader = null;
    try {
        reader = new JsonReader(new InputStreamReader(new FileInputStream(jsonFile)));
        reader.setLenient(true);
        reader.beginObject();
        String nam = reader.nextName();
        System.out.println(nam);
        reader.beginArray();

    } catch (Exception ex) {
        System.out.println("File not found");
        System.out.println(ex.toString());
    }
    return reader;
}

From source file:de.baydev.hueemulator.util.ConfigUtil.java

License:Open Source License

public AppConfig loadConfig(String config) {

    String configPath = "data/config/" + ((config == null) ? "config" : config) + ".json";
    try (JsonReader reader = new JsonReader(new FileReader(configPath))) {

        appConfig = JsonUtil.getInstance().getGson().fromJson(reader, AppConfig.class);
    } catch (FileNotFoundException ex) {

        ex.printStackTrace();/*ww  w .  ja  va  2 s . co  m*/
    } catch (IOException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
    }

    return appConfig;
}

From source file:de.baydev.hueemulator.util.HueLoader.java

License:Open Source License

public HueBridge loadBridge(String bridgeId) {
    try (JsonReader reader = new JsonReader(new FileReader("data/bridge/" + bridgeId + ".json"))) {
        this.loadedBridge = JsonUtil.getInstance().getGson().fromJson(reader, HueBridge.class);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(HueLoader.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(HueLoader.class.getName()).log(Level.SEVERE, null, ex);
    }//from   w  w  w  .j  a va 2  s  .  com
    return this.loadedBridge;
}

From source file:de.feike.tiingoclient.JSON.java

License:Apache License

/**
 * Deserialize the given JSON string to Java object.
 *
 * @param <T>//from  w  w w.  j  ava2s  . c o  m
 *            Type
 * @param body
 *            The JSON string
 * @param returnType
 *            The type to deserialize into
 * @return The deserialized Java object
 */
@SuppressWarnings("unchecked")
public <T> T deserialize(String body, Type returnType) {
    try {
        if (apiClient.isLenientOnJson()) {
            JsonReader jsonReader = new JsonReader(new StringReader(body));
            // see
            // https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean)
            jsonReader.setLenient(true);
            return gson.fromJson(jsonReader, returnType);
        } else {
            return gson.fromJson(body, returnType);
        }
    } catch (JsonParseException e) {
        // Fallback processing when failed to parse JSON form response body:
        // return the response body string directly for the String return
        // type;
        // parse response body into date or datetime for the Date return
        // type.
        if (returnType.equals(String.class))
            return (T) body;
        else if (returnType.equals(Date.class))
            return (T) apiClient.parseDateOrDatetime(body);
        else
            throw (e);
    }
}

From source file:de.hshannover.f4.trust.irongpm.rest.VisitmetaResource.java

License:Apache License

/**
 * Requests the REST interface for the given path, e.g. "current" or "changes"
 * //from w w w. ja va  2 s.  c o  m
 * @param path
 *            The path for the HTTP request
 * @return The JSON response string
 */
public String get(String path) {
    String json = null;
    boolean connected = true;
    do {
        try {
            URLConnection conn = new URL(mBaseUrl + path + "?rawData=" + mRawXml).openConnection();
            conn.setConnectTimeout(2000);
            conn.connect();
            JsonReader reader = new JsonReader(new InputStreamReader(conn.getInputStream()));
            JsonParser parser = new JsonParser();
            JsonElement rootElement = parser.parse(reader);
            json = rootElement.toString();
            if (!connected) {
                LOGGER.info("VisitmetaResource connection (re-)established");
            }
            connected = true;
        } catch (Exception e) {
            try {
                LOGGER.warn("VisitmetaResource connection failed on " + mBaseUrl
                        + ". Trying again in 5 seconds. Reason: [" + e + "]");
                Thread.sleep(5000);
            } catch (InterruptedException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            connected = false;
        }
    } while (!connected);
    return json;
}

From source file:de.itboehmer.confluence.rest.core.BaseClient.java

License:Apache License

protected JsonReader toJsonReader(InputStream inputStream) throws UnsupportedEncodingException {
    Validate.notNull(inputStream);/*from   www . j  a  va 2s .co m*/
    InputStreamReader reader = new InputStreamReader(inputStream, "UTF-8");
    JsonReader jsonReader = new JsonReader(reader);
    jsonReader.setLenient(true);
    return jsonReader;
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.elasticmi.read.MiJsonMicroImportProcess.java

License:Open Source License

/**
 * Parse the inputStream to an JsonObject.
 * If the inputStream is null, null is returned and the {@link #importProcessMessages} get an error message.
 * //from  ww  w  . j a  v a2 s .c o m
 * @param inputStream
 * @return JsonObject
 */
private JsonObject readJsonFromInputStream(InputStream inputStream) {
    if (inputStream == null) {
        LOGGER.error("The input stream to read the json from was null.");
        return null;
    }

    try {
        JsonReader reader = new JsonReader(new InputStreamReader(inputStream, "UTF-8"));
        return new JsonParser().parse(reader).getAsJsonObject();
    } catch (UnsupportedEncodingException e) {
        LOGGER.error("Error reading json", e);
    } catch (IllegalStateException e) {
        LOGGER.error("Error reading json", e);
    }
    return null;
}