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:framework.modules.users.admin.Model.utils.lib_Afiles.json.java

public static void openjson_admin() {

    String PATH = null;//from   www . j a  va2  s.  c  om
    admin_class a = new admin_class("");

    try {
        XStream xstream = new XStream(new JettisonMappedXmlDriver());
        xstream.setMode(XStream.NO_REFERENCES);
        xstream.alias("admin", admin_class.class);

        JFileChooser filechooser = new JFileChooser();

        filechooser.setAcceptAllFileFilterUsed(false);
        filechooser.addChoosableFileFilter(new FileNameExtensionFilter("JSON (*.json)", "json"));

        int selection = filechooser.showOpenDialog(null);
        if (selection == filechooser.APPROVE_OPTION) {
            File JFC = filechooser.getSelectedFile();
            PATH = JFC.getAbsolutePath();

            singleton_admin.admin.clear();

            JsonReader reader = new JsonReader(new FileReader(PATH));
            JsonParser parser = new JsonParser();
            JsonElement root = parser.parse(reader);

            Gson json = new Gson();
            JsonArray list = root.getAsJsonArray();
            for (JsonElement element : list) {
                a = json.fromJson(element, admin_class.class);
                singleton_admin.admin.add(a);
            }
        }

    } catch (Exception e) {

        JOptionPane.showMessageDialog(null, "Error al leer el JSON", "Error", JOptionPane.ERROR_MESSAGE);
    }

    //return singleton.admin;
}

From source file:framework.modules.users.client.Model.utils.lib_Cfiles.C_auto_json.java

public static void auto_openjson_client() {

    String PATH = null;/* www.  j av a 2  s. c om*/
    client_class c = new client_class("");

    try {
        XStream xstream = new XStream(new JettisonMappedXmlDriver());
        xstream.setMode(XStream.NO_REFERENCES);
        xstream.alias("client_class", client_class.class);

        PATH = new java.io.File(".").getCanonicalPath()
                + "/src/framework/modules/users/client/Model/utils/client_files/json/auto_json.json";

        File path = new File(PATH);

        if (path.exists()) {
            JsonReader reader = new JsonReader(new FileReader(PATH));
            JsonParser parser = new JsonParser();
            JsonElement root = parser.parse(reader);

            Gson json = new Gson();
            JsonArray list = root.getAsJsonArray();
            for (JsonElement element : list) {
                c = json.fromJson(element, client_class.class);
                singleton_client.client.add(c);
                //singleton.admin = (ArrayList<Usuarios>) xstream.fromXML(new FileReader(PATH));
            }
        }
    } catch (Exception e) {

        JOptionPane.showMessageDialog(null, class_language.getinstance().getProperty("error_open_json"),
                "Error", JOptionPane.ERROR_MESSAGE);
    }

}

From source file:framework.modules.users.client.Model.utils.lib_Cfiles.json.java

public static void openjson_client() {

    String PATH = null;/*from   w  w w .j  a va 2  s  . co m*/
    client_class c = new client_class("");

    try {
        XStream xstream = new XStream(new JettisonMappedXmlDriver());
        xstream.setMode(XStream.NO_REFERENCES);
        xstream.alias("client", client_class.class);

        JFileChooser filechooser = new JFileChooser();

        filechooser.setAcceptAllFileFilterUsed(false);
        filechooser.addChoosableFileFilter(new FileNameExtensionFilter("JSON (*.json)", "json"));

        int selection = filechooser.showOpenDialog(null);
        if (selection == filechooser.APPROVE_OPTION) {
            File JFC = filechooser.getSelectedFile();
            PATH = JFC.getAbsolutePath();

            singleton_client.client.clear();

            JsonReader reader = new JsonReader(new FileReader(PATH));
            JsonParser parser = new JsonParser();
            JsonElement root = parser.parse(reader);

            Gson json = new Gson();
            JsonArray list = root.getAsJsonArray();
            for (JsonElement element : list) {
                c = json.fromJson(element, client_class.class);
                singleton_client.client.add(c);
            }
        }

    } catch (Exception e) {

        JOptionPane.showMessageDialog(null, "Error al leer el JSON", "Error", JOptionPane.ERROR_MESSAGE);
    }
}

From source file:framework.modules.users.reg_user.Model.utils.lib_Rfiles.json.java

public static void openjson_reg() {

    String PATH = null;//from www  .  j av a 2s.com
    reg_user_class u = new reg_user_class("");

    try {
        XStream xstream = new XStream(new JettisonMappedXmlDriver());
        xstream.setMode(XStream.NO_REFERENCES);
        xstream.alias("reg_user", reg_user_class.class);

        JFileChooser filechooser = new JFileChooser();

        filechooser.setAcceptAllFileFilterUsed(false);
        filechooser.addChoosableFileFilter(new FileNameExtensionFilter("JSON (*.json)", "json"));

        int selection = filechooser.showOpenDialog(null);
        if (selection == filechooser.APPROVE_OPTION) {
            File JFC = filechooser.getSelectedFile();
            PATH = JFC.getAbsolutePath();

            singleton_reg.reg.clear();

            JsonReader reader = new JsonReader(new FileReader(PATH));
            JsonParser parser = new JsonParser();
            JsonElement root = parser.parse(reader);

            Gson json = new Gson();
            JsonArray list = root.getAsJsonArray();
            for (JsonElement element : list) {
                u = json.fromJson(element, reg_user_class.class);
                singleton_reg.reg.add(u);
            }
        }

    } catch (Exception e) {

        JOptionPane.showMessageDialog(null, "Error al leer el JSON", "Error", JOptionPane.ERROR_MESSAGE);
    }
}

From source file:framework.modules.users.reg_user.Model.utils.lib_Rfiles.R_auto_json.java

public static void auto_openjson_reg() {

    String PATH = null;/*  www.j  a v  a  2s .c  o m*/
    reg_user_class u = new reg_user_class("");

    try {
        XStream xstream = new XStream(new JettisonMappedXmlDriver());
        xstream.setMode(XStream.NO_REFERENCES);
        xstream.alias("reg_user_class", reg_user_class.class);

        PATH = new java.io.File(".").getCanonicalPath()
                + "/src/framework/modules/users/reg_user/Model/utils/reg_files/json/auto_json.json";

        File path = new File(PATH);

        if (path.exists()) {
            JsonReader reader = new JsonReader(new FileReader(PATH));
            JsonParser parser = new JsonParser();
            JsonElement root = parser.parse(reader);

            Gson json = new Gson();
            JsonArray list = root.getAsJsonArray();
            for (JsonElement element : list) {
                u = json.fromJson(element, reg_user_class.class);
                singleton_reg.reg.add(u);
                //singleton.admin = (ArrayList<Usuarios>) xstream.fromXML(new FileReader(PATH));
            }
        }
    } catch (Exception e) {

        JOptionPane.showMessageDialog(null, class_language.getinstance().getProperty("error_open_json"),
                "Error", JOptionPane.ERROR_MESSAGE);
    }

}

From source file:geomesa.example.twitter.ingest.TwitterParser.java

License:Apache License

/**
 * Parse an input stream using GSON//from  w  w w  .j  a  v  a  2 s .com
 */
public List<SimpleFeatureCollection> parse(final InputStream is, final String sourceName) throws IOException {
    log.info(sourceName + " - starting parsing");

    final long startTime = System.currentTimeMillis();

    final List<SimpleFeatureCollection> results = new ArrayList<>();
    final Reader bufReader = new BufferedReader(new InputStreamReader(is));
    final JsonReader jr = new JsonReader(bufReader);
    jr.setLenient(true);

    DefaultFeatureCollection batch = new DefaultFeatureCollection(featureName, twitterType);

    long numGoodTweets = 0;
    long numBadTweets = 0;
    JsonObject obj;
    while ((obj = next(jsonParser, jr, sourceName)) != null) {
        SimpleFeature sf = null;
        try {
            sf = convertToFeature(obj, builder, geoFac, df);
        } catch (Exception e) {
            // parsing error
        }
        if (sf != null && sf.getDefaultGeometry() != null) {
            batch.add(sf);
            numGoodTweets++;
            if (numGoodTweets % BATCH_SIZE == 0) {
                results.add(batch);
                batch = new DefaultFeatureCollection(featureName, twitterType);
            }
            if (numGoodTweets % 100_000 == 0) {
                log.debug(Long.toString(numGoodTweets) + " records parsed");
            }
        } else {
            numBadTweets++;
        }
    }
    // add remaining results
    if (!batch.isEmpty()) {
        results.add(batch);
    }
    final long parseTime = System.currentTimeMillis() - startTime;
    log.info(sourceName + " - parsed " + numGoodTweets + " skipping " + numBadTweets + " invalid tweets in "
            + parseTime + "ms");
    return results;
}

From source file:GoEuroTest_GiladM.GoEuroTest_GiladM.java

public static void main(String[] args) throws Exception {
    try {//w w w .  java 2  s.  c o m
        // Make sure a city_name argument was given
        if (args.length < 1) {
            errPrintAndExit("please supply a city name.");
        }
        String city_name = args[0];

        URL url = new URL("http://api.goeuro.com/api/v2/position/suggest/en/" + city_name);
        Path CSVfilePath = Paths.get(city_name + ".csv");

        // Open URL & JSON stream readers
        System.out.println("Connecting to the GoEuro API");
        try (InputStreamReader URLin = new InputStreamReader(url.openStream(), "UTF-8");
                JsonReader JSONin = new JsonReader(URLin);) {
            // Open CSV writer
            System.out.println("Creating the CSV file");
            // Delete the file if already exists
            Files.deleteIfExists(CSVfilePath);
            try (BufferedWriter CSVout = Files.newBufferedWriter(CSVfilePath)) {
                System.out.println("Writing data to the CSV file");
                // Write column headers
                CSVout.write("_id,name,type,latitude,longitude");
                CSVout.newLine();

                // Look for the JSON array beginning token
                JSONin.beginArray();

                Gson gson = new Gson();
                while (JSONin.hasNext()) {
                    // Gson will look for the next point (JSON object),
                    // comparing to the Point class structure
                    // and return it as an object (if exists)
                    Point point = gson.fromJson(JSONin, Point.class);

                    // Create a CSV line string from the point Fields
                    StringJoiner sj;
                    sj = new StringJoiner(",");
                    sj.add(point._id);
                    sj.add(point.name);
                    sj.add(point.type);
                    if (point.geo_position == null)
                        point.geo_position = new Geo_position();
                    sj.add(point.geo_position.latitude);
                    sj.add(point.geo_position.longitude);
                    String SCVline = sj.toString();

                    // Write to file
                    CSVout.write(SCVline);
                    CSVout.newLine();
                    CSVout.flush();
                }

                // Look for the JSONarray end token
                JSONin.endArray();
            } catch (Exception exc) {

                // Delete the CSV file (if exists)
                Files.deleteIfExists(CSVfilePath);

                String excName = exc.getClass().getSimpleName();
                // If the exception was thrown by one of the GSON methods
                if (Arrays.asList("MalformedJsonException", "EOFException", "JsonSyntaxException",
                        "IllegalStateException").contains(excName)) {
                    errPrintAndExit("the JSON data is corrupt or not in the excpected format.");
                }
                // If the exception was thrown by one of the CSV handling methods
                else {
                    errPrintAndExit("unable to write to the CSV file. "
                            + "Make sure the file is not write-protected, not currently in use "
                            + "and that the program has file management permissions for the current path, "
                            + "and try again.");
                }
            }
        } catch (IOException | JsonIOException exc) {
            errPrintAndExit("unable to read data from the GoEuro API. Please try again.");
        }

        System.out.println("Done! the file " + CSVfilePath.toString() + " was created in the current path.");

    } catch (Exception exc) {
        errPrintAndExit("an unexcpected error has occured. Please try again.");
    }
}

From source file:gov.pnnl.goss.gridappsd.testmanager.CompareResults.java

License:Open Source License

public SimulationOutput getOutputProperties(String path) {
    Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
    JsonReader jsonReader;//from   ww w.j  a  v  a 2  s .  c  o m
    SimulationOutput testScript = null;
    try {
        jsonReader = new JsonReader(new FileReader(path));
        jsonReader.setLenient(true);
        testScript = gson.fromJson(new FileReader(path), SimulationOutput.class);
        jsonReader.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return testScript;
}

From source file:gson_ext.Decoder.java

License:Apache License

private void decodeChunk(ThreadContext context, IRubyObject source) {
    Ruby ruby = context.getRuntime();/*from  www  .j  ava  2 s  . c  o m*/

    Reader sourceReader = prepareSourceReader(ruby, context, source);
    String memory = decodeMemory.getMemory();
    if (memory.length() > 0) {
        Reader memoryReader = new StringReader(memory);
        sourceReader = new SequenceReader(memoryReader, sourceReader);
    }
    decodeMemory.clearMemory();
    decodeMemory.setOrigin(sourceReader);

    if (reader == null) {
        reader = new JsonReader(decodeMemory);
    } else {
        reader.recoverAfterBreak(decodeMemory);
    }
    reader.setLenient(this.lenient);
    reader.setChunkMode(onDocumentCallback != null);

    if (memory.length() > 0) {
        try {
            reader.peek();
        } catch (IOException ex) {
            //TODO: try to avoid allowing every "End of input" exception
            if (onDocumentCallback == null && !isStartWith(ex.getMessage(), "End of input at line")) {
                throw DecodeError.newDecodeError(ruby, ex.getMessage());
            }
        }
    }

    IRubyObject val;
    try {
        while (true) {
            JsonToken token = reader.peek();
            switch (token) {
            case END_ARRAY:
                reader.endArray();
                nestedArrayLevel -= 1;
                if (builderStack.size() > 1) {
                    builderStack.pop();
                }
                checkAndFireCallback(context);

                break;
            case END_OBJECT:
                reader.endObject();
                nestedHashLevel -= 1;
                if (builderStack.size() > 1) {
                    builderStack.pop();
                }
                checkAndFireCallback(context);

                break;
            case NAME:
                if (this.symbolizeKeys) {
                    val = RubySymbol.newSymbol(ruby, reader.nextName());
                } else {
                    val = RubyString.newString(ruby, reader.nextName());
                }
                appendValue(context, val);

                break;
            case BEGIN_OBJECT:
                reader.beginObject();
                nestedHashLevel += 1;
                appendValue(context, RubyHash.newHash(ruby));

                break;
            case BEGIN_ARRAY:
                reader.beginArray();
                nestedArrayLevel += 1;
                appendValue(context, RubyArray.newArray(ruby));

                break;
            case STRING:
                val = RubyString.newString(ruby, reader.nextString());
                appendValue(context, val);

                break;
            case NUMBER:
                String tmp = reader.nextString();
                if (floatPattern.matcher(tmp).find()) {
                    val = RubyNumeric.str2fnum(ruby, RubyString.newString(ruby, tmp));
                } else {
                    val = RubyNumeric.str2inum(ruby, RubyString.newString(ruby, tmp), 10);
                }
                appendValue(context, val);

                break;
            case BOOLEAN:
                val = RubyBoolean.newBoolean(ruby, reader.nextBoolean());
                appendValue(context, val);

                break;
            case NULL:
                reader.nextNull();
                appendValue(context, context.nil);

                break;
            case END_DOCUMENT:
                return;
            default:
                throw DecodeError.newDecodeError(ruby, String.format("Unknown token: %s", token.toString()));
            }

            reader.prepareForBreak();
            decodeMemory.retainMemory(reader.getUnreadBufferLength());
        }
    } catch (MalformedJsonException ex) {
        if (onDocumentCallback != null && (isStartWith(ex.getMessage(), "Unterminated string at line")
                || isStartWith(ex.getMessage(), "Unterminated array at line")
                || isStartWith(ex.getMessage(), "Unterminated object at line") || //TODO: try to avoid allowing this
                isStartWith(ex.getMessage(), "Unterminated escape sequence at line"))) {
            return;
        } else {
            throw DecodeError.newDecodeError(ruby, ex.getMessage());
        }
    } catch (IOException ex) {
        if (onDocumentCallback != null && isStartWith(ex.getMessage(), "End of input at line")) {
            return;
        } else {
            throw DecodeError.newDecodeError(ruby, ex.getMessage());
        }
    } catch (Exception ex) {
        throw DecodeError.newDecodeError(ruby, ex.getMessage());
    }
}

From source file:ilearnrw.prototype.application.JsonHandler.java

License:Open Source License

public Object fromJson(java.lang.reflect.Type type) {

    Object obj = null;/*from w w  w.  j ava  2 s .c  o m*/
    try {
        InputStream inputStream = ResourceLoader.getInstance().getInputStream(this.type, path);
        JsonReader reader = new JsonReader(new InputStreamReader(inputStream, "UTF-8"));
        obj = gson.fromJson(reader, type);
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
        return obj;
    }

    return obj;
}