Code example for JsonReader

Methods: isLenientpeeksetLenient

0
   * @throws JsonSyntaxException if json is not a valid representation for an object of type 
   * @since 1.2 
   */ 
  @SuppressWarnings("unchecked") 
  public <T> T fromJson(Reader json, Type typeOfT) throws JsonIOException, JsonSyntaxException {
    JsonReader jsonReader = new JsonReader(json);
    T object = (T) fromJson(jsonReader, typeOfT);
    assertFullConsumption(object, jsonReader);
    return object;
  } 
 
  private static void assertFullConsumption(Object obj, JsonReader reader) {
    try { 
      if (obj != null && reader.peek() != JsonToken.END_DOCUMENT) {
        throw new JsonIOException("JSON document was not fully consumed.");
      } 
    } catch (MalformedJsonException e) {
      throw new JsonSyntaxException(e);
    } catch (IOException e) {
      throw new JsonIOException(e);
    } 
  } 
 
  /** 
   * 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);
    } 
  } 
 
  /** 
   * This method deserializes the Json read from the specified parse tree into an object of the