Example usage for com.google.gson JsonDeserializationContext deserialize

List of usage examples for com.google.gson JsonDeserializationContext deserialize

Introduction

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

Prototype

public <T> T deserialize(JsonElement json, Type typeOfT) throws JsonParseException;

Source Link

Document

Invokes default deserialization on the specified object.

Usage

From source file:com.samebug.clients.search.api.json.AbstractObjectAdapter.java

License:Apache License

@Override
public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    if (json == null)
        return null;
    else {/*from  ww  w .java 2s .  c om*/
        JsonObject jsonObject = json.getAsJsonObject();
        JsonElement typeFieldValue = jsonObject.get(typeField);
        if (typeFieldValue == null)
            throw new JsonParseException(
                    "Cannot serialize " + typeOfT + " because the type field" + typeField + " is missing");
        else {
            String type = jsonObject.get(typeField).getAsString();

            for (Map.Entry<String, Class<? extends T>> entry : typeClasses.entrySet()) {
                if (entry.getKey().equals(type))
                    return context.deserialize(jsonObject, entry.getValue());
            }
            throw new JsonParseException("Cannot serialize an abstract " + typeOfT + " with the type " + type);
        }
    }
}

From source file:com.slx.funstream.utils.ChatMessageDeserializer.java

License:Apache License

@Override
public ChatMessage[] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    if (json.isJsonArray()) {
        JsonArray jsonMessages = json.getAsJsonArray();
        ChatMessage[] messages = new ChatMessage[jsonMessages.size()];

        for (int i = 0; i < jsonMessages.size(); i++) {
            JsonObject jsonMessage = jsonMessages.get(i).getAsJsonObject();
            ChatMessage chatMessage = new ChatMessage();
            chatMessage.setId(jsonMessage.get(ID).getAsLong());
            chatMessage.setChannel(jsonMessage.get(CHANNEL).getAsLong());
            chatMessage//from w w  w  .j  a v a  2  s .  c  om
                    .setFrom(context.deserialize(jsonMessage.get(FROM).getAsJsonObject(), CurrentUser.class));
            chatMessage.setTo(context.deserialize(jsonMessage.get(TO).getAsJsonObject(), CurrentUser.class));
            chatMessage.setText(jsonMessage.get(TEXT).getAsString());
            chatMessage.setTime(jsonMessage.get(TIME).getAsString());
            messages[i] = chatMessage;
        }
        return messages;
    }
    return null;

}

From source file:com.slx.funstream.utils.ChatResponseDeserializer.java

License:Apache License

@Override
public ChatResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    JsonObject response = json.getAsJsonObject();
    final String status = response.get(STATUS).getAsString();
    ChatResponse chatResponse = new ChatResponse();
    chatResponse.setStatus(status);/*  ww w  .  ja v  a 2  s.c  om*/
    if (status.equals(APIUtils.OK_STATUS)) {
        // messages
        if (response.has(RESULT) && response.get(RESULT).isJsonArray()) {
            ChatMessage[] messages = context.deserialize(response.get(RESULT), ChatMessage[].class);
            chatResponse.setResult(new Result(Arrays.asList(messages)));
        }

    } else {
        JsonObject result = response.get(RESULT).getAsJsonObject();
        chatResponse.setResult(new Result(result.get(MESSAGE).getAsString()));
    }

    return chatResponse;
}

From source file:com.softwaremagico.tm.json.InterfaceAdapter.java

License:Open Source License

@Override
public T deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext)
        throws JsonParseException {

    JsonObject jsonObject = jsonElement.getAsJsonObject();
    JsonPrimitive prim = (JsonPrimitive) jsonObject.get(JSON_CLASSNAME);
    if (prim == null) {
        return null;
    }//from   w  ww . j  ava2 s .c  o  m
    String className = prim.getAsString();
    return jsonDeserializationContext.deserialize(jsonObject.get(JSON_DATA), getObjectClass(className));
}

From source file:com.solidfire.jsvcgen.serialization.OptionalAdapter.java

License:Open Source License

/**
 * Deserializes an Optional object.//from   w  ww . j  a v a 2 s .  co m
 *
 * @param json    the element to deserialize.
 * @param typeOfT type of the expected return value.
 * @param context Context used for deserialization.
 * @return An Optional object containing an object of type typeOfT.
 */
public Optional<?> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
    if (!json.isJsonObject() && !json.isJsonArray()) {
        if (json.isJsonNull() || json.getAsString() == null) {
            return Optional.empty();
        }
    }

    ParameterizedType pType = (ParameterizedType) typeOfT;
    Type genericType = pType.getActualTypeArguments()[0];

    // Special handling for string, "" will return Optional.of("")
    if (genericType.equals(String.class)) {
        return Optional.of(json.getAsString());
    }

    if (!json.isJsonObject() && !json.isJsonArray() && json.getAsString().trim().length() == 0) {
        return Optional.empty();
    }

    if (json.isJsonObject() || json.isJsonArray()) {
        if (json.isJsonNull()) {
            return Optional.empty();
        }
    }

    if (genericType.equals(Integer.class)) {
        return Optional.of(json.getAsInt());
    } else if (genericType.equals(Long.class)) {
        return Optional.of(json.getAsLong());
    } else if (genericType.equals(Double.class)) {
        return Optional.of(json.getAsDouble());
    }

    // Defer deserialization to handler for type contained in Optional
    Object obj = context.deserialize(json, genericType);
    OptionalAdaptorUtils.initializeAllNullOptionalFieldsAsEmpty(obj);
    return Optional.of(obj);
}

From source file:com.sourceclear.headlines.serialization.ImmutableListDeserializer.java

License:Apache License

public ImmutableList<?> deserialize(JsonElement json, Type type, JsonDeserializationContext context)
        throws JsonParseException {
    final Type type2 = ParameterizedTypeImpl.make(List.class,
            ((ParameterizedType) type).getActualTypeArguments(), null);
    final List<?> list = context.deserialize(json, type2);

    return ImmutableList.copyOf(list);
}

From source file:com.sourceclear.headlines.serialization.ImmutableMapDeserializer.java

License:Apache License

public ImmutableMap<?, ?> deserialize(JsonElement json, Type type, JsonDeserializationContext context)
        throws JsonParseException {
    final Type type2 = ParameterizedTypeImpl.make(Map.class,
            ((ParameterizedType) type).getActualTypeArguments(), null);
    final Map<?, ?> map = context.deserialize(json, type2);

    return ImmutableMap.copyOf(map);
}

From source file:com.splicemachine.derby.ddl.InterfaceSerializer.java

License:Apache License

@Override
public T deserialize(JsonElement elem, Type interfaceType, JsonDeserializationContext context)
        throws JsonParseException {
    final JsonObject wrapper = (JsonObject) elem;
    final JsonElement typeName = get(wrapper, "type");
    final JsonElement data = get(wrapper, "data");
    final Type actualType = typeForName(typeName);
    return context.deserialize(data, actualType);
}

From source file:com.srotya.tau.wraith.actions.ActionSerializer.java

License:Apache License

public Action deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject jsonObject = json.getAsJsonObject();
    if (jsonObject.entrySet().isEmpty()) {
        throw new JsonParseException("Empty action are not allowed");
    }//from www .j a v  a  2s . co m
    String type = jsonObject.get(TYPE).getAsString();
    if (Utils.CLASSNAME_REVERSE_MAP.containsKey(type)) {
        type = Utils.CLASSNAME_REVERSE_MAP.get(type);
    }
    JsonElement element = jsonObject.get(PROPS);
    try {
        Action pojo = context.deserialize(element, Class.forName(type));
        Field[] fields = pojo.getClass().getDeclaredFields();
        for (Field f : fields) {
            if (f.getAnnotation(Required.class) != null) {
                try {
                    f.setAccessible(true);
                    if (f.get(pojo) == null) {
                        throw new JsonParseException("Missing required field in condition: " + f.getName());
                    }
                } catch (IllegalArgumentException | IllegalAccessException ex) {
                }
            }
        }
        return pojo;
    } catch (ClassNotFoundException cnfe) {
        throw new JsonParseException("Unknown action type: " + type, cnfe);
    } catch (NumberFormatException e) {
        throw new JsonParseException("Type must be a number:" + e.getLocalizedMessage());
    }
}

From source file:com.srotya.tau.wraith.conditions.ConditionSerializer.java

License:Apache License

public Condition deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject jsonObject = json.getAsJsonObject();
    if (jsonObject.entrySet().isEmpty()) {
        throw new JsonParseException("Empty conditions are not allowed");
    }//from ww  w  . j av  a  2 s .  c o  m
    String type = jsonObject.get(TYPE).getAsString();
    if (Utils.CLASSNAME_REVERSE_MAP.containsKey(type)) {
        type = Utils.CLASSNAME_REVERSE_MAP.get(type);
    }
    JsonElement element = jsonObject.get(PROPS);
    try {
        Condition pojo = context.deserialize(element, Class.forName(type));
        if (pojo instanceof JavaRegexCondition) {
            JavaRegexCondition regex = ((JavaRegexCondition) pojo);
            if (regex.getValue() == null) {
                throw new JsonParseException("Regex can't be empty");
            } else {
                try {
                    regex.setValue(regex.getValue());
                } catch (PatternSyntaxException e) {
                    throw new JsonParseException("Regex " + regex.getValue() + " is not a valid Java regex");
                }
            }
        }
        List<Field> fields = new ArrayList<>();
        Utils.addDeclaredAndInheritedFields(Class.forName(type), fields);
        for (Field f : fields) {
            if (f.getAnnotation(Required.class) != null) {
                try {
                    f.setAccessible(true);
                    if (f.get(pojo) == null) {
                        throw new JsonParseException("Missing required field in condition: " + f.getName());
                    }
                } catch (IllegalArgumentException | IllegalAccessException ex) {
                }
            }
        }
        return pojo;
    } catch (ClassNotFoundException cnfe) {
        throw new JsonParseException("Unknown condition type: " + type, cnfe);
    }
}