List of usage examples for com.google.gson JsonDeserializationContext deserialize
public <T> T deserialize(JsonElement json, Type typeOfT) throws JsonParseException;
From source file:com.google.gwtjsonrpc.server.MapDeserializer.java
License:Apache License
public Map<Object, Object> deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException { final Type kt = ((ParameterizedType) typeOfT).getActualTypeArguments()[0]; final Type vt = ((ParameterizedType) typeOfT).getActualTypeArguments()[1]; if (json.isJsonNull()) { return null; }/* www. j av a 2 s . c o m*/ if (kt == String.class) { if (!json.isJsonObject()) { throw new JsonParseException("Expected object for map type"); } final JsonObject p = (JsonObject) json; final Map<Object, Object> r = createInstance(typeOfT); for (final Map.Entry<String, JsonElement> e : p.entrySet()) { final Object v = context.deserialize(e.getValue(), vt); r.put(e.getKey(), v); } return r; } else { if (!json.isJsonArray()) { throw new JsonParseException("Expected array for map type"); } final JsonArray p = (JsonArray) json; final Map<Object, Object> r = createInstance(typeOfT); for (int n = 0; n < p.size();) { final Object k = context.deserialize(p.get(n++), kt); final Object v = context.deserialize(p.get(n++), vt); r.put(k, v); } return r; } }
From source file:com.google.mr4c.serialize.json.MetadataEntryBeanDeserializer.java
License:Open Source License
public MetadataEntryBean deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { MetadataElementType elementType = MetadataElementType .valueOf(json.getAsJsonObject().getAsJsonPrimitive("elementType").getAsString()); JsonElement jsonElement = json.getAsJsonObject().get("element"); Class clazz = MetadataBeans.getBeanClass(elementType); MetadataElementBean elementBean = context.deserialize(jsonElement, clazz); return MetadataEntryBean.instance(elementBean, elementType); }
From source file:com.google.nigori.common.TypeAdapterProtobuf.java
License:Apache License
@Override public GeneratedMessage deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject jsonObject = json.getAsJsonObject(); @SuppressWarnings("unchecked") Class<? extends GeneratedMessage> protoClass = (Class<? extends GeneratedMessage>) typeOfT; try {//w ww.j a v a 2s .co m // Invoke the ProtoClass.newBuilder() method Object protoBuilder = getCachedMethod(protoClass, "newBuilder").invoke(null); Class<?> builderClass = protoBuilder.getClass(); Descriptor protoDescriptor = (Descriptor) getCachedMethod(protoClass, "getDescriptor").invoke(null); // Call setters on all of the available fields for (FieldDescriptor fieldDescriptor : protoDescriptor.getFields()) { String name = fieldDescriptor.getName(); if (jsonObject.has(name)) { JsonElement jsonElement = jsonObject.get(name); String fieldName = camelCaseField(name + "_"); Field field = protoClass.getDeclaredField(fieldName); Type fieldType = field.getGenericType(); if (fieldType.equals(Object.class)) { // TODO(drt24): this is very evil. // In NigoriMessages protobuf strings are stored in a field of type Object so that they // can use either String of ByteString as the implementation, however this causes a type // error when calling the set method. So we make a (potentially false) assumption that // all fields of type Object in NigoriMessages have that type because they actually // should have Strings set. fieldType = String.class; } Object fieldValue = context.deserialize(jsonElement, fieldType); if (fieldDescriptor.getJavaType() == FieldDescriptor.JavaType.ENUM) { Method methodVD = getCachedMethod(fieldValue.getClass(), "getValueDescriptor"); fieldValue = methodVD.invoke(fieldValue); } Method method = getCachedMethod(builderClass, "setField", FieldDescriptor.class, Object.class); method.invoke(protoBuilder, fieldDescriptor, fieldValue); } } // Invoke the build method to return the final proto return (GeneratedMessage) getCachedMethod(builderClass, "build").invoke(protoBuilder); } catch (SecurityException e) { throw new JsonParseException(e); } catch (NoSuchMethodException e) { throw new JsonParseException(e); } catch (IllegalArgumentException e) { throw new JsonParseException(e); } catch (IllegalAccessException e) { throw new JsonParseException(e); } catch (InvocationTargetException e) { throw new JsonParseException(e); } catch (NoSuchFieldException e) { throw new JsonParseException(e); } }
From source file:com.google.research.ic.ferret.data.ext.alogger.AccessibilityLogParser.java
License:Open Source License
@Override public Event deserializeEvent(JsonElement json, Type klass, JsonDeserializationContext jdContext) { return jdContext.deserialize(json, AccessibilityLogEvent.class); }
From source file:com.google.wave.api.event.EventSerializer.java
License:Apache License
/** * Deserializes the given {@link JsonObject} into an {@link Event}, and * assign the given {@link Wavelet} to the {@link Event}. * * @param wavelet the wavelet where the event occurred. * @param json the JSON representation of {@link Event}. * @param context the deserialization context. * @return an instance of {@link Event}. * * @throw {@link EventSerializationException} if there is a problem * deserializing the event JSON.//from www.ja v a2 s . co m */ public static Event deserialize(Wavelet wavelet, EventMessageBundle bundle, JsonObject json, JsonDeserializationContext context) throws EventSerializationException { // Construct the event object. String eventTypeString = json.get(TYPE).getAsString(); EventType type = EventType.valueOfIgnoreCase(eventTypeString); if (type == EventType.UNKNOWN) { throw new EventSerializationException( "Trying to deserialize event JSON with unknown " + "type: " + json, json); } // Parse the generic parameters. String modifiedBy = json.get(MODIFIED_BY).getAsString(); Long timestamp = json.get(TIMESTAMP).getAsLong(); // Construct the event object. Class<? extends Event> clazz = type.getClazz(); Constructor<? extends Event> ctor; try { ctor = clazz.getDeclaredConstructor(); ctor.setAccessible(true); Event event = ctor.newInstance(); // Set the default fields from AbstractEvent. Class<?> rootClass = AbstractEvent.class; setField(event, rootClass.getDeclaredField(WAVELET), wavelet); setField(event, rootClass.getDeclaredField(MODIFIED_BY), modifiedBy); setField(event, rootClass.getDeclaredField(TIMESTAMP), timestamp); setField(event, rootClass.getDeclaredField(TYPE), type); setField(event, rootClass.getDeclaredField(BUNDLE), bundle); JsonObject properties = json.get(PROPERTIES).getAsJsonObject(); // Set the blip id field, that can be null for certain events, such as // OPERATION_ERROR. JsonElement blipId = properties.get(BLIP_ID); if (blipId != null && !(blipId instanceof JsonNull)) { setField(event, rootClass.getDeclaredField(BLIP_ID), blipId.getAsString()); } // Set the additional fields. for (Field field : clazz.getDeclaredFields()) { String fieldName = field.getName(); if (properties.has(fieldName)) { setField(event, field, context.deserialize(properties.get(fieldName), field.getGenericType())); } } return event; } catch (NoSuchMethodException e) { throw new EventSerializationException("Unable to deserialize event JSON: " + json, json); } catch (NoSuchFieldException e) { throw new EventSerializationException("Unable to deserialize event JSON: " + json, json); } catch (InstantiationException e) { throw new EventSerializationException("Unable to deserialize event JSON: " + json, json); } catch (IllegalAccessException e) { throw new EventSerializationException("Unable to deserialize event JSON: " + json, json); } catch (InvocationTargetException e) { throw new EventSerializationException("Unable to deserialize event JSON: " + json, json); } catch (JsonParseException e) { throw new EventSerializationException("Unable to deserialize event JSON: " + json, json); } }
From source file:com.google.wave.api.impl.ElementGsonAdaptor.java
License:Apache License
@Override public Element deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { Element result = null;//from ww w.j ava2 s.c o m ElementType type = ElementType.valueOfIgnoreCase(json.getAsJsonObject().get(TYPE_TAG).getAsString()); Map<String, String> properties = context.deserialize(json.getAsJsonObject().get(PROPERTIES_TAG), GsonFactory.STRING_MAP_TYPE); if (FormElement.getFormElementTypes().contains(type)) { result = new FormElement(type, properties); } else if (type == ElementType.GADGET) { result = new Gadget(properties); } else if (type == ElementType.IMAGE) { result = new Image(properties); } else if (type == ElementType.ATTACHMENT) { byte[] data = null; String encodedData = properties.get(Attachment.DATA); if (encodedData != null) { try { data = Base64.decodeBase64(encodedData.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new JsonParseException("Couldn't convert to utf-8", e); } } result = new Attachment(properties, data); } else if (type == ElementType.LINE) { result = new Line(properties); } else { result = new Element(type, properties); } return result; }
From source file:com.google.wave.api.impl.EventMessageBundleGsonAdaptor.java
License:Apache License
@Override public EventMessageBundle deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject jsonObj = json.getAsJsonObject(); String robotAddress = jsonObj.get(ROBOT_ADDRESS_TAG).getAsString(); String rpcServerUrl = ""; if (jsonObj.has(RPC_SERVER_URL_TAG)) { rpcServerUrl = jsonObj.get(RPC_SERVER_URL_TAG).getAsString(); }// ww w .ja v a 2s .c o m EventMessageBundle result = new EventMessageBundle(robotAddress, rpcServerUrl); OperationQueue operationQueue; if (jsonObj.has(PROXYING_FOR_TAG)) { result.setProxyingFor(jsonObj.get(PROXYING_FOR_TAG).getAsString()); operationQueue = new OperationQueue(new ArrayList<OperationRequest>(), result.getProxyingFor()); } else { operationQueue = new OperationQueue(); } // Deserialize wavelet. WaveletData waveletData = context.deserialize(jsonObj.get(WAVELET_TAG), WaveletData.class); result.setWaveletData(waveletData); Map<String, Blip> blips = new HashMap<String, Blip>(); Map<String, BlipThread> threads = new HashMap<String, BlipThread>(); Wavelet wavelet = Wavelet.deserialize(operationQueue, blips, threads, waveletData); wavelet.setRobotAddress(robotAddress); result.setWavelet(wavelet); // Deserialize threads. Map<String, BlipThread> tempThreads = context.deserialize(jsonObj.get(THREADS_TAG), GsonFactory.THREAD_MAP_TYPE); for (Entry<String, BlipThread> entry : tempThreads.entrySet()) { BlipThread thread = entry.getValue(); threads.put(entry.getKey(), new BlipThread(thread.getId(), thread.getLocation(), thread.getBlipIds(), blips)); } // Deserialize blips. Map<String, BlipData> blipDatas = context.deserialize(jsonObj.get(BLIPS_TAG), GsonFactory.BLIP_MAP_TYPE); result.setBlipData(blipDatas); for (Entry<String, BlipData> entry : blipDatas.entrySet()) { blips.put(entry.getKey(), Blip.deserialize(operationQueue, wavelet, entry.getValue())); } // Deserialize events. JsonArray eventsArray = jsonObj.get(EVENTS_TAG).getAsJsonArray(); List<Event> events = new ArrayList<Event>(eventsArray.size()); for (JsonElement element : eventsArray) { JsonObject eventObject = element.getAsJsonObject(); try { events.add(EventSerializer.deserialize(wavelet, result, eventObject, context)); } catch (EventSerializationException e) { throw new JsonParseException(e.getMessage()); } } result.setEvents(events); return result; }
From source file:com.google.wave.api.impl.JsonRpcResponseGsonAdaptor.java
License:Apache License
@Override public JsonRpcResponse deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { JsonObject jsonObject = json.getAsJsonObject(); String id = jsonObject.get(ResponseProperty.ID.key()).getAsString(); if (jsonObject.has(ResponseProperty.ERROR.key())) { JsonElement errorObject = jsonObject.get(ResponseProperty.ERROR.key()); String errorMessage = errorObject.getAsJsonObject().get("message").getAsString(); return JsonRpcResponse.error(id, errorMessage); }//from w w w . ja va2 s . co m // Deserialize the data. Map<ParamsProperty, Object> properties = new HashMap<ParamsProperty, Object>(); JsonElement data = jsonObject.get(ResponseProperty.DATA.key()); if (data != null && data.isJsonObject()) { for (Entry<String, JsonElement> parameter : data.getAsJsonObject().entrySet()) { ParamsProperty parameterType = ParamsProperty.fromKey(parameter.getKey()); if (parameterType == null) { // Skip this unknown parameter. continue; } Object object = null; if (parameterType == ParamsProperty.BLIPS) { object = context.deserialize(parameter.getValue(), GsonFactory.BLIP_MAP_TYPE); } else if (parameterType == ParamsProperty.PARTICIPANTS_ADDED || parameterType == ParamsProperty.PARTICIPANTS_REMOVED) { object = context.deserialize(parameter.getValue(), GsonFactory.PARTICIPANT_LIST_TYPE); } else if (parameterType == ParamsProperty.THREADS) { object = context.deserialize(parameter.getValue(), GsonFactory.THREAD_MAP_TYPE); } else if (parameterType == ParamsProperty.WAVELET_IDS) { object = context.deserialize(parameter.getValue(), GsonFactory.WAVELET_ID_LIST_TYPE); } else if (parameterType == ParamsProperty.RAW_DELTAS) { object = context.deserialize(parameter.getValue(), GsonFactory.RAW_DELTAS_TYPE); } else { object = context.deserialize(parameter.getValue(), parameterType.clazz()); } properties.put(parameterType, object); } } return JsonRpcResponse.result(id, properties); }
From source file:com.google.wave.api.impl.OperationRequestGsonAdaptor.java
License:Apache License
@Override public OperationRequest deserialize(JsonElement json, Type type, JsonDeserializationContext ctx) throws JsonParseException { JsonObject jsonObject = json.getAsJsonObject(); JsonObject parameters = jsonObject.getAsJsonObject(RequestProperty.PARAMS.key()); OperationRequest request = new OperationRequest(jsonObject.get(RequestProperty.METHOD.key()).getAsString(), jsonObject.get(RequestProperty.ID.key()).getAsString(), getPropertyAsStringThenRemove(parameters, ParamsProperty.WAVE_ID), getPropertyAsStringThenRemove(parameters, ParamsProperty.WAVELET_ID), getPropertyAsStringThenRemove(parameters, ParamsProperty.BLIP_ID)); for (Entry<String, JsonElement> parameter : parameters.entrySet()) { ParamsProperty parameterType = ParamsProperty.fromKey(parameter.getKey()); if (parameterType != null) { Object object;// w w w.ja va 2s .com if (parameterType == ParamsProperty.RAW_DELTAS) { object = ctx.deserialize(parameter.getValue(), GsonFactory.RAW_DELTAS_TYPE); } else { object = ctx.deserialize(parameter.getValue(), parameterType.clazz()); } request.addParameter(Parameter.of(parameterType, object)); } } return request; }
From source file:com.graphhopper.json.FeatureJsonDeserializer.java
License:Apache License
@Override public JsonFeature deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { try {//from w ww. j av a 2s. c o m JsonObject obj = json.getAsJsonObject(); String id, strType = null; Map<String, Object> properties = null; BBox bbox = null; Geometry geometry = null; // TODO ensure uniqueness if (obj.has("id")) id = obj.get("id").getAsString(); else id = UUID.randomUUID().toString(); if (obj.has("properties")) { properties = context.deserialize(obj.get("properties"), Map.class); } if (obj.has("bbox")) bbox = parseBBox(obj.get("bbox").getAsJsonArray()); if (obj.has("geometry")) { JsonObject geometryJson = obj.get("geometry").getAsJsonObject(); if (geometryJson.has("coordinates")) { if (!geometryJson.has("type")) throw new IllegalArgumentException("No type for non-empty coordinates specified"); strType = context.deserialize(geometryJson.get("type"), String.class); if ("Point".equals(strType)) { JsonArray arr = geometryJson.get("coordinates").getAsJsonArray(); double lon = arr.get(0).getAsDouble(); double lat = arr.get(1).getAsDouble(); if (arr.size() == 3) geometry = new Point(lat, lon, arr.get(2).getAsDouble()); else geometry = new Point(lat, lon); } else if ("MultiPoint".equals(strType)) { geometry = parseLineString(geometryJson); } else if ("LineString".equals(strType)) { geometry = parseLineString(geometryJson); } else { throw new IllegalArgumentException("Coordinates type " + strType + " not yet supported"); } } } return new JsonFeature(id, strType, bbox, geometry, properties); } catch (Exception ex) { throw new JsonParseException("Problem parsing JSON feature " + json); } }