简体   繁体   中英

How should I create a custom deserializer for Google Storage object?

If i do not make a custom factory this is the error

Unable to invoke no-args constructor for interface com.google.cloud.storage.Storage. Registering an InstanceCreator with Gson for this type may fix this problem.

Here is the code for my Data converter with custom Factory

import com.google.cloud.storage.Storage;
 /**
 * Helper for working with JsonDataConverter for Random service.
 */
public class RandomServiceJsonDataConverterHelper {

    /**
     * Creates json data converter.
*/
        public static JsonDataConverter createWorkflowServiceJsonDataConverter() {
            return new JsonDataConverter(RandomServiceJsonDataConverterHelper::registerFactories);
        }
    
        private static GsonBuilder registerFactories(GsonBuilder gsonBuilder) {
            return gsonBuilder.registerTypeAdapter(Storage.class, new StorageDeserialiser());
        }
    }

And here is the code for the storage deserialiser

public class StorageDeserialiser implements JsonDeserializer<Storage>, JsonSerializer<Storage> {

    @Override
    public Storage deserialize(
        JsonElement jsonElement,
        Type type,
        JsonDeserializationContext jsonDeserializationContext
    ) {
        //what should i do here ?
    }

    @Override
    public JsonElement serialize(Storage storage, Type typeOfSrc, JsonSerializationContext context) {
        Gson gson = new Gson();
        return new JsonPrimitive(gson.toJson(storage));
    }
}

The section with the comment is where I have to add a deserializer for the Storage object. Could someone please help me out with this?

You should not be trying to serialize the authorized service object because it is a functional interface and does not hold data. The Storage object is used to create an authorized service object to which objects are the primitive that GCS uses to save data. The Storage object must be created for each service, to which that interface is used to get and set objects. If one wishes to share the service object, then the concept they are looking for is dependency injection , which allows them to share a single object across logical scopes, but within the same application/environment.

You should follow "Upload objects" , to which they have the ability to call storage.createFrom with inputs a ByteArrayInputStream that could contain a JSON string instead of the String content = "Hello world." used in the example.

A custom deserializer is not needed for GCS objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM