@SuppressWarnings("unchecked")
  @Override
  public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
    Type type = typeToken.getType();
    if (typeToken.getRawType() != ImmutableMap.class || !(type instanceof ParameterizedType)) {
      return null;
    }

    com.google.common.reflect.TypeToken<ImmutableMap<?, ?>> betterToken =
        (com.google.common.reflect.TypeToken<ImmutableMap<?, ?>>)
            com.google.common.reflect.TypeToken.of(typeToken.getType());
    final TypeAdapter<HashMap<?, ?>> hashMapAdapter =
        (TypeAdapter<HashMap<?, ?>>)
            gson.getAdapter(
                TypeToken.get(
                    betterToken.getSupertype(Map.class).getSubtype(HashMap.class).getType()));
    return new TypeAdapter<T>() {
      @Override
      public void write(JsonWriter out, T value) throws IOException {
        HashMap<?, ?> hashMap = Maps.newHashMap((Map<?, ?>) value);
        hashMapAdapter.write(out, hashMap);
      }

      @Override
      public T read(JsonReader in) throws IOException {
        HashMap<?, ?> hashMap = hashMapAdapter.read(in);
        return (T) ImmutableMap.copyOf(hashMap);
      }
    };
  }
 @Override
 protected void authenticate(IOperationMonitor monitor) throws IOException {
   UserCredentials credentials =
       getClient().getLocation().getCredentials(AuthenticationType.REPOSITORY);
   if (credentials == null) {
     throw new IllegalStateException("Authentication requested without valid credentials");
   }
   HttpRequestBase request =
       new HttpGet(
           baseUrl()
               + MessageFormat.format(
                   "/login?login={0}&password={1}",
                   new Object[] {credentials.getUserName(), credentials.getPassword()}));
   request.setHeader(CONTENT_TYPE, TEXT_XML_CHARSET_UTF_8);
   request.setHeader(ACCEPT, APPLICATION_JSON);
   HttpResponse response = getClient().execute(request, monitor);
   try {
     if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
       getClient().setAuthenticated(false);
       throw new AuthenticationException(
           "Authentication failed",
           new AuthenticationRequest<AuthenticationType<UserCredentials>>(
               getClient().getLocation(), AuthenticationType.REPOSITORY));
     } else {
       TypeToken<LoginToken> type = new TypeToken<LoginToken>() {};
       InputStream is = response.getEntity().getContent();
       InputStreamReader in = new InputStreamReader(is);
       LoginToken loginToken = new Gson().fromJson(in, type.getType());
       ((BugzillaRestHttpClient) getClient()).setLoginToken(loginToken);
       getClient().setAuthenticated(true);
     }
   } finally {
     HttpUtil.release(request, response, monitor);
   }
 }
 public TypeAdapter create(Gson gson, TypeToken typetoken)
 {
     typetoken = typetoken.getType();
     if (!(typetoken instanceof GenericArrayType) && (!(typetoken instanceof Class) || !((Class)typetoken).isArray()))
     {
         return null;
     } else
     {
         typetoken = com.google.gson.internal.yComponentType(typetoken);
         return new ArrayTypeAdapter(gson, gson.getAdapter(TypeToken.get(typetoken)), com.google.gson.internal.ype(typetoken));
     }
 }
Example #4
0
  private void addTypeAdaptersForDate(
      String datePattern, int dateStyle, int timeStyle, List<TypeAdapterFactory> factories) {
    DefaultDateTypeAdapter dateTypeAdapter;
    if (datePattern != null && !"".equals(datePattern.trim())) {
      dateTypeAdapter = new DefaultDateTypeAdapter(datePattern);
    } else if (dateStyle != DateFormat.DEFAULT && timeStyle != DateFormat.DEFAULT) {
      dateTypeAdapter = new DefaultDateTypeAdapter(dateStyle, timeStyle);
    } else {
      return;
    }

    factories.add(TreeTypeAdapter.newFactory(TypeToken.get(Date.class), dateTypeAdapter));
    factories.add(TreeTypeAdapter.newFactory(TypeToken.get(Timestamp.class), dateTypeAdapter));
    factories.add(TreeTypeAdapter.newFactory(TypeToken.get(java.sql.Date.class), dateTypeAdapter));
  }
  @Override
  public <T> TypeAdapter<T> create(Gson gson, final TypeToken<T> type) {
    if (type.getRawType().getAnnotation(RestModel.class) == null) {
      return null;
    }
    final TypeAdapter<T> defaultAdapter = gson.getDelegateAdapter(this, type);
    return new TypeAdapter<T>() {
      @Override
      public void write(JsonWriter out, T value) throws IOException {
        defaultAdapter.write(out, value);
      }

      @Override
      public T read(JsonReader in) throws IOException {
        T stub = defaultAdapter.read(in);
        if (stub == null) return null;

        for (Field field : ReflectionUtil.collectFields(type.getRawType())) {
          if (field.getAnnotation(Mandatory.class) != null) {
            try {
              field.setAccessible(true);
              if (field.get(stub) == null) {
                throw new JsonMandatoryException(
                    String.format(
                        "Field '%s' is mandatory, but missing in response", field.getName()));
              }
            } catch (IllegalAccessException e) {
              throw new RuntimeException(e);
            }
          }
        }
        return stub;
      }
    };
  }
Example #6
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);
   }
 }
  public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
    Type type = typeToken.getType();

    Class<? super T> rawType = typeToken.getRawType();
    if (!Collection.class.isAssignableFrom(rawType)) {
      return null;
    }

    Type elementType = $Gson$Types.getCollectionElementType(type, rawType);
    TypeAdapter<?> elementTypeAdapter = gson.getAdapter(TypeToken.get(elementType));
    ObjectConstructor<T> constructor = constructorConstructor.getConstructor(typeToken);

    @SuppressWarnings({"unchecked", "rawtypes"}) // create() doesn't define a type parameter
    TypeAdapter<T> result = new Adapter(gson, elementType, elementTypeAdapter, constructor);
    return result;
  }
Example #8
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);
   }
 }
Example #9
0
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {

      @SuppressWarnings("unchecked")
      Class<T> rawType = (Class<T>) type.getRawType();
      if (!rawType.isEnum()) {
        return null;
      }

      final Map<String, T> lowercaseToConstant = new HashMap<String, T>();
      for (T constant : rawType.getEnumConstants()) {
        lowercaseToConstant.put(toLowercase(constant), constant);
      }

      return new TypeAdapter<T>() {
        public void write(JsonWriter out, T value) throws IOException {
          if (value == null) {
            out.nullValue();
          } else {
            out.value(toLowercase(value));
          }
        }

        public T read(JsonReader reader) throws IOException {
          if (reader.peek() == JsonToken.NULL) {
            reader.nextNull();
            return null;
          } else {
            return lowercaseToConstant.get(reader.nextString());
          }
        }
      };
    }
    @Override
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
      if (!type.getRawType().equals(Broadcast.class)) {
        return null;
      }
      final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
      return new TypeAdapter<T>() {

        @Override
        public void write(JsonWriter out, T value) throws IOException {
          delegate.write(out, value);
        }

        @Override
        public T read(JsonReader in) throws IOException {
          T read = delegate.read(in);
          if (read instanceof Broadcast) {
            Broadcast broadcast = (Broadcast) read;
            if (broadcast.getChannel() != null && broadcast.getBroadcastOn() != null) {
              broadcast.getChannel().setUri(broadcast.getBroadcastOn());
            }
          }
          return read;
        }
      };
    }
 @SuppressWarnings("unchecked")
 public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> targetType) {
   JsonAdapter annotation = targetType.getRawType().getAnnotation(JsonAdapter.class);
   if (annotation == null) {
     return null;
   }
   return (TypeAdapter<T>) getTypeAdapter(constructorConstructor, gson, targetType, annotation);
 }
 @Test(
     expectedExceptions = IllegalArgumentException.class,
     expectedExceptionsMessageRegExp =
         ".* parameter 0 failed to be named by AnnotationBasedNamingStrategy requiring one of javax.inject.Named")
 public void testSerializedNameRequiredOnAllParameters() {
   parameterizedCtorFactory.create(
       gson, TypeToken.get(WithDeserializationConstructorButWithoutSerializedName.class));
 }
Example #13
0
 /** Preferencesから取得したJSONをListに変換して返す */
 public static <T> List<T> getList(Context context, String key, TypeToken typeToken) {
   String jsonString = getPreferences(context).getString(key, "");
   if (TextUtils.isEmpty(jsonString)) {
     return null;
   }
   List<T> list = new Gson().fromJson(jsonString, typeToken.getType());
   return list;
 }
 public void checkSimpleComposedObject() throws IOException {
   ValidatedConstructor x = new ValidatedConstructor(Optional.of(0), 1);
   ValidatedConstructor y = new ValidatedConstructor(Optional.of(1), 2);
   TypeAdapter<ComposedObjects> adapter =
       parameterizedCtorFactory.create(gson, TypeToken.get(ComposedObjects.class));
   assertEquals(
       new ComposedObjects(x, y),
       adapter.fromJson("{\"x\":{\"foo\":0,\"bar\":1},\"y\":{\"foo\":1,\"bar\":2}}"));
 }
Example #15
0
 /*
  * Enabled aggressive block sorting
  */
 private static boolean isAssignableFrom(Type class_, GenericArrayType genericArrayType) {
     void var1_4;
     Type type = genericArrayType.getGenericComponentType();
     if (!(type instanceof ParameterizedType)) return true;
     Class class_2 = class_;
     if (class_ instanceof GenericArrayType) {
         Type type2 = ((GenericArrayType)((Object)class_)).getGenericComponentType();
         return TypeToken.isAssignableFrom((Type)var1_4, (ParameterizedType)type, new HashMap<String, Type>());
     }
     if (!(class_ instanceof Class)) return TypeToken.isAssignableFrom((Type)var1_4, (ParameterizedType)type, new HashMap<String, Type>());
     do {
         if (!class_.isArray()) {
             Class class_3 = class_;
             return TypeToken.isAssignableFrom((Type)var1_4, (ParameterizedType)type, new HashMap<String, Type>());
         }
         class_ = class_.getComponentType();
     } while (true);
 }
Example #16
0
 /**
  * Configures Gson for custom serialization or deserialization. This method combines the
  * registration of an {@link TypeAdapter}, {@link InstanceCreator}, {@link JsonSerializer}, and a
  * {@link JsonDeserializer}. It is best used when a single object {@code typeAdapter} implements
  * all the required interfaces for custom serialization with Gson. If a type adapter was
  * previously registered for the specified {@code type}, it is overwritten.
  *
  * <p>This registers the type specified and no other types: you must manually register related
  * types! For example, applications registering {@code boolean.class} should also register {@code
  * Boolean.class}.
  *
  * @param type the type definition for the type adapter being registered
  * @param typeAdapter This object must implement at least one of the {@link TypeAdapter}, {@link
  *     InstanceCreator}, {@link JsonSerializer}, and a {@link JsonDeserializer} interfaces.
  * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
  */
 @SuppressWarnings({"unchecked", "rawtypes"})
 public GsonBuilder registerTypeAdapter(Type type, Object typeAdapter) {
   $Gson$Preconditions.checkArgument(
       typeAdapter instanceof JsonSerializer<?>
           || typeAdapter instanceof JsonDeserializer<?>
           || typeAdapter instanceof InstanceCreator<?>
           || typeAdapter instanceof TypeAdapter<?>);
   if (typeAdapter instanceof InstanceCreator<?>) {
     instanceCreators.put(type, (InstanceCreator) typeAdapter);
   }
   if (typeAdapter instanceof JsonSerializer<?> || typeAdapter instanceof JsonDeserializer<?>) {
     TypeToken<?> typeToken = TypeToken.get(type);
     factories.add(TreeTypeAdapter.newFactoryWithMatchRawType(typeToken, typeAdapter));
   }
   if (typeAdapter instanceof TypeAdapter<?>) {
     factories.add(TypeAdapters.newFactory(TypeToken.get(type), (TypeAdapter) typeAdapter));
   }
   return this;
 }
Example #17
0
 /*
  * Enabled force condition propagation
  * Lifted jumps to return sites
  */
 @Deprecated
 public boolean isAssignableFrom(Type type) {
     if (type == null) {
         return false;
     }
     if (this.type.equals(type)) {
         return true;
     }
     if (this.type instanceof Class) {
         return this.rawType.isAssignableFrom($Gson$Types.getRawType(type));
     }
     if (this.type instanceof ParameterizedType) {
         return TypeToken.isAssignableFrom(type, (ParameterizedType)this.type, new HashMap<String, Type>());
     }
     if (!(this.type instanceof GenericArrayType)) throw TypeToken.buildUnexpectedTypeError(this.type, Class.class, ParameterizedType.class, GenericArrayType.class);
     if (!this.rawType.isAssignableFrom($Gson$Types.getRawType(type))) return false;
     if (!TypeToken.isAssignableFrom(type, (GenericArrayType)this.type)) return false;
     return true;
 }
 @Override
 public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
   final Class<? super T> rawType = type.getRawType();
   if (rawType != null && LaDBFluteUtil.isClassificationType(rawType)) {
     @SuppressWarnings("unchecked")
     final TypeAdapter<T> pter = (TypeAdapter<T>) createTypeAdapterClassification(rawType);
     return pter;
   } else {
     return null;
   }
 }
  @Override
  public <T> TypeAdapter<T> create(Gson gson, final TypeToken<T> type) {
    Class<? super T> raw = type.getRawType();

    if (!Object.class.isAssignableFrom(raw)) {
      return null; // it's a primitive!
    }

    ObjectConstructor<T> constructor = constructorConstructor.get(type);
    return new Adapter<T>(constructor, getBoundFields(gson, type, raw));
  }
Example #20
0
  <T> T convertFromJsonToObjectOfType(String response, TypeToken<T> type) {
    try {

      return (T) gson.fromJson(response, type.getType());

    } catch (JsonParseException x) {
      log.warn("could not parse json", x);
    } catch (Exception x) {
      log.error("Unhandled exception!", x);
    }
    return null;
  }
Example #21
0
 /*
  * Enabled force condition propagation
  * Lifted jumps to return sites
  */
 private static boolean typeEquals(ParameterizedType arrtype, ParameterizedType arrtype2, Map<String, Type> map) {
     if (!arrtype.getRawType().equals(arrtype2.getRawType())) return false;
     arrtype = arrtype.getActualTypeArguments();
     arrtype2 = arrtype2.getActualTypeArguments();
     int n2 = 0;
     while (n2 < arrtype.length) {
         if (!TypeToken.matches(arrtype[n2], arrtype2[n2], map)) {
             return false;
         }
         ++n2;
     }
     return true;
 }
  public void testGenericParamsCopiedIn() throws IOException {
    TypeAdapter<GenericParamsCopiedIn> adapter =
        parameterizedCtorFactory.create(gson, TypeToken.get(GenericParamsCopiedIn.class));
    List<String> inputFoo = Lists.newArrayList();
    inputFoo.add("one");
    Map<String, String> inputBar = Maps.newHashMap();
    inputBar.put("2", "two");

    GenericParamsCopiedIn toTest =
        adapter.fromJson("{ \"foo\":[\"one\"], \"bar\":{ \"2\":\"two\"}}");
    assertEquals(inputFoo, toTest.foo);
    assertNotSame(inputFoo, toTest.foo);
    assertEquals(inputBar, toTest.bar);
  }
Example #23
0
 private static boolean isAssignableFrom(Type object, ParameterizedType parameterizedType, Map<String, Type> map) {
     int n2;
     if (object == null) {
         return false;
     }
     if (parameterizedType.equals(object)) {
         return true;
     }
     Class class_ = $Gson$Types.getRawType((Type)object);
     ParameterizedType parameterizedType2 = null;
     if (object instanceof ParameterizedType) {
         parameterizedType2 = (ParameterizedType)object;
     }
     if (parameterizedType2 != null) {
         Type[] arrtype = parameterizedType2.getActualTypeArguments();
         TypeVariable<Class<?>>[] arrtypeVariable = class_.getTypeParameters();
         for (n2 = 0; n2 < arrtype.length; ++n2) {
             object = arrtype[n2];
             TypeVariable typeVariable = arrtypeVariable[n2];
             while (object instanceof TypeVariable) {
                 object = map.get(((TypeVariable)object).getName());
             }
             map.put(typeVariable.getName(), (Type)object);
         }
         if (TypeToken.typeEquals(parameterizedType2, parameterizedType, map)) {
             return true;
         }
     }
     object = class_.getGenericInterfaces();
     int n3 = object.length;
     for (n2 = 0; n2 < n3; ++n2) {
         if (!TypeToken.isAssignableFrom(object[n2], parameterizedType, new HashMap<String, Type>(map))) continue;
         return true;
     }
     return TypeToken.isAssignableFrom(class_.getGenericSuperclass(), parameterizedType, new HashMap<String, Type>(map));
 }
  @SuppressWarnings("unchecked") // Casts guarded by conditionals.
  static TypeAdapter<?> getTypeAdapter(
      ConstructorConstructor constructorConstructor,
      Gson gson,
      TypeToken<?> fieldType,
      JsonAdapter annotation) {
    Class<?> value = annotation.value();
    if (TypeAdapter.class.isAssignableFrom(value)) {
      Class<TypeAdapter<?>> typeAdapter = (Class<TypeAdapter<?>>) value;
      return constructorConstructor.get(TypeToken.get(typeAdapter)).construct();
    }
    if (TypeAdapterFactory.class.isAssignableFrom(value)) {
      Class<TypeAdapterFactory> typeAdapterFactory = (Class<TypeAdapterFactory>) value;
      TypeAdapterFactory factory =
          constructorConstructor.get(TypeToken.get(typeAdapterFactory)).construct();
      synchronized (createdFactories) {
        createdFactories.add(factory);
      }
      return factory.create(gson, fieldType);
    }

    throw new IllegalArgumentException(
        "@JsonAdapter value must be TypeAdapter or TypeAdapterFactory reference.");
  }
 public static <T> T fromJson(String json, TypeToken<T> token, String datePattern) {
   if (TextUtils.isEmpty(json)) {
     return null;
   }
   GsonBuilder builder = new GsonBuilder();
   if (TextUtils.isEmpty(datePattern)) {
     datePattern = DEFAULT_DATE_PATTERN;
   }
   /* builder.registerTypeAdapter(Map.class, new HashMapDeserializer()); */
   Gson gson = builder.create();
   try {
     return gson.fromJson(json, token.getType());
   } catch (Exception ex) {
     return null;
   }
 }
  private ReflectiveTypeAdapterFactory.BoundField createBoundField(
      final Gson context,
      final Field field,
      final String name,
      final TypeToken<?> fieldType,
      boolean serialize,
      boolean deserialize) {
    final boolean isPrimitive = Primitives.isPrimitive(fieldType.getRawType());
    // special casing primitives here saves ~5% on Android...
    JsonAdapter annotation = field.getAnnotation(JsonAdapter.class);
    TypeAdapter<?> mapped = null;
    if (annotation != null) {
      mapped =
          jsonAdapterFactory.getTypeAdapter(constructorConstructor, context, fieldType, annotation);
    }
    final boolean jsonAdapterPresent = mapped != null;
    if (mapped == null) mapped = context.getAdapter(fieldType);

    final TypeAdapter<?> typeAdapter = mapped;
    return new ReflectiveTypeAdapterFactory.BoundField(name, serialize, deserialize) {
      @SuppressWarnings({"unchecked", "rawtypes"}) // the type adapter and field type always agree
      @Override
      void write(JsonWriter writer, Object value) throws IOException, IllegalAccessException {
        Object fieldValue = field.get(value);
        TypeAdapter t =
            jsonAdapterPresent
                ? typeAdapter
                : new TypeAdapterRuntimeTypeWrapper(context, typeAdapter, fieldType.getType());
        t.write(writer, fieldValue);
      }

      @Override
      void read(JsonReader reader, Object value) throws IOException, IllegalAccessException {
        Object fieldValue = typeAdapter.read(reader);
        if (fieldValue != null || !isPrimitive) {
          field.set(value, fieldValue);
        }
      }

      @Override
      public boolean writeField(Object value) throws IOException, IllegalAccessException {
        if (!serialized) return false;
        Object fieldValue = field.get(value);
        return fieldValue != value; // avoid recursion for example for Throwable.cause
      }
    };
  }
Example #27
0
  /**
   * 将给定的 {@code JSON} 字符串转换成指定的类型对象。
   *
   * @param <T> 要转换的目标类型。
   * @param json 给定的 {@code JSON} 字符串。
   * @param token {@code com.google.gson.reflect.TypeToken} 的类型指示类对象。
   * @param datePattern 日期格式模式。
   * @return 给定的 {@code JSON} 字符串表示的指定的类型对象。
   */
  public static <T> T fromJson(String json, TypeToken<T> token, String datePattern) {
    if (isEmpty(json)) {
      return null;
    }

    GsonBuilder builder = new GsonBuilder();
    if (isEmpty(datePattern)) {
      datePattern = DEFAULT_DATE_PATTERN;
    }

    Gson gson = builder.create();

    try {
      return gson.fromJson(json, token.getType());
    } catch (Exception ex) {
      return null;
    }
  }
Example #28
0
 /**
  * Writes the JSON representation of {@code src} of type {@code typeOfSrc} to {@code writer}.
  *
  * @throws JsonIOException if there was a problem writing to the writer
  */
 @SuppressWarnings("unchecked")
 public void toJson(Object src, Type typeOfSrc, JsonWriter writer) throws JsonIOException {
   TypeAdapter<?> adapter = getAdapter(TypeToken.get(typeOfSrc));
   boolean oldLenient = writer.isLenient();
   writer.setLenient(true);
   boolean oldHtmlSafe = writer.isHtmlSafe();
   writer.setHtmlSafe(htmlSafe);
   boolean oldSerializeNulls = writer.getSerializeNulls();
   writer.setSerializeNulls(serializeNulls);
   try {
     ((TypeAdapter<Object>) adapter).write(writer, src);
   } catch (IOException e) {
     throw new JsonIOException(e);
   } finally {
     writer.setLenient(oldLenient);
     writer.setHtmlSafe(oldHtmlSafe);
     writer.setSerializeNulls(oldSerializeNulls);
   }
 }
Example #29
0
        @SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal
        public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
          if (typeToken.getRawType() != Timestamp.class) {
            return null;
          }

          final TypeAdapter<Date> dateTypeAdapter = gson.getAdapter(Date.class);
          return (TypeAdapter<T>)
              new TypeAdapter<Timestamp>() {
                @Override
                public Timestamp read(JsonReader in) throws IOException {
                  Date date = dateTypeAdapter.read(in);
                  return date != null ? new Timestamp(date.getTime()) : null;
                }

                @Override
                public void write(JsonWriter out, Timestamp value) throws IOException {
                  dateTypeAdapter.write(out, value);
                }
              };
        }
Example #30
0
 public void toJson(Object obj, Type type, JsonWriter jsonWriter) throws JsonIOException {
   TypeAdapter adapter = getAdapter(TypeToken.get(type));
   boolean isLenient = jsonWriter.isLenient();
   jsonWriter.setLenient(true);
   boolean isHtmlSafe = jsonWriter.isHtmlSafe();
   jsonWriter.setHtmlSafe(this.htmlSafe);
   boolean serializeNulls = jsonWriter.getSerializeNulls();
   jsonWriter.setSerializeNulls(this.serializeNulls);
   try {
     adapter.write(jsonWriter, obj);
     jsonWriter.setLenient(isLenient);
     jsonWriter.setHtmlSafe(isHtmlSafe);
     jsonWriter.setSerializeNulls(serializeNulls);
   } catch (Throwable e) {
     throw new JsonIOException(e);
   } catch (Throwable th) {
     jsonWriter.setLenient(isLenient);
     jsonWriter.setHtmlSafe(isHtmlSafe);
     jsonWriter.setSerializeNulls(serializeNulls);
   }
 }