Search in sources :

Example 1 with JsonReader

use of com.google.gson.stream.JsonReader in project elastic-job by dangdangdotcom.

the class GsonFactoryTest method assertRegisterTypeAdapter.

@Test
public void assertRegisterTypeAdapter() {
    Gson beforeRegisterGson = GsonFactory.getGson();
    GsonFactory.registerTypeAdapter(GsonFactoryTest.class, new TypeAdapter() {

        @Override
        public Object read(final JsonReader in) throws IOException {
            return null;
        }

        @Override
        public void write(final JsonWriter out, final Object value) throws IOException {
            out.jsonValue("test");
        }
    });
    assertThat(beforeRegisterGson.toJson(new GsonFactoryTest()), is("{}"));
    assertThat(GsonFactory.getGson().toJson(new GsonFactoryTest()), is("test"));
}
Also used : TypeAdapter(com.google.gson.TypeAdapter) Gson(com.google.gson.Gson) JsonReader(com.google.gson.stream.JsonReader) IOException(java.io.IOException) JsonWriter(com.google.gson.stream.JsonWriter) Test(org.junit.Test)

Example 2 with JsonReader

use of com.google.gson.stream.JsonReader in project zeppelin by apache.

the class Notebook method importNote.

/**
   * import JSON as a new note.
   *
   * @param sourceJson - the note JSON to import
   * @param noteName   - the name of the new note
   * @return note ID
   * @throws IOException
   */
public Note importNote(String sourceJson, String noteName, AuthenticationInfo subject) throws IOException {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setPrettyPrinting();
    Gson gson = gsonBuilder.registerTypeAdapter(Date.class, new NotebookImportDeserializer()).create();
    JsonReader reader = new JsonReader(new StringReader(sourceJson));
    reader.setLenient(true);
    Note newNote;
    try {
        Note oldNote = gson.fromJson(reader, Note.class);
        convertFromSingleResultToMultipleResultsFormat(oldNote);
        newNote = createNote(subject);
        if (noteName != null)
            newNote.setName(noteName);
        else
            newNote.setName(oldNote.getName());
        List<Paragraph> paragraphs = oldNote.getParagraphs();
        for (Paragraph p : paragraphs) {
            newNote.addCloneParagraph(p);
        }
        notebookAuthorization.setNewNotePermissions(newNote.getId(), subject);
        newNote.persist(subject);
    } catch (IOException e) {
        logger.error(e.toString(), e);
        throw e;
    }
    return newNote;
}
Also used : GsonBuilder(com.google.gson.GsonBuilder) StringReader(java.io.StringReader) Gson(com.google.gson.Gson) JsonReader(com.google.gson.stream.JsonReader) IOException(java.io.IOException) Date(java.util.Date)

Example 3 with JsonReader

use of com.google.gson.stream.JsonReader in project buck by facebook.

the class WorkerProcess method ensureLaunchAndHandshake.

public synchronized void ensureLaunchAndHandshake() throws IOException {
    if (handshakePerformed) {
        return;
    }
    LOG.debug("Starting up process %d using command: \'%s\'", this.hashCode(), Joiner.on(' ').join(processParams.getCommand()));
    launchedProcess = executor.launchProcess(processParams);
    JsonWriter processStdinWriter = new JsonWriter(new BufferedWriter(new OutputStreamWriter(launchedProcess.getOutputStream())));
    JsonReader processStdoutReader = new JsonReader(new BufferedReader(new InputStreamReader(launchedProcess.getInputStream())));
    protocol = new WorkerProcessProtocolZero(executor, launchedProcess, processStdinWriter, processStdoutReader, stdErr);
    int messageID = currentMessageID.getAndAdd(1);
    LOG.debug("Sending handshake to process %d", this.hashCode());
    protocol.sendHandshake(messageID);
    LOG.debug("Receiving handshake from process %d", this.hashCode());
    protocol.receiveHandshake(messageID);
    handshakePerformed = true;
}
Also used : InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) JsonReader(com.google.gson.stream.JsonReader) OutputStreamWriter(java.io.OutputStreamWriter) JsonWriter(com.google.gson.stream.JsonWriter) BufferedWriter(java.io.BufferedWriter)

Example 4 with JsonReader

use of com.google.gson.stream.JsonReader in project buck by facebook.

the class ChromeTraceParser method parse.

/**
   * Parses a Chrome trace and stops parsing once all of the specified matchers have been
   * satisfied. This method parses only one Chrome trace event at a time, which avoids loading the
   * entire trace into memory.
   * @param pathToTrace is a relative path [to the ProjectFilesystem] to a Chrome trace in the
   *     "JSON Array Format."
   * @param chromeTraceEventMatchers set of matchers this invocation of {@code parse()} is trying to
   *     satisfy. Once a matcher finds a match, it will not consider any other events in the trace.
   * @return a {@code Map} where every matcher that found a match will have an entry whose key is
   *     the matcher and whose value is the one returned by
   *     {@link ChromeTraceEventMatcher#test(JsonObject, String)} without the {@link Optional}
   *     wrapper.
   */
public Map<ChromeTraceEventMatcher<?>, Object> parse(Path pathToTrace, Set<ChromeTraceEventMatcher<?>> chromeTraceEventMatchers) throws IOException {
    Set<ChromeTraceEventMatcher<?>> unmatchedMatchers = new HashSet<>(chromeTraceEventMatchers);
    Preconditions.checkArgument(!unmatchedMatchers.isEmpty(), "Must specify at least one matcher");
    Map<ChromeTraceEventMatcher<?>, Object> results = new HashMap<>();
    try (InputStream input = projectFilesystem.newFileInputStream(pathToTrace);
        JsonReader jsonReader = new JsonReader(new InputStreamReader(input))) {
        jsonReader.beginArray();
        Gson gson = new Gson();
        featureSearch: while (true) {
            // If END_ARRAY is the next token, then there are no more elements in the array.
            if (jsonReader.peek().equals(JsonToken.END_ARRAY)) {
                break;
            }
            // Verify and extract the name property before invoking any of the matchers.
            JsonElement eventEl = gson.fromJson(jsonReader, JsonElement.class);
            JsonObject event = eventEl.getAsJsonObject();
            JsonElement nameEl = event.get("name");
            if (nameEl == null || !nameEl.isJsonPrimitive()) {
                continue;
            }
            String name = nameEl.getAsString();
            // Prefer Iterator to Iterable+foreach so we can use remove().
            for (Iterator<ChromeTraceEventMatcher<?>> iter = unmatchedMatchers.iterator(); iter.hasNext(); ) {
                ChromeTraceEventMatcher<?> chromeTraceEventMatcher = iter.next();
                Optional<?> result = chromeTraceEventMatcher.test(event, name);
                if (result.isPresent()) {
                    iter.remove();
                    results.put(chromeTraceEventMatcher, result.get());
                    if (unmatchedMatchers.isEmpty()) {
                        break featureSearch;
                    }
                }
            }
        }
    }
    // We could throw if !unmatchedMatchers.isEmpty(), but that might be overbearing.
    return results;
}
Also used : InputStreamReader(java.io.InputStreamReader) Optional(java.util.Optional) HashMap(java.util.HashMap) InputStream(java.io.InputStream) Gson(com.google.gson.Gson) JsonObject(com.google.gson.JsonObject) JsonElement(com.google.gson.JsonElement) Iterator(java.util.Iterator) JsonReader(com.google.gson.stream.JsonReader) JsonObject(com.google.gson.JsonObject) HashSet(java.util.HashSet)

Example 5 with JsonReader

use of com.google.gson.stream.JsonReader in project okhttp-OkGo by jeasonlzy.

the class NewsCallback method convertSuccess.

/**
     * 这里的数据解析是根据 http://apistore.baidu.com/apiworks/servicedetail/688.html 返回的数据来写的
     * 实际使用中,自己服务器返回的数据格式和上面网站肯定不一样,所以以下是参考代码,根据实际情况自己改写
     */
@Override
public T convertSuccess(Response response) throws Exception {
    //以下代码是通过泛型解析实际参数,泛型必须传
    Type genType = getClass().getGenericSuperclass();
    Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
    Type type = params[0];
    if (!(type instanceof ParameterizedType))
        throw new IllegalStateException("没有填写泛型参数");
    JsonReader jsonReader = new JsonReader(response.body().charStream());
    Type rawType = ((ParameterizedType) type).getRawType();
    if (rawType == NewsResponse.class) {
        NewsResponse newsResponse = Convert.fromJson(jsonReader, type);
        if (newsResponse.showapi_res_code == 0) {
            response.close();
            //noinspection unchecked
            return (T) newsResponse;
        } else {
            response.close();
            throw new IllegalStateException(newsResponse.showapi_res_error);
        }
    } else {
        response.close();
        throw new IllegalStateException("基类错误无法解析!");
    }
}
Also used : ParameterizedType(java.lang.reflect.ParameterizedType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) JsonReader(com.google.gson.stream.JsonReader) NewsResponse(com.lzy.demo.model.NewsResponse)

Aggregations

JsonReader (com.google.gson.stream.JsonReader)250 InputStreamReader (java.io.InputStreamReader)85 IOException (java.io.IOException)76 JsonElement (com.google.gson.JsonElement)67 StringReader (java.io.StringReader)58 JsonObject (com.google.gson.JsonObject)55 JsonParser (com.google.gson.JsonParser)54 Gson (com.google.gson.Gson)38 ArrayList (java.util.ArrayList)30 JsonWriter (com.google.gson.stream.JsonWriter)28 Test (org.junit.Test)28 Map (java.util.Map)23 JsonArray (com.google.gson.JsonArray)21 URL (java.net.URL)21 JsonParseException (com.google.gson.JsonParseException)19 FileReader (java.io.FileReader)19 HttpURLConnection (java.net.HttpURLConnection)19 File (java.io.File)16 InputStream (java.io.InputStream)16 TypeAdapter (com.google.gson.TypeAdapter)15