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:modules.menu.model.files_Config.java

public static void OpenConfig() {
    String PATH = null;/*  ww w. j  a va 2  s.  com*/
    Config c = null;
    try {
        PATH = new java.io.File(".").getCanonicalPath() + "/src/modules/menu/model/ConfigFiles/config.json";

    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        XStream xstream = new XStream(new JettisonMappedXmlDriver());
        xstream.setMode(XStream.NO_REFERENCES);
        xstream.alias("Config", Config.class);

        JsonReader lector = new JsonReader(new FileReader(PATH));
        JsonParser parseador = new JsonParser();
        JsonElement raiz = parseador.parse(lector);

        Gson json = new Gson();
        c = json.fromJson(raiz, Config.class);
        Config.getInstance().setCurrency(c.getCurrency());
        Config.getInstance().setDecimals(c.getDecimals());
        Config.getInstance().setFiles(c.getFiles());
        Config.getInstance().setFormatDate(c.getFormatDate());
        Config.getInstance().setLanguage(c.getLanguage());
        Config.getInstance().setTheme(c.getTheme());
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, Language.getInstance().getProperty("openerrorjson"),
                Language.getInstance().getProperty("errorjson"), JOptionPane.ERROR_MESSAGE);
    }
}

From source file:Modules.Reg_user.Model.Utils.Files_lib.json.java

/**
 * Used to auto load registered user data from JSON file format
 *///from w  w w  .j a va  2s  .c  om
public static void autoloadjsonruser() {
    String[] p = { "/src/Modules/Reg_user/Model/Utils/Files/json/ruser.json",
            "/src/Modules/Reg_user/Model/Utils/Files/json/dummy_ruser.json" };
    String p2 = "";
    String PATH = "";
    Reg_user_class a = new Reg_user_class("");

    if (Config_class.getinstance().isDummy() == true) {
        p2 = p[1];
    } else {
        p2 = p[0];
    }

    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() + p2;

        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) {
                a = json.fromJson(element, Reg_user_class.class);
                Singleton_ruser.rus.add(a);
            } //for end
        } //if end

    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, Singleton_app.lang.getProperty("problopejson"), "Error!",
                JOptionPane.INFORMATION_MESSAGE);
        //                                                JOptionPane.showMessageDialog(null,"Error auto-loading JSON file");
    }
}

From source file:Modules.Reg_user.Model.Utils.Files_lib.json.java

/**
 * Used to load registered user data from JSON file format
 *///from w  ww  .j  a v  a 2s.c om
public static void loadjsonruser() {
    String path = "";
    Reg_user_class ruser = 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);

        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setAcceptAllFileFilterUsed(false);
        fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("JSON (*.json)", "json"));
        int selection = fileChooser.showOpenDialog(null);
        if (selection == JFileChooser.APPROVE_OPTION) {
            File JFC = fileChooser.getSelectedFile();
            path = JFC.getAbsolutePath();

            Singleton_ruser.rus.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) {
                ruser = json.fromJson(element, Reg_user_class.class);
                Singleton_ruser.rus.add(ruser);
            }
        }

    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, Singleton_app.lang.getProperty("problopejson"), "Error",
                JOptionPane.INFORMATION_MESSAGE);
        //                                               JOptionPane.showMessageDialog(null,"Error loading JSON file");
    }
}

From source file:modules.users.userreg.model.utils.json_Userreg.java

/**
 * abre un fichero con usuarios registrados en JSON
 *//*from w  ww . ja  v a  2s.  com*/
public static void OpenUserreg() {
    String PATH = null;
    registered_user userreg = new registered_user("");

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

        JFileChooser fileChooser = new JFileChooser();

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

        int seleccion = fileChooser.showOpenDialog(null);
        if (seleccion == JFileChooser.APPROVE_OPTION) {
            File JFC = fileChooser.getSelectedFile();
            PATH = JFC.getAbsolutePath();

            singleton.userreg.clear();

            JsonReader lector = new JsonReader(new FileReader(PATH));
            JsonParser parseador = new JsonParser();
            JsonElement raiz = parseador.parse(lector);

            Gson json = new Gson();
            JsonArray lista = raiz.getAsJsonArray();
            for (JsonElement elemento : lista) {
                userreg = json.fromJson(elemento, registered_user.class);
                singleton.userreg.add(userreg);
            }
        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, Language.getInstance().getProperty("openerrorjson"),
                Language.getInstance().getProperty("errorjson"), JOptionPane.ERROR_MESSAGE);
    }
}

From source file:modules.users.userreg.model.utils.json_Userreg.java

/**
 * abre automaticamente un fichero en JSON que contenga los usuarios registrados
 *//*w  w  w  .j a  v  a2 s  . com*/
public static void OpenAutoUserreg() {
    String PATH = null;
    registered_user userreg = new registered_user("");
    try {
        PATH = new java.io.File(".").getCanonicalPath()
                + "/src/modules/users/userreg/model/files/json/json.json";
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        XStream xstream = new XStream(new JettisonMappedXmlDriver());
        xstream.setMode(XStream.NO_REFERENCES);
        xstream.alias("Registered_user", registered_user.class);

        singleton.userreg.clear();

        JsonReader lector = new JsonReader(new FileReader(PATH));
        JsonParser parseador = new JsonParser();
        JsonElement raiz = parseador.parse(lector);

        Gson json = new Gson();
        JsonArray lista = raiz.getAsJsonArray();
        for (JsonElement elemento : lista) {
            userreg = json.fromJson(elemento, registered_user.class);
            singleton.userreg.add(userreg);
        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, Language.getInstance().getProperty("openerrorjson"),
                Language.getInstance().getProperty("errorjson"), JOptionPane.ERROR_MESSAGE);
    }
}

From source file:mx.ipn.escom.supernaut.nile.logic.CommonBean.java

protected void streamedUnmarshall(HttpEntity entity) throws IOException {
    model = gson.fromJson(new JsonReader(new InputStreamReader(entity.getContent(), StandardCharsets.UTF_8)),
            modelType);/* w  ww .  ja v a 2s  . c  om*/
}

From source file:mx.ipn.escom.supernaut.nile.logic.CommonBean.java

@Override
public List<Model> getAll() {
    List<Model> list;/*from ww  w .  j  av  a  2s.c  o m*/
    HttpGet request = new HttpGet(baseUri);
    request.addHeader(JSON_IN_HEAD);
    HttpResponse response;
    try {
        response = client.execute(HOST, request);
        list = (List<Model>) gson.fromJson(
                new JsonReader(
                        new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8)),
                List.class);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
    StatusLine statusLine = response.getStatusLine();
    if (statusLine.getStatusCode() < 200 || statusLine.getStatusCode() > 299)
        throw new RuntimeException(statusLine.getReasonPhrase());
    return list;
}

From source file:nectec.thai.widget.address.repository.JsonParser.java

License:Apache License

public static <T> List<T> parse(Context context, String jsonFileName, Class<T> tClass) {
    List<T> allProvince = new ArrayList<>();
    Gson gson = new Gson();
    try {//from w  ww .  ja v  a2 s .c  o m
        InputStream inputStream = context.getAssets().open(jsonFileName);
        JsonReader reader = new JsonReader(new InputStreamReader(inputStream, "UTF-8"));
        reader.beginArray();
        while (reader.hasNext()) {
            T message = gson.fromJson(reader, tClass);
            allProvince.add(message);
        }
        reader.endArray();
        reader.close();
    } catch (IOException e) {
        if (BuildConfig.DEBUG)
            Log.e(TAG, "parse() error.", e);
    }
    return allProvince;
}

From source file:net.ae97.pokebot.extensions.scollstopic.ScrollsTopic.java

License:Open Source License

@Override
public void runEvent(CommandEvent event) {
    if (!event.getChannel().getName().equalsIgnoreCase("#scrollsguide")) {
        return;//from  ww w .  j a va 2  s.  c o  m
    }
    try {
        URL url = new URL(VERSION_URL);
        try (JsonReader json = new JsonReader(new BufferedReader(new InputStreamReader(url.openStream())))) {
            json.beginObject();
            json.nextName();
            json.beginObject();
            json.nextName();
            char[] prodVersion = json.nextString().replace("version-", "").replace("-production", "")
                    .toCharArray();
            String prodVersionCompiled = new String(
                    new char[] { prodVersion[0], '.', prodVersion[2], '.', prodVersion[3] });
            json.nextName();
            char[] testVersion = json.nextString().replace("version-", "").replace("-test", "").toCharArray();
            String testVersionCompiled = new String(
                    new char[] { testVersion[0], '.', testVersion[2], '.', testVersion[3] });
            switch (event.getCommand()) {
            case "versions":
                event.getChannel().send().message(
                        "Latest versions - Prod: " + prodVersionCompiled + ", Test: " + testVersionCompiled);
                break;
            case "updatetopic":
                String topic = getConfig().getString("topic").replace("{prod}", prodVersionCompiled)
                        .replace("{test}", testVersionCompiled);
                if (!event.getChannel().getTopic().equals(topic) && event.getUser().isVerified()) {
                    event.getChannel().send().setTopic(topic);
                }
                break;
            }
        }
    } catch (IOException e) {
    }
}

From source file:net.cnri.doregistrytools.registrar.replication.ReplicationPoller.java

License:Open Source License

public void getRemoteSchemas(CloseableHttpClient httpClient, RemoteRepositoryInfo remoteRepository)
        throws IOException, RepositoryException {
    String baseUri = remoteRepository.baseUri;
    if (baseUri.endsWith("/")) {
        baseUri = baseUri.substring(0, baseUri.length() - 1);
    }/*from  w ww.  j a  v  a  2  s  .  co m*/
    String url = baseUri + "/replicate/schemas";
    HttpGet request = new HttpGet(url);
    try {
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(remoteRepository.username,
                remoteRepository.password);
        request.addHeader(new BasicScheme(Charset.forName("UTF-8")).authenticate(creds, request, null));
    } catch (AuthenticationException e) {
        throw new AssertionError(e);
    }

    CloseableHttpResponse response = null;
    HttpEntity entity = null;
    try {
        response = httpClient.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            logger.error("Exception in getRemoteSchemas response code: " + statusCode);
            return;
        }
        entity = response.getEntity();
        InputStream in = entity.getContent();
        Reader reader = new InputStreamReader(in, "UTF-8");
        JsonReader jsonReader = new JsonReader(reader);
        jsonReader.beginArray();
        while (jsonReader.hasNext()) {
            registrar.addReplicatedObject(jsonReader, remoteRepository.baseUri);
        }
    } finally {
        if (entity != null)
            EntityUtils.consumeQuietly(entity);
        if (response != null)
            try {
                response.close();
            } catch (IOException e) {
            }
    }

}