Example usage for com.google.gson TypeAdapter TypeAdapter

List of usage examples for com.google.gson TypeAdapter TypeAdapter

Introduction

In this page you can find the example usage for com.google.gson TypeAdapter TypeAdapter.

Prototype

TypeAdapter

Source Link

Usage

From source file:BundleTypeAdapterFactory.java

License:Apache License

@SuppressWarnings("unchecked")
@Override//w w  w  . j a  v a 2 s.  c o m
public <T> TypeAdapter<T> create(final Gson gson, TypeToken<T> type) {
    if (!Bundle.class.isAssignableFrom(type.getRawType())) {
        return null;
    }
    return (TypeAdapter<T>) new TypeAdapter<Bundle>() {
        @Override
        public void write(JsonWriter out, Bundle bundle) throws IOException {
            if (bundle == null) {
                out.nullValue();
                return;
            }
            out.beginObject();
            for (String key : bundle.keySet()) {
                out.name(key);
                Object value = bundle.get(key);
                if (value == null) {
                    out.nullValue();
                } else {
                    gson.toJson(value, value.getClass(), out);
                }
            }
            out.endObject();
        }

        @Override
        public Bundle read(JsonReader in) throws IOException {
            switch (in.peek()) {
            case NULL:
                in.nextNull();
                return null;
            case BEGIN_OBJECT:
                return toBundle(readObject(in));
            default:
                throw new IOException("expecting object: " + in.getPath());
            }
        }

        private Bundle toBundle(List<Pair<String, Object>> values) throws IOException {
            Bundle bundle = new Bundle();
            for (Pair<String, Object> entry : values) {
                String key = entry.first;
                Object value = entry.second;
                if (value instanceof String) {
                    bundle.putString(key, (String) value);
                } else if (value instanceof Integer) {
                    bundle.putInt(key, ((Integer) value).intValue());
                } else if (value instanceof Long) {
                    bundle.putLong(key, ((Long) value).longValue());
                } else if (value instanceof Double) {
                    bundle.putDouble(key, ((Double) value).doubleValue());
                } else if (value instanceof Parcelable) {
                    bundle.putParcelable(key, (Parcelable) value);
                } else if (value instanceof List) {
                    List<Pair<String, Object>> objectValues = (List<Pair<String, Object>>) value;
                    Bundle subBundle = toBundle(objectValues);
                    bundle.putParcelable(key, subBundle);
                } else {
                    throw new IOException("Unparcelable key, value: " + key + ", " + value);
                }
            }
            return bundle;
        }

        private List<Pair<String, Object>> readObject(JsonReader in) throws IOException {
            List<Pair<String, Object>> object = new ArrayList<Pair<String, Object>>();
            in.beginObject();
            while (in.peek() != JsonToken.END_OBJECT) {
                switch (in.peek()) {
                case NAME:
                    String name = in.nextName();
                    Object value = readValue(in);
                    object.add(new Pair<String, Object>(name, value));
                    break;
                case END_OBJECT:
                    break;
                default:
                    throw new IOException("expecting object: " + in.getPath());
                }
            }
            in.endObject();
            return object;
        }

        private Object readValue(JsonReader in) throws IOException {
            switch (in.peek()) {
            case BEGIN_ARRAY:
                return readArray(in);
            case BEGIN_OBJECT:
                return readObject(in);
            case BOOLEAN:
                return in.nextBoolean();
            case NULL:
                in.nextNull();
                return null;
            case NUMBER:
                return readNumber(in);
            case STRING:
                return in.nextString();
            default:
                throw new IOException("expecting value: " + in.getPath());
            }
        }

        private Object readNumber(JsonReader in) throws IOException {
            double doubleValue = in.nextDouble();
            if (doubleValue - Math.ceil(doubleValue) == 0) {
                long longValue = (long) doubleValue;
                if (longValue >= Integer.MIN_VALUE && longValue <= Integer.MAX_VALUE) {
                    return (int) longValue;
                }
                return longValue;
            }
            return doubleValue;
        }

        @SuppressWarnings("rawtypes")
        private List readArray(JsonReader in) throws IOException {
            List list = new ArrayList();
            in.beginArray();
            while (in.peek() != JsonToken.END_ARRAY) {
                Object element = readValue(in);
                list.add(element);
            }
            in.endArray();
            return list;
        }
    };
}

From source file:RestrictSerializationToBaseClassFactory.java

License:Apache License

@Override
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
    Class incoming = type.getRawType();
    if (subClasses != null) {
        boolean matched = false;
        for (Class<? extends B> subClass : subClasses) {
            if (incoming == subClass) {
                matched = true;//from w  w w  . j av a 2 s .com
                break;
            }
        }
        if (!matched)
            return null;
    } else { // restricting all sub-classes since none specified
        // don't match the baseClass since we want to use the default factory for it
        if (incoming == baseClass || !baseClass.isAssignableFrom(incoming))
            return null;
    }
    TypeAdapter<T> adapter = new TypeAdapter<T>() {
        @Override
        public T read(JsonReader reader) throws IOException {
            final TypeAdapter subAdapter = gson.getDelegateAdapter(RestrictSerializationToBaseClassFactory.this,
                    type);
            return (T) subAdapter.read(reader);
        }

        @Override
        public void write(JsonWriter writer, T value) throws IOException {
            final TypeAdapter<B> baseAdapter = gson.getAdapter(baseClass);
            baseAdapter.write(writer, (B) value);
        }
    };
    return adapter;
}

From source file:ca.ualberta.cs.team1travelexpenseapp.gsonUtils.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (type.getRawType() != baseType) {
        return null;
    }/*from w w w .  ja v  a  2  s .co m*/

    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();
            @SuppressWarnings("unchecked") // registration requires that subtype extends T
            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);
            @SuppressWarnings("unchecked") // registration requires that subtype extends T
            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);
        }
    };
}

From source file:cc.kave.commons.utils.json.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (type.getRawType() != baseType) {
        return null;
    }// ww  w.  ja  v a 2  s . co m

    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);
            // (kave adaptation) was: ".remove(typeFiledName)"
            JsonElement labelJsonElement = jsonElement.getAsJsonObject().get(typeFieldName);
            if (labelJsonElement == null) {
                throw new JsonParseException("cannot deserialize " + baseType
                        + " because it does not define a field named " + typeFieldName);
            }
            String label = labelJsonElement.getAsString();
            @SuppressWarnings("unchecked") // registration requires that
            // subtype extends T
            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 {
            if (value == null) {
                Streams.write(null, out);
                return;
            }
            Class<?> srcType = value.getClass();
            String label = subtypeToLabel.get(srcType);
            @SuppressWarnings("unchecked") // registration requires that
            // subtype extends T
            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();
            // (kave adaptation) disabled check
            // 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);
        }
    };
}

From source file:co.aurasphere.botmill.kik.util.json.LowerCaseTypeAdapterFactory.java

License:Open Source License

public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
    final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);

    return new TypeAdapter<T>() {

        @Override//from w  ww .j a va 2 s  .c  o m
        public T read(JsonReader in) throws IOException {
            JsonElement tree = elementAdapter.read(in);
            afterRead(tree);
            return delegate.fromJsonTree(tree);
        }

        @Override
        public void write(JsonWriter out, T value) throws IOException {
            JsonElement tree = delegate.toJsonTree(value);
            beforeWrite(value, tree);
            elementAdapter.write(out, tree);
        }

        protected void beforeWrite(T source, JsonElement toSerialize) {
        }

        protected void afterRead(JsonElement deserialized) {
            if (deserialized instanceof JsonObject) {
                JsonObject jsonObject = ((JsonObject) deserialized);
                Set<Map.Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
                for (Map.Entry<String, JsonElement> entry : entrySet) {
                    if (entry.getValue() instanceof JsonElement) {
                        if (entry.getKey().equalsIgnoreCase("type")) {
                            String val = jsonObject.get(entry.getKey()).toString();
                            jsonObject.addProperty(entry.getKey(), val.toLowerCase());
                        }
                    } else {
                        afterRead(entry.getValue());
                    }
                }
            }
        }
    };
}

From source file:co.cask.cdap.common.io.CaseInsensitiveEnumTypeAdapterFactory.java

License:Apache License

public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    @SuppressWarnings("unchecked")
    Class<T> rawType = (Class<T>) type.getRawType();
    if (!rawType.isEnum()) {
        return null;
    }/*from   w  ww.ja va 2  s  . c  om*/

    final Map<String, T> lowercaseToConstant = new HashMap<>();
    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(toLowercase(reader.nextString()));
            }
        }
    };
}

From source file:co.forsaken.projectindigo.utils.mojangtokens.EnumTypeAdapterFactory.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override//from   w ww.j  a va2 s.co  m
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    if (!type.getRawType().isEnum()) {
        return null;
    }
    final Map<String, T> map = new HashMap<String, T>();
    for (T c : (T[]) type.getRawType().getEnumConstants()) {
        map.put(c.toString().toLowerCase(Locale.US), c);
    }

    return new TypeAdapter<T>() {
        @Override
        public T read(JsonReader reader) throws IOException {
            if (reader.peek() == JsonToken.NULL) {
                reader.nextNull();
                return null;
            }
            String name = reader.nextString();
            if (name == null) {
                return null;
            }
            return map.get(name.toLowerCase(Locale.US));
        }

        @Override
        public void write(JsonWriter writer, T value) throws IOException {
            if (value == null) {
                writer.nullValue();
            } else {
                writer.value(value.toString().toLowerCase(Locale.US));
            }
        }
    };
}

From source file:com.atlauncher.workers.EnumTypeAdapterFactory.java

License:Creative Commons License

@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    if (!type.getRawType().isEnum())
        return null;
    final Map<String, T> map = new HashMap<String, T>();
    for (T c : (T[]) type.getRawType().getEnumConstants()) {
        map.put(c.toString().toLowerCase(Locale.US), c);
    }//from ww  w. ja va  2 s  . c  o  m

    return new TypeAdapter<T>() {
        @Override
        public T read(JsonReader reader) throws IOException {
            if (reader.peek() == JsonToken.NULL) {
                reader.nextNull();
                return null;
            }
            String name = reader.nextString();
            if (name == null)
                return null;
            return map.get(name.toLowerCase(Locale.US));
        }

        @Override
        public void write(JsonWriter writer, T value) throws IOException {
            if (value == null) {
                writer.nullValue();
            } else {
                writer.value(value.toString().toLowerCase(Locale.US));
            }
        }
    };
}

From source file:com.codefororlando.streettrees.api.deserializer.ResponseSanitizer.java

License:Open Source License

@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
    return new TypeAdapter<T>() {
        public void write(JsonWriter out, T value) throws IOException {
            delegate.write(out, value);//  w  ww . j  a va 2  s  .  c om
        }

        public T read(JsonReader in) throws IOException {
            T parsedObject = delegate.read(in);

            // NOTE(jpr): Tree names come in with errant whitespace, and its easiest to fix it here
            // rather than fighting retrofit during deserialization
            if (parsedObject instanceof Tree) {
                Tree tree = (Tree) parsedObject;
                tree.setTreeName(tree.getTreeName().trim());
            }

            return parsedObject;
        }
    };
}

From source file:com.continuuity.loom.codec.json.LowercaseEnumTypeAdapterFactory.java

License:Apache License

public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    Class<T> rawType = (Class<T>) type.getRawType();
    if (!rawType.isEnum()) {
        return null;
    }/*from w w  w .jav  a2  s .co m*/

    final Map<String, T> lowercaseToConstant = Maps.newHashMap();
    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 {
                String next = reader.nextString();
                return lowercaseToConstant.get(next);
            }
        }
    };
}