com.google.gson.internal.bind.TypeAdapters Java Examples

The following examples show how to use com.google.gson.internal.bind.TypeAdapters. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GsonBuilder.java    From framework with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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 #2
Source File: Gson.java    From gson with Apache License 2.0 6 votes vote down vote up
private TypeAdapter<Number> doubleAdapter(boolean serializeSpecialFloatingPointValues) {
  if (serializeSpecialFloatingPointValues) {
    return TypeAdapters.DOUBLE;
  }
  return new TypeAdapter<Number>() {
    @Override public Double read(JsonReader in) throws IOException {
      if (in.peek() == JsonToken.NULL) {
        in.nextNull();
        return null;
      }
      return in.nextDouble();
    }
    @Override public void write(JsonWriter out, Number value) throws IOException {
      if (value == null) {
        out.nullValue();
        return;
      }
      double doubleValue = value.doubleValue();
      checkValidFloatingPoint(doubleValue);
      out.value(value);
    }
  };
}
 
Example #3
Source File: Gson.java    From gson with Apache License 2.0 6 votes vote down vote up
private TypeAdapter<Number> floatAdapter(boolean serializeSpecialFloatingPointValues) {
  if (serializeSpecialFloatingPointValues) {
    return TypeAdapters.FLOAT;
  }
  return new TypeAdapter<Number>() {
    @Override public Float read(JsonReader in) throws IOException {
      if (in.peek() == JsonToken.NULL) {
        in.nextNull();
        return null;
      }
      return (float) in.nextDouble();
    }
    @Override public void write(JsonWriter out, Number value) throws IOException {
      if (value == null) {
        out.nullValue();
        return;
      }
      float floatValue = value.floatValue();
      checkValidFloatingPoint(floatValue);
      out.value(value);
    }
  };
}
 
Example #4
Source File: Gson.java    From gson with Apache License 2.0 6 votes vote down vote up
private static TypeAdapter<Number> longAdapter(LongSerializationPolicy longSerializationPolicy) {
  if (longSerializationPolicy == LongSerializationPolicy.DEFAULT) {
    return TypeAdapters.LONG;
  }
  return new TypeAdapter<Number>() {
    @Override public Number read(JsonReader in) throws IOException {
      if (in.peek() == JsonToken.NULL) {
        in.nextNull();
        return null;
      }
      return in.nextLong();
    }
    @Override public void write(JsonWriter out, Number value) throws IOException {
      if (value == null) {
        out.nullValue();
        return;
      }
      out.value(value.toString());
    }
  };
}
 
Example #5
Source File: GsonBuilder.java    From gson with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #6
Source File: GsonBuilder.java    From gson with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void addTypeAdaptersForDate(String datePattern, int dateStyle, int timeStyle,
    List<TypeAdapterFactory> factories) {
  DefaultDateTypeAdapter dateTypeAdapter;
  TypeAdapter<Timestamp> timestampTypeAdapter;
  TypeAdapter<java.sql.Date> javaSqlDateTypeAdapter;
  if (datePattern != null && !"".equals(datePattern.trim())) {
    dateTypeAdapter = new DefaultDateTypeAdapter(Date.class, datePattern);
    timestampTypeAdapter = (TypeAdapter) new DefaultDateTypeAdapter(Timestamp.class, datePattern);
    javaSqlDateTypeAdapter = (TypeAdapter) new DefaultDateTypeAdapter(java.sql.Date.class, datePattern);
  } else if (dateStyle != DateFormat.DEFAULT && timeStyle != DateFormat.DEFAULT) {
    dateTypeAdapter = new DefaultDateTypeAdapter(Date.class, dateStyle, timeStyle);
    timestampTypeAdapter = (TypeAdapter) new DefaultDateTypeAdapter(Timestamp.class, dateStyle, timeStyle);
    javaSqlDateTypeAdapter = (TypeAdapter) new DefaultDateTypeAdapter(java.sql.Date.class, dateStyle, timeStyle);
  } else {
    return;
  }

  factories.add(TypeAdapters.newFactory(Date.class, dateTypeAdapter));
  factories.add(TypeAdapters.newFactory(Timestamp.class, timestampTypeAdapter));
  factories.add(TypeAdapters.newFactory(java.sql.Date.class, javaSqlDateTypeAdapter));
}
 
Example #7
Source File: Gson.java    From framework with GNU Affero General Public License v3.0 6 votes vote down vote up
private TypeAdapter<Number> doubleAdapter(boolean serializeSpecialFloatingPointValues) {
  if (serializeSpecialFloatingPointValues) {
    return TypeAdapters.DOUBLE;
  }
  return new TypeAdapter<Number>() {
    @Override public Double read(JsonReader in) throws IOException {
      if (in.peek() == JsonToken.NULL) {
        in.nextNull();
        return null;
      }
      return in.nextDouble();
    }
    @Override public void write(JsonWriter out, Number value) throws IOException {
      if (value == null) {
        out.nullValue();
        return;
      }
      double doubleValue = value.doubleValue();
      checkValidFloatingPoint(doubleValue);
      out.value(value);
    }
  };
}
 
Example #8
Source File: Gson.java    From framework with GNU Affero General Public License v3.0 6 votes vote down vote up
private TypeAdapter<Number> floatAdapter(boolean serializeSpecialFloatingPointValues) {
  if (serializeSpecialFloatingPointValues) {
    return TypeAdapters.FLOAT;
  }
  return new TypeAdapter<Number>() {
    @Override public Float read(JsonReader in) throws IOException {
      if (in.peek() == JsonToken.NULL) {
        in.nextNull();
        return null;
      }
      return (float) in.nextDouble();
    }
    @Override public void write(JsonWriter out, Number value) throws IOException {
      if (value == null) {
        out.nullValue();
        return;
      }
      float floatValue = value.floatValue();
      checkValidFloatingPoint(floatValue);
      out.value(value);
    }
  };
}
 
Example #9
Source File: Gson.java    From framework with GNU Affero General Public License v3.0 6 votes vote down vote up
private TypeAdapter<Number> longAdapter(LongSerializationPolicy longSerializationPolicy) {
  if (longSerializationPolicy == LongSerializationPolicy.DEFAULT) {
    return TypeAdapters.LONG;
  }
  return new TypeAdapter<Number>() {
    @Override public Number read(JsonReader in) throws IOException {
      if (in.peek() == JsonToken.NULL) {
        in.nextNull();
        return null;
      }
      return in.nextLong();
    }
    @Override public void write(JsonWriter out, Number value) throws IOException {
      if (value == null) {
        out.nullValue();
        return;
      }
      out.value(value.toString());
    }
  };
}
 
Example #10
Source File: Streams.java    From letv with Apache License 2.0 6 votes vote down vote up
public static JsonElement parse(JsonReader reader) throws JsonParseException {
    boolean isEmpty = true;
    try {
        reader.peek();
        isEmpty = false;
        return (JsonElement) TypeAdapters.JSON_ELEMENT.read(reader);
    } catch (Throwable e) {
        if (isEmpty) {
            return JsonNull.INSTANCE;
        }
        throw new JsonIOException(e);
    } catch (Throwable e2) {
        throw new JsonSyntaxException(e2);
    } catch (Throwable e22) {
        throw new JsonIOException(e22);
    } catch (Throwable e222) {
        throw new JsonSyntaxException(e222);
    }
}
 
Example #11
Source File: GsonBuilder.java    From letv with Apache License 2.0 6 votes vote down vote up
public GsonBuilder registerTypeHierarchyAdapter(Class<?> baseType, Object typeAdapter) {
    boolean z;
    if ((typeAdapter instanceof JsonSerializer) || (typeAdapter instanceof JsonDeserializer) || (typeAdapter instanceof TypeAdapter)) {
        z = true;
    } else {
        z = false;
    }
    C$Gson$Preconditions.checkArgument(z);
    if ((typeAdapter instanceof JsonDeserializer) || (typeAdapter instanceof JsonSerializer)) {
        this.hierarchyFactories.add(0, TreeTypeAdapter.newTypeHierarchyFactory(baseType, typeAdapter));
    }
    if (typeAdapter instanceof TypeAdapter) {
        this.factories.add(TypeAdapters.newTypeHierarchyFactory(baseType, (TypeAdapter) typeAdapter));
    }
    return this;
}
 
Example #12
Source File: GsonBuilder.java    From letv with Apache License 2.0 6 votes vote down vote up
public GsonBuilder registerTypeAdapter(Type type, Object typeAdapter) {
    boolean z = (typeAdapter instanceof JsonSerializer) || (typeAdapter instanceof JsonDeserializer) || (typeAdapter instanceof InstanceCreator) || (typeAdapter instanceof TypeAdapter);
    C$Gson$Preconditions.checkArgument(z);
    if (Primitives.isPrimitive(type) || Primitives.isWrapperType(type)) {
        throw new IllegalArgumentException("Cannot register type adapters for " + type);
    }
    if (typeAdapter instanceof InstanceCreator) {
        this.instanceCreators.put(type, (InstanceCreator) typeAdapter);
    }
    if ((typeAdapter instanceof JsonSerializer) || (typeAdapter instanceof JsonDeserializer)) {
        this.factories.add(TreeTypeAdapter.newFactoryWithMatchRawType(TypeToken.get(type), typeAdapter));
    }
    if (typeAdapter instanceof TypeAdapter) {
        this.factories.add(TypeAdapters.newFactory(TypeToken.get(type), (TypeAdapter) typeAdapter));
    }
    return this;
}
 
Example #13
Source File: Gson.java    From letv with Apache License 2.0 6 votes vote down vote up
private TypeAdapter<Number> longAdapter(LongSerializationPolicy longSerializationPolicy) {
    if (longSerializationPolicy == LongSerializationPolicy.DEFAULT) {
        return TypeAdapters.LONG;
    }
    return new TypeAdapter<Number>() {
        public Number read(JsonReader in) throws IOException {
            if (in.peek() != JsonToken.NULL) {
                return Long.valueOf(in.nextLong());
            }
            in.nextNull();
            return null;
        }

        public void write(JsonWriter out, Number value) throws IOException {
            if (value == null) {
                out.nullValue();
            } else {
                out.value(value.toString());
            }
        }
    };
}
 
Example #14
Source File: Gson.java    From letv with Apache License 2.0 6 votes vote down vote up
private TypeAdapter<Number> floatAdapter(boolean serializeSpecialFloatingPointValues) {
    if (serializeSpecialFloatingPointValues) {
        return TypeAdapters.FLOAT;
    }
    return new TypeAdapter<Number>() {
        public Float read(JsonReader in) throws IOException {
            if (in.peek() != JsonToken.NULL) {
                return Float.valueOf((float) in.nextDouble());
            }
            in.nextNull();
            return null;
        }

        public void write(JsonWriter out, Number value) throws IOException {
            if (value == null) {
                out.nullValue();
                return;
            }
            Gson.this.checkValidFloatingPoint((double) value.floatValue());
            out.value(value);
        }
    };
}
 
Example #15
Source File: Gson.java    From letv with Apache License 2.0 6 votes vote down vote up
private TypeAdapter<Number> doubleAdapter(boolean serializeSpecialFloatingPointValues) {
    if (serializeSpecialFloatingPointValues) {
        return TypeAdapters.DOUBLE;
    }
    return new TypeAdapter<Number>() {
        public Double read(JsonReader in) throws IOException {
            if (in.peek() != JsonToken.NULL) {
                return Double.valueOf(in.nextDouble());
            }
            in.nextNull();
            return null;
        }

        public void write(JsonWriter out, Number value) throws IOException {
            if (value == null) {
                out.nullValue();
                return;
            }
            Gson.this.checkValidFloatingPoint(value.doubleValue());
            out.value(value);
        }
    };
}
 
Example #16
Source File: GsonBuilder.java    From framework with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Configures Gson for custom serialization or deserialization for an inheritance type hierarchy.
 * This method combines the registration of a {@link TypeAdapter}, {@link JsonSerializer} and
 * a {@link JsonDeserializer}. If a type adapter was previously registered for the specified
 * type hierarchy, it is overridden. If a type adapter is registered for a specific type in
 * the type hierarchy, it will be invoked instead of the one registered for the type hierarchy.
 *
 * @param baseType the class definition for the type adapter being registered for the base class
 *        or interface
 * @param typeAdapter This object must implement at least one of {@link TypeAdapter},
 *        {@link JsonSerializer} or {@link JsonDeserializer} interfaces.
 * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
 * @since 1.7
 */
@SuppressWarnings({"unchecked", "rawtypes"})
public GsonBuilder registerTypeHierarchyAdapter(Class<?> baseType, Object typeAdapter) {
  $Gson$Preconditions.checkArgument(typeAdapter instanceof JsonSerializer<?>
      || typeAdapter instanceof JsonDeserializer<?>
      || typeAdapter instanceof TypeAdapter<?>);
  if (typeAdapter instanceof JsonDeserializer || typeAdapter instanceof JsonSerializer) {
    hierarchyFactories.add(0,
        TreeTypeAdapter.newTypeHierarchyFactory(baseType, typeAdapter));
  }
  if (typeAdapter instanceof TypeAdapter<?>) {
    factories.add(TypeAdapters.newTypeHierarchyFactory(baseType, (TypeAdapter)typeAdapter));
  }
  return this;
}
 
Example #17
Source File: OptionalTypeAdapterFactory.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
private <A> TypeAdapter<Optional<A>> optionalAdapter(TypeAdapter<A> innerAdapter) {
    return new TypeAdapter<Optional<A>>() {
        @Override
        public Optional<A> read(JsonReader in) throws IOException {
            if (in.peek() == JsonToken.NULL) {
                in.nextNull();
                return Optional.empty();
            }
            else {
                JsonElement json = TypeAdapters.JSON_ELEMENT.read(in);
                try {
                    A value = innerAdapter.fromJsonTree(json);
                    return Optional.of(value);
                }
                catch (JsonSyntaxException e) {
                    /**
                     * Note : This is a workaround and it only exists because salt doesn't differentiate between a
                     * non-existent grain and a grain which exists but has value set to empty String.
                     *
                     * If an object is expected but instead empty string comes in then we return empty Optional.
                     */
                    if (json.isJsonPrimitive() && json.getAsJsonPrimitive().isString() &&
                            json.getAsString().isEmpty()) {
                        return Optional.empty();
                    }
                    throw e;
                }
            }
        }

        @Override
        public void write(JsonWriter out, Optional<A> optional) throws IOException {
            innerAdapter.write(out, optional.orElse(null));
        }
    };
}
 
Example #18
Source File: BsonReaderTest.java    From immutables with Apache License 2.0 5 votes vote down vote up
/**
 * Reading from BSON to GSON
 */
@Test
public void bsonToGson() throws Exception {
  BsonDocument document = new BsonDocument();
  document.append("boolean", new BsonBoolean(true));
  document.append("int32", new BsonInt32(32));
  document.append("int64", new BsonInt64(64));
  document.append("double", new BsonDouble(42.42D));
  document.append("string", new BsonString("foo"));
  document.append("null", new BsonNull());
  document.append("array", new BsonArray());
  document.append("object", new BsonDocument());

  JsonElement element = TypeAdapters.JSON_ELEMENT.read(new BsonReader(new BsonDocumentReader(document)));
  check(element.isJsonObject());

  check(element.getAsJsonObject().get("boolean").getAsJsonPrimitive().isBoolean());
  check(element.getAsJsonObject().get("boolean").getAsJsonPrimitive().getAsBoolean());

  check(element.getAsJsonObject().get("int32").getAsJsonPrimitive().isNumber());
  check(element.getAsJsonObject().get("int32").getAsJsonPrimitive().getAsNumber().intValue()).is(32);

  check(element.getAsJsonObject().get("int64").getAsJsonPrimitive().isNumber());
  check(element.getAsJsonObject().get("int64").getAsJsonPrimitive().getAsNumber().longValue()).is(64L);

  check(element.getAsJsonObject().get("double").getAsJsonPrimitive().isNumber());
  check(element.getAsJsonObject().get("double").getAsJsonPrimitive().getAsNumber().doubleValue()).is(42.42D);

  check(element.getAsJsonObject().get("string").getAsJsonPrimitive().isString());
  check(element.getAsJsonObject().get("string").getAsJsonPrimitive().getAsString()).is("foo");

  check(element.getAsJsonObject().get("null").isJsonNull());
  check(element.getAsJsonObject().get("array").isJsonArray());
  check(element.getAsJsonObject().get("object").isJsonObject());
}
 
Example #19
Source File: OptionalTypeAdapterFactory.java    From salt-netapi-client with MIT License 5 votes vote down vote up
private <A> TypeAdapter<Optional<A>> optionalAdapter(TypeAdapter<A> innerAdapter) {
    return new TypeAdapter<Optional<A>>() {
        @Override
        public Optional<A> read(JsonReader in) throws IOException {
            if (in.peek() == JsonToken.NULL) {
                in.nextNull();
                return Optional.empty();
            } else {
                JsonElement json = TypeAdapters.JSON_ELEMENT.read(in);
                try {
                    A value = innerAdapter.fromJsonTree(json);
                    return Optional.of(value);
                }
                catch (JsonSyntaxException e) {
                    /**
                     * Note : This is a workaround and it only exists because salt doesn't differentiate between a
                     * non-existent grain and a grain which exists but has value set to empty String.
                     *
                     * If an object is expected but instead empty string comes in then we return empty Optional.
                     */
                    if (json.isJsonPrimitive() && json.getAsJsonPrimitive().isString() &&
                            json.getAsString().isEmpty()) {
                        return Optional.empty();
                    }
                    throw e;
                }
            }
        }

        @Override
        public void write(JsonWriter out, Optional<A> optional) throws IOException {
            innerAdapter.write(out, optional.orElse(null));
        }
    };
}
 
Example #20
Source File: BsonReaderTest.java    From immutables with Apache License 2.0 5 votes vote down vote up
/**
 * Tests direct bson and gson mappings
 */
@Test
public void gsonToBson() throws Exception {
  JsonObject obj = new JsonObject();
  obj.addProperty("boolean", true);
  obj.addProperty("int32", 32);
  obj.addProperty("int64", 64L);
  obj.addProperty("double", 42.42D);
  obj.addProperty("string", "foo");
  obj.add("null", JsonNull.INSTANCE);
  obj.add("array", new JsonArray());
  obj.add("object", new JsonObject());


  BsonDocument doc = Jsons.toBson(obj);
  TypeAdapters.JSON_ELEMENT.write(new BsonWriter(new BsonDocumentWriter(doc)), obj);

  check(doc.keySet()).notEmpty();

  check(doc.get("boolean").getBsonType()).is(BsonType.BOOLEAN);
  check(doc.get("boolean").asBoolean());
  check(doc.get("int32").getBsonType()).is(BsonType.INT32);
  check(doc.get("int32").asInt32().getValue()).is(32);
  check(doc.get("int64").getBsonType()).is(BsonType.INT64);
  check(doc.get("int64").asInt64().getValue()).is(64L);
  check(doc.get("double").getBsonType()).is(BsonType.DOUBLE);
  check(doc.get("double").asDouble().getValue()).is(42.42D);
  check(doc.get("string").getBsonType()).is(BsonType.STRING);
  check(doc.get("string").asString().getValue()).is("foo");
  check(doc.get("null").getBsonType()).is(BsonType.NULL);
  check(doc.get("null").isNull());
  check(doc.get("array").getBsonType()).is(BsonType.ARRAY);
  check(doc.get("array").asArray()).isEmpty();
  check(doc.get("object").getBsonType()).is(BsonType.DOCUMENT);
  check(doc.get("object").asDocument().keySet()).isEmpty();
}
 
Example #21
Source File: Gson.java    From MiBandDecompiled with Apache License 2.0 5 votes vote down vote up
private TypeAdapter b(boolean flag)
{
    if (flag)
    {
        return TypeAdapters.FLOAT;
    } else
    {
        return new j(this);
    }
}
 
Example #22
Source File: Gson.java    From MiBandDecompiled with Apache License 2.0 5 votes vote down vote up
private TypeAdapter a(boolean flag)
{
    if (flag)
    {
        return TypeAdapters.DOUBLE;
    } else
    {
        return new i(this);
    }
}
 
Example #23
Source File: Gson.java    From MiBandDecompiled with Apache License 2.0 5 votes vote down vote up
private TypeAdapter a(LongSerializationPolicy longserializationpolicy)
{
    if (longserializationpolicy == LongSerializationPolicy.DEFAULT)
    {
        return TypeAdapters.LONG;
    } else
    {
        return new k(this);
    }
}
 
Example #24
Source File: JsonUnitTest.java    From EasyHttp with Apache License 2.0 5 votes vote down vote up
@Before
public void onTestBefore() {
    mGson = new GsonBuilder()
            .registerTypeAdapterFactory(TypeAdapters.newFactory(String.class, new StringTypeAdapter()))
            .registerTypeAdapterFactory(TypeAdapters.newFactory(boolean.class, Boolean.class, new BooleanTypeAdapter()))
            .registerTypeAdapterFactory(TypeAdapters.newFactory(int.class, Integer.class, new IntegerTypeAdapter()))
            .registerTypeAdapterFactory(TypeAdapters.newFactory(long.class, Long.class, new LongTypeAdapter()))
            .registerTypeAdapterFactory(TypeAdapters.newFactory(float.class, Float.class, new FloatTypeAdapter()))
            .registerTypeAdapterFactory(TypeAdapters.newFactory(double.class, Double.class, new DoubleTypeAdapter()))
            .registerTypeHierarchyAdapter(List.class, new ListTypeAdapter())
            .create();
}
 
Example #25
Source File: BooleanGsonAdaptable.java    From lastaflute with Apache License 2.0 4 votes vote down vote up
default TypeAdapterFactory createBooleanTypeAdapterFactory() {
    return TypeAdapters.newFactory(boolean.class, Boolean.class, createTypeAdapterBoolean());
}
 
Example #26
Source File: ExpectedSubtypesAdapter.java    From immutables with Apache License 2.0 4 votes vote down vote up
JsonReaderSupplier(JsonReader in) throws IOException {
  this.element = TypeAdapters.JSON_ELEMENT.read(in);
}
 
Example #27
Source File: Jsons.java    From immutables with Apache License 2.0 4 votes vote down vote up
static JsonObject toGson(BsonDocument bson) throws IOException {
  return TypeAdapters.JSON_ELEMENT.read(asGsonReader(bson)).getAsJsonObject();
}
 
Example #28
Source File: Jsons.java    From immutables with Apache License 2.0 4 votes vote down vote up
static org.bson.BsonReader asBsonReader(JsonObject gson) throws IOException {
  BasicOutputBuffer buffer = new BasicOutputBuffer();
  BsonWriter writer = new BsonWriter(new BsonBinaryWriter(buffer));
  TypeAdapters.JSON_ELEMENT.write(writer, gson);
  return new BsonBinaryReader(ByteBuffer.wrap(buffer.toByteArray()));
}
 
Example #29
Source File: BsonReaderTest.java    From immutables with Apache License 2.0 4 votes vote down vote up
private static void compare(String string) throws IOException {
  JsonElement bson = TypeAdapters.JSON_ELEMENT.read(new BsonReader(new JsonReader(string))); // compare as BSON
  JsonElement gson = TypeAdapters.JSON_ELEMENT.fromJson(string); // compare as JSON
  check(bson).is(gson); // compare the two
}
 
Example #30
Source File: Streams.java    From letv with Apache License 2.0 4 votes vote down vote up
public static void write(JsonElement element, JsonWriter writer) throws IOException {
    TypeAdapters.JSON_ELEMENT.write(writer, element);
}