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:com.aliyun.openservices.odps.console.common.JobDetailInfo.java

License:Apache License

private void getInfoFromJsonSummary(List<FuxiJob> fuxiJobs, String jsonSummaryContent) throws IOException {
    jsonSummaryContent = jsonSummaryContent.replaceAll("\n", " ");
    jsonSummaryContent = jsonSummaryContent.replaceAll("\t", " ");
    jsonSummaryContent = jsonSummaryContent.replace("\\\"", "\"");

    JsonReader reader = new JsonReader(
            new InputStreamReader(new ByteArrayInputStream(jsonSummaryContent.getBytes())));

    reader.beginObject();//from  ww  w.  j av a  2 s  . c  o m
    while (reader.hasNext()) {
        String name = reader.nextName();
        if (name.equals("jobs")) {
            reader.beginArray();

            int jobCount = 0;
            // Get more info for each job
            while (reader.hasNext()) {
                reader.beginObject();
                FuxiJob job = fuxiJobs.get(jobCount);
                while (reader.hasNext()) {
                    String nameInJobs = reader.nextName();
                    if (nameInJobs.equals("tasks")) {
                        reader.beginObject();

                        int taskCount = 0;
                        // Get more info for each task
                        while (reader.hasNext()) {
                            String taskName = reader.nextName();
                            FuxiTask task = job.tasks.get(taskCount);

                            // Get the downstream tasks info
                            reader.beginObject();
                            while (reader.hasNext()) {
                                if (reader.nextName().equals("output_record_counts")) {
                                    List<String> downTasks = new ArrayList<String>();
                                    reader.beginObject();
                                    while (reader.hasNext()) {
                                        downTasks.add(reader.nextName());
                                        reader.skipValue();
                                    }
                                    reader.endObject();
                                    addUpAndDownTasks(job, task.name, downTasks);
                                } else {
                                    reader.skipValue();
                                }
                            }
                            reader.endObject();
                            taskCount++;
                        }
                        reader.endObject();
                    } else {
                        reader.skipValue();
                    }
                }
                reader.endObject();
                jobCount++;
            }
            reader.endArray();
        } else {
            reader.skipValue();
        }
    }
    reader.endObject();
}

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;//from w w  w  . j  a  v  a 2 s.  c o m

    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 {//w ww .j  a  v  a 2 s.  co 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) {/*ww w.  j a v a 2s.  co  m*/
    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;/*from w  ww . j a  v  a  2 s. c  om*/
    File file = getSingleFile(folder, shard);
    if (!file.exists()) {
        return fileMap;
    }
    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.appunity.ant.Utils.java

License:Apache License

protected static ProjectProfile getProfile(Task task, String profilePath) {
    ProjectProfile profile = null;// w  w  w .  ja v a  2s .co  m
    try {
        Gson gson = new Gson();
        JsonParser parser = new JsonParser();
        InputStreamReader reader = new InputStreamReader(
                new FileInputStream(obtainValidPath(task, profilePath, "project.profile")), "UTF-8");
        JsonReader jsonReader = new JsonReader(reader);
        JsonObject asJsonObject = parser.parse(jsonReader).getAsJsonObject();
        profile = gson.fromJson(asJsonObject.get("project"), ProjectProfile.class);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(InitProjectTask.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(InitProjectTask.class.getName()).log(Level.SEVERE, null, ex);
    } catch (JsonIOException ex) {
        Logger.getLogger(InitProjectTask.class.getName()).log(Level.SEVERE, null, ex);
    } catch (JsonSyntaxException ex) {
        Logger.getLogger(InitProjectTask.class.getName()).log(Level.SEVERE, null, ex);
    }
    return profile;
}

From source file:com.arbalest.net.converter.GsonConverter.java

License:Open Source License

private Object convertObject(InputStream in, Type type)
        throws ArbalestNetworkException, ArbalestResponseException {
    JsonReader reader = null;// www  .jav a2 s .c o m
    try {
        reader = new JsonReader(new InputStreamReader(in, DEFAULT_CHARSET));
        Gson gson = mDefaultGsonBuilder.create();
        return gson.fromJson(reader, type);
    } catch (JsonSyntaxException e) {
        throw new ArbalestResponseException(e);
    } catch (IOException e) {
        throw new ArbalestNetworkException(e);
    } finally {
        CloseableUtils.close(reader);
    }
}

From source file:com.arbalest.net.converter.GsonConverter.java

License:Open Source License

@SuppressWarnings("unchecked")
private <T> T convertArray(InputStream in, Class<T> clazz)
        throws ArbalestNetworkException, ArbalestResponseException {
    JsonReader reader = null;// www  .  ja va 2s  . com
    try {
        reader = new JsonReader(new InputStreamReader(in, DEFAULT_CHARSET));
        Class<?> type = clazz.getComponentType();
        Gson gson = mDefaultGsonBuilder.create();
        List<Object> list = new ArrayList<Object>();

        reader.beginArray();

        while (reader.hasNext()) {
            list.add(gson.fromJson(reader, type));
        }

        reader.endArray();

        return (T) list.toArray((T[]) Array.newInstance(type, list.size()));
    } catch (JsonSyntaxException e) {
        throw new ArbalestResponseException(e);
    } catch (IOException e) {
        throw new ArbalestNetworkException(e);
    } finally {
        CloseableUtils.close(reader);
    }
}

From source file:com.asakusafw.lang.inspection.json.JsonInspectionNodeRepository.java

License:Apache License

@Override
public InspectionNode load(InputStream input) throws IOException {
    try (JsonReader reader = new JsonReader(new InputStreamReader(input, ENCODING))) {
        InspectionNode result = gson.fromJson(reader, InspectionNode.class);
        if (result == null) {
            throw new IOException("there are no valid JSON object");
        }/*www  . ja  va 2  s. c o m*/
        return result;
    } catch (JsonParseException e) {
        throw new IOException("invalid JSON object", e);
    }
}

From source file:com.astech.mnlottery.web.EditGameList.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request/*  w ww  .  j  a  v a  2s  .c o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String operation = request.getParameter("operation");
    if (operation != null) {
        int lotteryGameId = Integer.parseInt(request.getParameter("lotteryGameId"));
        switch (operation) {
        case "delete":
            Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
            LotteryGameResponse lotGameObj = null;
            String fetchUrl = "http://localhost:8080/AstonTech.MNLottery.RestService/webresources/lotGame/get/";
            fetchUrl = fetchUrl + lotteryGameId;
            try {
                URLConnection urlConnection = new URL(fetchUrl).openConnection();
                urlConnection.connect();
                JsonReader reader = new JsonReader(new InputStreamReader(urlConnection.getInputStream()));
                gson = new GsonBuilder().create();
                Type type = new TypeToken<LotteryGameResponse>() {
                }.getType();
                lotGameObj = gson.fromJson(reader, type);
            } catch (IOException | JsonIOException | JsonSyntaxException ex) {
                System.out.println("Exception caught: " + ex);
            }

            String jsonGame = gson.toJson(lotGameObj);
            fetchUrl = "http://localhost:8080/AstonTech.MNLottery.RestService/webresources/lotGame/delete";
            try {
                HttpURLConnection urlConnection = (HttpURLConnection) new URL(fetchUrl).openConnection();
                urlConnection.setRequestMethod("POST");
                urlConnection.setDoOutput(true);
                urlConnection.setDoInput(true);
                urlConnection.addRequestProperty("Content-type", "application/json");
                urlConnection.setRequestProperty("Accept", "text/plain");

                OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
                out.write(jsonGame);
                out.flush();

                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(urlConnection.getInputStream()));
                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
                }
            } catch (Exception ex) {
                System.out.println("Exception caught: " + ex);
            }
            break;
        default:
            break;
        }
    }
    request.setAttribute("navBarContent", Builders.buildNavBar(0));
    request.setAttribute("homeNavBar", Builders.buildHomeNavBar(4));

    Collection<LotteryGameResponse> lotGameCol = null;
    lotGameCol = Builders.getGameCollection();
    request.setAttribute("lotteryGameCol", lotGameCol);

    request.getRequestDispatcher("./editGameList.jsp").forward(request, response);
}