Esempio n. 1
0
 /**
  * Reads the next JSON value from {@code reader} and convert it to an object of type {@code
  * typeOfT}. Since Type is not parameterized by T, this method is type unsafe and should be used
  * carefully
  *
  * @throws JsonIOException if there was a problem writing to the Reader
  * @throws JsonSyntaxException if json is not a valid representation for an object of type
  */
 @SuppressWarnings("unchecked")
 public <T> T fromJson(JsonReader reader, Type typeOfT)
     throws JsonIOException, JsonSyntaxException {
   boolean isEmpty = true;
   boolean oldLenient = reader.isLenient();
   reader.setLenient(true);
   try {
     reader.peek();
     isEmpty = false;
     TypeToken<T> typeToken = (TypeToken<T>) TypeToken.get(typeOfT);
     TypeAdapter<T> typeAdapter = getAdapter(typeToken);
     T object = typeAdapter.read(reader);
     return object;
   } catch (EOFException e) {
     /*
      * For compatibility with JSON 1.5 and earlier, we return null for empty
      * documents instead of throwing.
      */
     if (isEmpty) {
       return null;
     }
     throw new JsonSyntaxException(e);
   } catch (IllegalStateException e) {
     throw new JsonSyntaxException(e);
   } catch (IOException e) {
     // TODO(inder): Figure out whether it is indeed right to rethrow this as JsonSyntaxException
     throw new JsonSyntaxException(e);
   } finally {
     reader.setLenient(oldLenient);
   }
 }
Esempio n. 2
0
 public <T> T fromJson(JsonReader jsonReader, Type type)
     throws JsonIOException, JsonSyntaxException {
   boolean z = true;
   boolean isLenient = jsonReader.isLenient();
   jsonReader.setLenient(true);
   try {
     jsonReader.peek();
     z = DEFAULT_JSON_NON_EXECUTABLE;
     T read = getAdapter(TypeToken.get(type)).read(jsonReader);
     jsonReader.setLenient(isLenient);
     return read;
   } catch (Throwable e) {
     if (z) {
       jsonReader.setLenient(isLenient);
       return null;
     }
     throw new JsonSyntaxException(e);
   } catch (Throwable e2) {
     throw new JsonSyntaxException(e2);
   } catch (Throwable e22) {
     throw new JsonSyntaxException(e22);
   } catch (Throwable th) {
     jsonReader.setLenient(isLenient);
   }
 }
  @Override
  public void onMessage(byte[] data) {

    try {

      String message = new String(data, "UTF8");

      JsonReader reader = new JsonReader(new StringReader(message));
      reader.setLenient(true);

      // pretty print use this
      Gson gson = new GsonBuilder().setPrettyPrinting().create();

      // normal print, use this
      // Gson gson = new Gson();

      HeartbeatMessage hbm = gson.fromJson(reader, HeartbeatMessage.class);

      String jsonOutput = gson.toJson(hbm);

      logger.info("received heart beat: " + jsonOutput);

    } catch (Exception e) {
      logger.log(Level.WARNING, e.getMessage(), e);
    }
  }
  /**
   * import JSON as a new note.
   *
   * @param sourceJson - the note JSON to import
   * @param noteName - the name of the new note
   * @return notebook 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);
      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);
      }

      newNote.persist(subject);
    } catch (IOException e) {
      logger.error(e.toString(), e);
      throw e;
    }

    return newNote;
  }
Esempio n. 5
0
 public JsonElement parse(JsonReader jsonreader)
     throws JsonIOException, JsonSyntaxException
 {
     boolean flag;
     flag = jsonreader.isLenient();
     jsonreader.setLenient(true);
     JsonElement jsonelement = Streams.parse(jsonreader);
     jsonreader.setLenient(flag);
     return jsonelement;
     Object obj;
     obj;
     throw new JsonParseException((new StringBuilder()).append("Failed parsing JSON source: ").append(jsonreader).append(" to Json").toString(), ((Throwable) (obj)));
     obj;
     jsonreader.setLenient(flag);
     throw obj;
     obj;
     throw new JsonParseException((new StringBuilder()).append("Failed parsing JSON source: ").append(jsonreader).append(" to Json").toString(), ((Throwable) (obj)));
 }
Esempio n. 6
0
 /**
  * Converts {@code jsonTree} to a Java object.
  *
  * @param jsonTree the Java object to convert. May be {@link JsonNull}.
  */
 /*public*/ final T fromJsonTree(JsonElement jsonTree) {
   try {
     JsonReader jsonReader = new JsonTreeReader(jsonTree);
     jsonReader.setLenient(true);
     return read(jsonReader);
   } catch (IOException e) {
     throw new JsonIOException(e);
   }
 }
Esempio n. 7
0
 protected void loadModel(InputStream model_stream) throws Exception {
   Gson gson = new Gson();
   labelMap = new HashMap<String, Integer>();
   JsonReader br = new JsonReader(new InputStreamReader(model_stream));
   br.setLenient(true);
   model = gson.fromJson(br, Model.class);
   for (int i = 0; i < model.labels.size(); i++) {
     labelMap.put(model.labels.get(i), i);
   }
 }
  private void parseInfo(String response) {

    if (DEBUG) {
      Log.v(LOG_TAG, "parseInfo(): "); // + response);
    }
    SiteItemList = new ArrayList<SiteItem>();
    // to remove the "XXXX" characters
    try {
      String jsonResponse = response.substring(4, response.length() - 3);
      Log.i("JSONSTRING", jsonResponse);
      JsonReader reader = new JsonReader(new StringReader(jsonResponse));
      reader.setLenient(true);
      Type type = new TypeToken<ArrayList<JsonObject>>() {}.getType();
      ArrayList<JsonObject> jsonObjs = new Gson().fromJson(reader, type);

      // store the parsed data to an array list
      for (JsonObject jsonObj : jsonObjs) {
        SiteItemList.add(new Gson().fromJson(jsonObj, SiteItem.class));
      }

      // 拿到数据库的ID,与网络获取的数据进行判断
      i = ++i;
      if (i == 1) {
        for (int i = 0; i < mSiteItemList.size(); i++) {
          String id = mSiteItemList.get(i).getSiteID();
          loginid = mSiteItemList.get(i).getLoginID(); // 数据库的loginID
          loginID = preferences.getString("LoginID", null); // 登录的loginID
          if (loginid.equals(loginID)) {
            for (int j = 0; j < SiteItemList.size(); j++) {
              String siteID = SiteItemList.get(j).getSiteID();
              if (id.equals(siteID)) {
                siteItem =
                    new SiteItem(
                        siteID,
                        SiteItemList.get(j).getSiteName(),
                        SiteItemList.get(j).getAlarmNum(),
                        SiteItemList.get(j).getSeverity());
                mSiteItemLists.add(siteItem);
              }
            }
          }
        }

        mAdapter =
            new BookMarkAdapter(
                getActivity(), R.layout.list_item_site, mSiteItemLists, mFragmentManager);
        setListAdapter(mAdapter);
        // 拿到数据库的数据进行长度判断
        judgeFromDatabase();
      }
    } catch (Exception e) {
      // TODO: handle exception
    }
  }
Esempio n. 9
0
 public Command[] getCommands() {
   if (_cmds == null) {
     try {
       StringReader reader = new StringReader(_content);
       JsonReader jsonReader = new JsonReader(reader);
       jsonReader.setLenient(true);
       _cmds = s_gson.fromJson(jsonReader, (Type) Command[].class);
     } catch (RuntimeException e) {
       s_logger.error("Caught problem with " + _content, e);
       throw e;
     }
   }
   return _cmds;
 }
 private static JsonElement parse(File file) {
   try {
     InputStream stream = new FileInputStream(file);
     try {
       Reader fileReader = new InputStreamReader(stream, Charsets.UTF_8);
       JsonReader jsonReader = new JsonReader(fileReader);
       jsonReader.setLenient(true);
       return Streams.parse(jsonReader);
     } finally {
       stream.close();
     }
   } catch (IOException e) {
     throw Throwables.propagate(e);
   }
 }
  public JsonSchemaObject read(
      @NotNull final Reader reader, @Nullable JsonSchemaExportedDefinitions definitions)
      throws IOException {
    final JsonReader in = new JsonReader(reader);
    in.setLenient(true);

    in.beginObject();
    final JsonSchemaObject object = new JsonSchemaObject();
    final JsonSchemaGeneralObjectTypeAdapter adapter = new JsonSchemaGeneralObjectTypeAdapter();

    while (in.peek() == JsonToken.NAME) {
      final String name = in.nextName();
      adapter.readSomeProperty(in, name, object);
    }

    processReferences(object, adapter.getAllObjects(), definitions);
    final ArrayList<JsonSchemaObject> withoutDefinitions = new ArrayList<>(adapter.getAllObjects());
    removeDefinitions(object, withoutDefinitions);
    return object;
  }
Esempio n. 12
0
 /**
  * Converts the JSON document in {@code in} to a Java object. Unlike Gson's similar {@link
  * Gson#fromJson(Reader, Class) fromJson} method, this read is strict. Create a {@link
  * JsonReader#setLenient(boolean) lenient} {@code JsonReader} and call {@link #read(JsonReader)}
  * for lenient reading.
  *
  * @return the converted Java object. May be null.
  */
 /*public*/ final T fromJson(Reader in) throws IOException {
   JsonReader reader = new JsonReader(in);
   reader.setLenient(true); // TODO: non-lenient?
   return read(reader);
 }