Example usage for com.google.gson JsonDeserializer deserialize

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

Introduction

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

Prototype

public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException;

Source Link

Document

Gson invokes this call-back method during deserialization when it encounters a field of the specified type.

Usage

From source file:net.segoia.event.eventbus.config.json.EventBusJsonConfigLoader.java

License:Apache License

public static EventBusJsonConfig load(Reader reader) {
    GsonBuilder gb = new GsonBuilder();

    gb.registerTypeAdapter(Condition.class, new JsonDeserializer<Condition>() {

        @Override/*w  ww  .j a v a  2  s. com*/
        public Condition deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            JsonObject jo = json.getAsJsonObject();
            JsonElement conditionType = jo.get("ctype");
            String ctype = null;
            if (conditionType != null) {
                ctype = conditionType.getAsString().trim();
                if ("".equals(ctype)) {
                    ctype = null;
                }
            }
            JsonDeserializer<?> deserializerForType = jsonDeserializers.get(ctype);
            if (deserializerForType == null) {
                throw new JsonParseException("No deserializer defined for condition type " + ctype);
            }
            return (Condition) deserializerForType.deserialize(json, typeOfT, context);
        }
    });

    gb.registerTypeAdapterFactory(new TypeAdapterFactory() {

        @Override
        public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
            final TypeAdapter<T> delegateAdapter = gson.getDelegateAdapter(this, type);

            TypeAdapter<T> typeAdapter = new TypeAdapter<T>() {

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

                @Override
                public T read(JsonReader in) throws IOException {
                    JsonElement value = Streams.parse(in);

                    if (value.isJsonNull()) {
                        return null;
                    }

                    if (!value.isJsonObject()) {
                        return delegateAdapter.fromJsonTree(value);
                    }
                    // System.out.println(value+" "+value.getClass());
                    JsonObject jo = value.getAsJsonObject();

                    JsonElement cnameElem = jo.remove("className");

                    if (cnameElem != null) {
                        String cname = cnameElem.getAsString();

                        try {
                            // System.out.println("using clazz " + cname);
                            return (T) gson.fromJson(value, Class.forName(cname));
                        } catch (ClassNotFoundException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            return null;
                        }
                    } else {
                        return delegateAdapter.fromJsonTree(value);
                    }
                }
            };

            return typeAdapter;

        }
    });

    final Gson gson = gb.create();

    EventBusJsonConfig ebusConfig = gson.fromJson(reader, EventBusJsonConfig.class);

    return ebusConfig;
}

From source file:org.apache.rya.indexing.pcj.fluo.app.batch.serializer.BatchInformationTypeAdapter.java

License:Apache License

@Override
public BatchInformation deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2)
        throws JsonParseException {
    try {//from   w ww .  j  av  a  2 s. co m
        JsonObject json = arg0.getAsJsonObject();
        String type = json.get("class").getAsString();
        JsonDeserializer<? extends BatchInformation> deserializer = factory.getDeserializerFromName(type);
        return deserializer.deserialize(arg0, arg1, arg2);
    } catch (Exception e) {
        log.trace("Unable to deserialize JsonElement: " + arg0);
        log.trace("Returning an empty Batch");
        throw new JsonParseException(e);
    }
}

From source file:rest.ws.gson.deserializer.request.EntityRequestDeserializer.java

@Override
public Message deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
        throws JsonParseException {
    JsonObject jsonObject = je.getAsJsonObject();
    if (jsonObject.has(DATA)) {
        try {//  www.j  ava 2s .c o m
            JsonDeserializer<T> deserializer = getEntityDeserializer();
            if (deserializer == null) {
                Log log = new Log.LogBuilder(LogLevel.ERROR).codeKey(String.valueOf(500))
                        .codeStr(NullPointerException.class.getCanonicalName())
                        .userMsg(String.format("You must register an Entity Merge Deserializer for '%s' entity",
                                clazz.getCanonicalName()))
                        .build();
                return new Message.MessageBuilder(getOperationErrorType()).addLog(log).build();
            }
            entity = deserializer.deserialize(jsonObject.get(DATA), clazz, jdc);

            ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
            Validator validator = factory.getValidator();
            Set<ConstraintViolation<T>> uncheckedConstraintViolations = validator.validate(entity);
            if (uncheckedConstraintViolations.size() > 0) {
                List<ConstraintViolation<T>> constraintViolations = new ArrayList<>();

                uncheckedConstraintViolations.stream().forEach((ConstraintViolation<T> constraint) -> {
                    boolean add = true;
                    if (constraint.getConstraintDescriptor().getAnnotation() instanceof NotNull)
                        try {
                            Field field = constraint.getRootBeanClass()
                                    .getDeclaredField(constraint.getPropertyPath().toString());
                            for (Annotation a : field.getDeclaredAnnotations())
                                if (a instanceof GeneratedValue)
                                    add = false;
                        } catch (NoSuchFieldException | SecurityException ex) {
                            Logger.getLogger(EntityRequestDeserializer.class.getName()).log(Level.SEVERE, null,
                                    ex);
                        }
                    if (add)
                        constraintViolations.add(constraint);
                });
                if (constraintViolations.size() > 0) {
                    Message.MessageBuilder messageBuilder = new Message.MessageBuilder(getOperationErrorType());
                    constraintViolations.stream().forEach((constraint) -> {
                        messageBuilder.addLog(new Log.LogBuilder(LogLevel.ERROR).codeKey(String.valueOf(412))
                                .codeStr(ConstraintViolationException.class.getCanonicalName()).userMsg("")
                                .userMsg(String.format("On '%s' entity the property '%s' violates: %s",
                                        constraint.getRootBeanClass().getCanonicalName(),
                                        constraint.getPropertyPath(), constraint.getMessage()))
                                .build());
                    });
                    return messageBuilder.build();
                }
            }

            doEntityAction(createEntityDAO(clazz, entityManager));
            return getResponse();
        } catch (Exception ex) {
            StringWriter errors = new StringWriter();
            ex.printStackTrace(new PrintWriter(errors));
            Log log = new Log.LogBuilder(LogLevel.ERROR).codeKey(String.valueOf(500))
                    .codeStr(ex.getClass().getCanonicalName()).userMsg(errors.toString()).build();
            return new Message.MessageBuilder(getOperationErrorType()).addLog(log).build();
        }

    } else {
        Log log = new Log.LogBuilder(LogLevel.ERROR).codeKey(String.valueOf(400)).codeStr("Bad Request")
                .userMsg(String.format("Request protocol error. The '%s' property is missed", DATA)).build();
        return new Message.MessageBuilder(getOperationErrorType()).addLog(log).build();
    }
}

From source file:rest.ws.gson.deserializer.request.read.ReadRequestDeserializer.java

private StringBuilder configureJPQL(JsonObject jsonData, JsonDeserializationContext jdc,
        String jpqlPredicateType, JsonDeserializer<JPQLPredicate> jpqlPredicateDeserializer,
        String predicateSeparator) {
    StringBuilder builder = new StringBuilder();
    if (jsonData.has(jpqlPredicateType)) {
        JsonArray jsonArray = jsonData.get(jpqlPredicateType).getAsJsonArray();
        baseUri.queryParam(jpqlPredicateType, jsonArray.toString());
        boolean flag = false;
        for (JsonElement filter : jsonArray) {
            JPQLPredicate value = jpqlPredicateDeserializer.deserialize(filter, JPQLPredicate.class, jdc);
            builder.append(String.format("%s %s", flag ? predicateSeparator : "", value.getJpqlPredicate()));
            flag = true;//from  w w  w  .ja  va  2 s .co  m
        }
    }
    return builder;
}