Search in sources :

Example 1 with TypeAdapter

use of com.google.gson.TypeAdapter 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 TypeAdapter

use of com.google.gson.TypeAdapter in project smarthome by eclipse.

the class PropertiesTypeAdapterFactory method create.

@SuppressWarnings({ "unused", "unchecked" })
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
    Type type = typeToken.getType();
    Class<? super T> rawType = typeToken.getRawType();
    if (!PropertiesTypeAdapter.TOKEN.equals(typeToken)) {
        return null;
    }
    return (TypeAdapter<T>) new PropertiesTypeAdapter(gson);
}
Also used : Type(java.lang.reflect.Type) TypeAdapter(com.google.gson.TypeAdapter)

Example 3 with TypeAdapter

use of com.google.gson.TypeAdapter in project LanternServer by LanternPowered.

the class ObjectTypeAdapterFactory method create.

@Nullable
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    if (!type.isAssignableFrom(this.typeToken)) {
        return null;
    }
    final TypeAdapter<JsonElement> jsonElementTypeAdapter = gson.getAdapter(JsonElement.class);
    final TypeToken theTypeToken = type;
    return new TypeAdapter<T>() {

        @SuppressWarnings("unchecked")
        @Override
        public void write(JsonWriter out, T value) throws IOException {
            final JsonElement element = serialize((TypeToken<V>) theTypeToken, (V) value, gson);
            jsonElementTypeAdapter.write(out, element);
        }

        @SuppressWarnings("unchecked")
        @Override
        public T read(JsonReader in) throws IOException {
            final JsonElement element = jsonElementTypeAdapter.read(in);
            return (T) deserialize(theTypeToken, element, gson);
        }
    };
}
Also used : JsonElement(com.google.gson.JsonElement) TypeToken(com.google.gson.reflect.TypeToken) TypeAdapter(com.google.gson.TypeAdapter) JsonReader(com.google.gson.stream.JsonReader) JsonWriter(com.google.gson.stream.JsonWriter) Nullable(javax.annotation.Nullable)

Example 4 with TypeAdapter

use of com.google.gson.TypeAdapter in project runelite by runelite.

the class RuntimeTypeAdapterFactory method create.

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (type.getRawType() != baseType) {
        return null;
    }
    final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<String, TypeAdapter<?>>();
    final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<Class<?>, TypeAdapter<?>>();
    for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
        TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue()));
        labelToDelegate.put(entry.getKey(), delegate);
        subtypeToDelegate.put(entry.getValue(), delegate);
    }
    return new TypeAdapter<R>() {

        @Override
        public R read(JsonReader in) throws IOException {
            JsonElement jsonElement = Streams.parse(in);
            JsonElement labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName);
            if (labelJsonElement == null) {
                throw new JsonParseException("cannot deserialize " + baseType + " because it does not define a field named " + typeFieldName);
            }
            String label = labelJsonElement.getAsString();
            // registration requires that subtype extends T
            @SuppressWarnings("unchecked") TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label);
            if (delegate == null) {
                throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label + "; did you forget to register a subtype?");
            }
            return delegate.fromJsonTree(jsonElement);
        }

        @Override
        public void write(JsonWriter out, R value) throws IOException {
            Class<?> srcType = value.getClass();
            String label = subtypeToLabel.get(srcType);
            // registration requires that subtype extends T
            @SuppressWarnings("unchecked") TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType);
            if (delegate == null) {
                throw new JsonParseException("cannot serialize " + srcType.getName() + "; did you forget to register a subtype?");
            }
            JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject();
            if (jsonObject.has(typeFieldName)) {
                throw new JsonParseException("cannot serialize " + srcType.getName() + " because it already defines a field named " + typeFieldName);
            }
            JsonObject clone = new JsonObject();
            clone.add(typeFieldName, new JsonPrimitive(label));
            for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
                clone.add(e.getKey(), e.getValue());
            }
            Streams.write(clone, out);
        }
    }.nullSafe();
}
Also used : JsonPrimitive(com.google.gson.JsonPrimitive) JsonObject(com.google.gson.JsonObject) IOException(java.io.IOException) JsonParseException(com.google.gson.JsonParseException) JsonWriter(com.google.gson.stream.JsonWriter) LinkedHashMap(java.util.LinkedHashMap) JsonElement(com.google.gson.JsonElement) TypeAdapter(com.google.gson.TypeAdapter) JsonReader(com.google.gson.stream.JsonReader) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 5 with TypeAdapter

use of com.google.gson.TypeAdapter in project BuildCraft by BuildCraft.

the class JsonUtil method registerNbtSerializersDeserializers.

public static GsonBuilder registerNbtSerializersDeserializers(GsonBuilder gsonBuilder) {
    return gsonBuilder.registerTypeAdapterFactory(new TypeAdapterFactory() {

        @Override
        public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
            return type.getRawType() == NBTBase.class ? new TypeAdapter<T>() {

                @Override
                public void write(JsonWriter out, T value) throws IOException {
                    // noinspection unchecked, RedundantCast
                    Streams.write(((JsonSerializer<T>) (JsonSerializer<NBTBase>) (src, typeOfSrc, context) -> {
                        if (src == NBTUtilBC.NBT_NULL) {
                            return JsonNull.INSTANCE;
                        }
                        switch(src.getId()) {
                            case Constants.NBT.TAG_BYTE:
                                return context.serialize(src, NBTTagByte.class);
                            case Constants.NBT.TAG_SHORT:
                                return context.serialize(src, NBTTagShort.class);
                            case Constants.NBT.TAG_INT:
                                return context.serialize(src, NBTTagInt.class);
                            case Constants.NBT.TAG_LONG:
                                return context.serialize(src, NBTTagLong.class);
                            case Constants.NBT.TAG_FLOAT:
                                return context.serialize(src, NBTTagFloat.class);
                            case Constants.NBT.TAG_DOUBLE:
                                return context.serialize(src, NBTTagDouble.class);
                            case Constants.NBT.TAG_BYTE_ARRAY:
                                return context.serialize(src, NBTTagByteArray.class);
                            case Constants.NBT.TAG_STRING:
                                return context.serialize(src, NBTTagString.class);
                            case Constants.NBT.TAG_LIST:
                                return context.serialize(src, NBTTagList.class);
                            case Constants.NBT.TAG_COMPOUND:
                                return context.serialize(src, NBTTagCompound.class);
                            case Constants.NBT.TAG_INT_ARRAY:
                                return context.serialize(src, NBTTagIntArray.class);
                            default:
                                throw new IllegalArgumentException(src.toString());
                        }
                    }).serialize(value, type.getType(), new JsonSerializationContext() {

                        @Override
                        public JsonElement serialize(Object src) {
                            return gson.toJsonTree(src);
                        }

                        @Override
                        public JsonElement serialize(Object src, Type typeOfSrc) {
                            return gson.toJsonTree(src, typeOfSrc);
                        }
                    }), out);
                }

                @Override
                public T read(JsonReader in) throws IOException {
                    return ((JsonDeserializer<T>) (json, typeOfT, context) -> {
                        if (json.isJsonNull()) {
                            // noinspection unchecked
                            return (T) NBTUtilBC.NBT_NULL;
                        }
                        if (json.isJsonPrimitive() && json.getAsJsonPrimitive().isNumber()) {
                            Number number = json.getAsJsonPrimitive().getAsNumber();
                            if (number instanceof BigInteger || number instanceof Long || number instanceof Integer || number instanceof Short || number instanceof Byte) {
                                return context.deserialize(json, NBTTagLong.class);
                            } else {
                                return context.deserialize(json, NBTTagDouble.class);
                            }
                        }
                        if (json.isJsonPrimitive() && json.getAsJsonPrimitive().isBoolean()) {
                            return context.deserialize(new JsonPrimitive(json.getAsJsonPrimitive().getAsBoolean() ? (byte) 1 : (byte) 0), NBTTagByte.class);
                        }
                        if (json.isJsonPrimitive() && json.getAsJsonPrimitive().isString()) {
                            return context.deserialize(json, NBTTagString.class);
                        }
                        if (json.isJsonArray()) {
                            return context.deserialize(json, NBTTagList.class);
                        }
                        if (json.isJsonObject()) {
                            return context.deserialize(json, NBTTagCompound.class);
                        }
                        throw new IllegalArgumentException(json.toString());
                    }).deserialize(Streams.parse(in), type.getType(), gson::fromJson);
                }
            } : null;
        }
    }).registerTypeAdapter(NBTTagByte.class, (JsonSerializer<NBTTagByte>) (src, typeOfSrc, context) -> new JsonPrimitive(src.getByte())).registerTypeAdapter(NBTTagByte.class, (JsonDeserializer<NBTTagByte>) (json, typeOfT, context) -> new NBTTagByte(json.getAsJsonPrimitive().getAsByte())).registerTypeAdapter(NBTTagShort.class, (JsonSerializer<NBTTagShort>) (src, typeOfSrc, context) -> new JsonPrimitive(src.getShort())).registerTypeAdapter(NBTTagShort.class, (JsonDeserializer<NBTTagShort>) (json, typeOfT, context) -> new NBTTagShort(json.getAsJsonPrimitive().getAsShort())).registerTypeAdapter(NBTTagInt.class, (JsonSerializer<NBTTagInt>) (src, typeOfSrc, context) -> new JsonPrimitive(src.getInt())).registerTypeAdapter(NBTTagInt.class, (JsonDeserializer<NBTTagInt>) (json, typeOfT, context) -> new NBTTagInt(json.getAsJsonPrimitive().getAsInt())).registerTypeAdapter(NBTTagLong.class, (JsonSerializer<NBTTagLong>) (src, typeOfSrc, context) -> new JsonPrimitive(src.getLong())).registerTypeAdapter(NBTTagLong.class, (JsonDeserializer<NBTTagLong>) (json, typeOfT, context) -> new NBTTagLong(json.getAsJsonPrimitive().getAsLong())).registerTypeAdapter(NBTTagFloat.class, (JsonSerializer<NBTTagFloat>) (src, typeOfSrc, context) -> new JsonPrimitive(src.getFloat())).registerTypeAdapter(NBTTagFloat.class, (JsonDeserializer<NBTTagFloat>) (json, typeOfT, context) -> new NBTTagFloat(json.getAsJsonPrimitive().getAsFloat())).registerTypeAdapter(NBTTagDouble.class, (JsonSerializer<NBTTagDouble>) (src, typeOfSrc, context) -> new JsonPrimitive(src.getDouble())).registerTypeAdapter(NBTTagDouble.class, (JsonDeserializer<NBTTagDouble>) (json, typeOfT, context) -> new NBTTagDouble(json.getAsJsonPrimitive().getAsDouble())).registerTypeAdapter(NBTTagByteArray.class, (JsonSerializer<NBTTagByteArray>) (src, typeOfSrc, context) -> {
        JsonArray jsonArray = new JsonArray();
        for (byte element : src.getByteArray()) {
            jsonArray.add(new JsonPrimitive(element));
        }
        return jsonArray;
    }).registerTypeAdapter(NBTTagByteArray.class, (JsonDeserializer<NBTTagByteArray>) (json, typeOfT, context) -> new NBTTagByteArray(ArrayUtils.toPrimitive(StreamSupport.stream(json.getAsJsonArray().spliterator(), false).map(JsonElement::getAsByte).toArray(Byte[]::new)))).registerTypeAdapter(NBTTagString.class, (JsonSerializer<NBTTagString>) (src, typeOfSrc, context) -> new JsonPrimitive(src.getString())).registerTypeAdapter(NBTTagString.class, (JsonDeserializer<NBTTagString>) (json, typeOfT, context) -> new NBTTagString(json.getAsJsonPrimitive().getAsString())).registerTypeAdapter(NBTTagList.class, (JsonSerializer<NBTTagList>) (src, typeOfSrc, context) -> {
        JsonArray jsonArray = new JsonArray();
        for (int i = 0; i < src.tagCount(); i++) {
            NBTBase element = src.get(i);
            jsonArray.add(context.serialize(element, NBTBase.class));
        }
        return jsonArray;
    }).registerTypeAdapter(NBTTagList.class, (JsonDeserializer<NBTTagList>) (json, typeOfT, context) -> {
        NBTTagList nbtTagList = new NBTTagList();
        StreamSupport.stream(json.getAsJsonArray().spliterator(), false).map(element -> context.<NBTBase>deserialize(element, NBTBase.class)).forEach(nbtTagList::appendTag);
        return nbtTagList;
    }).registerTypeAdapter(NBTTagCompound.class, (JsonSerializer<NBTTagCompound>) (src, typeOfSrc, context) -> {
        JsonObject jsonObject = new JsonObject();
        for (String key : src.getKeySet()) {
            jsonObject.add(key, context.serialize(src.getTag(key), NBTBase.class));
        }
        return jsonObject;
    }).registerTypeAdapter(NBTTagCompound.class, (JsonDeserializer<NBTTagCompound>) (json, typeOfT, context) -> {
        NBTTagCompound nbtTagCompound = new NBTTagCompound();
        for (Map.Entry<String, JsonElement> entry : json.getAsJsonObject().entrySet()) {
            nbtTagCompound.setTag(entry.getKey(), context.deserialize(entry.getValue(), NBTBase.class));
        }
        return nbtTagCompound;
    }).registerTypeAdapter(NBTTagIntArray.class, (JsonSerializer<NBTTagIntArray>) (src, typeOfSrc, context) -> {
        JsonArray jsonArray = new JsonArray();
        for (int element : src.getIntArray()) {
            jsonArray.add(new JsonPrimitive(element));
        }
        return jsonArray;
    }).registerTypeAdapter(NBTTagIntArray.class, (JsonDeserializer<NBTTagIntArray>) (json, typeOfT, context) -> new NBTTagIntArray(StreamSupport.stream(json.getAsJsonArray().spliterator(), false).mapToInt(JsonElement::getAsByte).toArray()));
}
Also used : JsonObject(com.google.gson.JsonObject) TypeToken(com.google.gson.reflect.TypeToken) NBTTagByte(net.minecraft.nbt.NBTTagByte) NBTTagByteArray(net.minecraft.nbt.NBTTagByteArray) Constants(net.minecraftforge.common.util.Constants) HashMap(java.util.HashMap) JsonSerializer(com.google.gson.JsonSerializer) ArrayUtils(org.apache.commons.lang3.ArrayUtils) NBTTagString(net.minecraft.nbt.NBTTagString) GsonBuilder(com.google.gson.GsonBuilder) TypeAdapter(com.google.gson.TypeAdapter) JsonReader(com.google.gson.stream.JsonReader) NBTTagFloat(net.minecraft.nbt.NBTTagFloat) ArrayList(java.util.ArrayList) JsonElement(com.google.gson.JsonElement) NBTTagList(net.minecraft.nbt.NBTTagList) ImmutableList(com.google.common.collect.ImmutableList) Gson(com.google.gson.Gson) Map(java.util.Map) JsonSerializationContext(com.google.gson.JsonSerializationContext) BigInteger(java.math.BigInteger) StreamSupport(java.util.stream.StreamSupport) JsonPrimitive(com.google.gson.JsonPrimitive) JsonWriter(com.google.gson.stream.JsonWriter) NBTTagCompound(net.minecraft.nbt.NBTTagCompound) NBTTagInt(net.minecraft.nbt.NBTTagInt) NBTTagDouble(net.minecraft.nbt.NBTTagDouble) NBTTagShort(net.minecraft.nbt.NBTTagShort) Streams(com.google.gson.internal.Streams) ImmutableMap(com.google.common.collect.ImmutableMap) JsonSyntaxException(com.google.gson.JsonSyntaxException) NBTBase(net.minecraft.nbt.NBTBase) NBTTagIntArray(net.minecraft.nbt.NBTTagIntArray) IOException(java.io.IOException) JsonArray(com.google.gson.JsonArray) Type(java.lang.reflect.Type) JsonNull(com.google.gson.JsonNull) Entry(java.util.Map.Entry) JsonDeserializer(com.google.gson.JsonDeserializer) NBTTagLong(net.minecraft.nbt.NBTTagLong) TypeAdapterFactory(com.google.gson.TypeAdapterFactory) JsonPrimitive(com.google.gson.JsonPrimitive) NBTTagByte(net.minecraft.nbt.NBTTagByte) NBTTagCompound(net.minecraft.nbt.NBTTagCompound) Gson(com.google.gson.Gson) JsonObject(com.google.gson.JsonObject) JsonSerializer(com.google.gson.JsonSerializer) NBTTagString(net.minecraft.nbt.NBTTagString) JsonDeserializer(com.google.gson.JsonDeserializer) NBTTagIntArray(net.minecraft.nbt.NBTTagIntArray) NBTTagList(net.minecraft.nbt.NBTTagList) Entry(java.util.Map.Entry) NBTBase(net.minecraft.nbt.NBTBase) JsonReader(com.google.gson.stream.JsonReader) NBTTagString(net.minecraft.nbt.NBTTagString) NBTTagShort(net.minecraft.nbt.NBTTagShort) TypeAdapterFactory(com.google.gson.TypeAdapterFactory) NBTTagFloat(net.minecraft.nbt.NBTTagFloat) NBTTagInt(net.minecraft.nbt.NBTTagInt) JsonWriter(com.google.gson.stream.JsonWriter) BigInteger(java.math.BigInteger) JsonArray(com.google.gson.JsonArray) Type(java.lang.reflect.Type) NBTTagShort(net.minecraft.nbt.NBTTagShort) JsonElement(com.google.gson.JsonElement) JsonSerializationContext(com.google.gson.JsonSerializationContext) NBTTagByte(net.minecraft.nbt.NBTTagByte) TypeAdapter(com.google.gson.TypeAdapter) NBTTagLong(net.minecraft.nbt.NBTTagLong) BigInteger(java.math.BigInteger) JsonObject(com.google.gson.JsonObject) NBTTagByteArray(net.minecraft.nbt.NBTTagByteArray) NBTTagLong(net.minecraft.nbt.NBTTagLong) NBTTagDouble(net.minecraft.nbt.NBTTagDouble)

Aggregations

TypeAdapter (com.google.gson.TypeAdapter)22 JsonReader (com.google.gson.stream.JsonReader)15 JsonWriter (com.google.gson.stream.JsonWriter)15 JsonElement (com.google.gson.JsonElement)11 JsonPrimitive (com.google.gson.JsonPrimitive)9 Map (java.util.Map)9 JsonObject (com.google.gson.JsonObject)8 IOException (java.io.IOException)8 JsonParseException (com.google.gson.JsonParseException)7 Type (java.lang.reflect.Type)7 LinkedHashMap (java.util.LinkedHashMap)6 Gson (com.google.gson.Gson)2 TypeToken (com.google.gson.reflect.TypeToken)2 ArrayList (java.util.ArrayList)2 Nullable (javax.annotation.Nullable)2 Reference (ch.aaap.harvestclient.domain.reference.Reference)1 HarvestRuntimeException (ch.aaap.harvestclient.exception.HarvestRuntimeException)1 ImmutableList (com.google.common.collect.ImmutableList)1 ImmutableMap (com.google.common.collect.ImmutableMap)1 GsonBuilder (com.google.gson.GsonBuilder)1